ZhiQiang Fan | 39f9722 | 2013-09-20 04:49:44 +0800 | [diff] [blame] | 1 | # Copyright 2012 OpenStack Foundation |
Brant Knudson | c7ca334 | 2013-03-28 21:08:50 -0500 | [diff] [blame] | 2 | # Copyright 2013 IBM Corp. |
Jay Pipes | 3f981df | 2012-03-27 18:59:44 -0400 | [diff] [blame] | 3 | # 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 Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 17 | import collections |
Sean Dague | 9986262 | 2014-03-19 18:41:38 -0400 | [diff] [blame] | 18 | import inspect |
Matthew Treinish | a83a16e | 2012-12-07 13:44:02 -0500 | [diff] [blame] | 19 | import json |
Dan Smith | ba6cb16 | 2012-08-14 07:22:42 -0700 | [diff] [blame] | 20 | from lxml import etree |
Attila Fazekas | 11d2a77 | 2013-01-29 17:46:52 +0100 | [diff] [blame] | 21 | import re |
Eoghan Glynn | a559897 | 2012-03-01 09:27:17 -0500 | [diff] [blame] | 22 | import time |
Jay Pipes | 3f981df | 2012-03-27 18:59:44 -0400 | [diff] [blame] | 23 | |
Chris Yeoh | c266b28 | 2014-03-13 18:19:00 +1030 | [diff] [blame] | 24 | import jsonschema |
| 25 | |
Mate Lakat | 23a58a3 | 2013-08-23 02:06:22 +0100 | [diff] [blame] | 26 | from tempest.common import http |
Matthew Treinish | 684d899 | 2014-01-30 16:27:40 +0000 | [diff] [blame] | 27 | from tempest import config |
Daryl Walleck | ed8bef3 | 2011-12-05 23:02:08 -0600 | [diff] [blame] | 28 | from tempest import exceptions |
Matthew Treinish | f4a9b0f | 2013-07-26 16:58:26 -0400 | [diff] [blame] | 29 | from tempest.openstack.common import log as logging |
Masayuki Igawa | 1edf94f | 2014-03-04 18:34:16 +0900 | [diff] [blame] | 30 | from tempest.services.compute.xml import common |
Daryl Walleck | 1465d61 | 2011-11-02 02:22:15 -0500 | [diff] [blame] | 31 | |
Matthew Treinish | 684d899 | 2014-01-30 16:27:40 +0000 | [diff] [blame] | 32 | CONF = config.CONF |
| 33 | |
Eoghan Glynn | a559897 | 2012-03-01 09:27:17 -0500 | [diff] [blame] | 34 | # redrive rate limited calls at most twice |
| 35 | MAX_RECURSION_DEPTH = 2 |
Attila Fazekas | 11d2a77 | 2013-01-29 17:46:52 +0100 | [diff] [blame] | 36 | TOKEN_CHARS_RE = re.compile('^[-A-Za-z0-9+/=]*$') |
Eoghan Glynn | a559897 | 2012-03-01 09:27:17 -0500 | [diff] [blame] | 37 | |
Attila Fazekas | 54a4286 | 2013-07-28 22:31:06 +0200 | [diff] [blame] | 38 | # All the successful HTTP status codes from RFC 2616 |
| 39 | HTTP_SUCCESS = (200, 201, 202, 203, 204, 205, 206) |
| 40 | |
Eoghan Glynn | a559897 | 2012-03-01 09:27:17 -0500 | [diff] [blame] | 41 | |
Daryl Walleck | 1465d61 | 2011-11-02 02:22:15 -0500 | [diff] [blame] | 42 | class RestClient(object): |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 43 | |
Dan Smith | ba6cb16 | 2012-08-14 07:22:42 -0700 | [diff] [blame] | 44 | TYPE = "json" |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 45 | |
| 46 | # This is used by _parse_resp method |
| 47 | # Redefine it for purposes of your xml service client |
| 48 | # List should contain top-xml_tag-names of data, which is like list/array |
| 49 | # For example, in keystone it is users, roles, tenants and services |
| 50 | # All of it has children with same tag-names |
| 51 | list_tags = [] |
| 52 | |
| 53 | # This is used by _parse_resp method too |
| 54 | # Used for selection of dict-like xmls, |
| 55 | # like metadata for Vms in nova, and volumes in cinder |
| 56 | dict_tags = ["metadata", ] |
| 57 | |
Attila Fazekas | 11d2a77 | 2013-01-29 17:46:52 +0100 | [diff] [blame] | 58 | LOG = logging.getLogger(__name__) |
Daryl Walleck | 1465d61 | 2011-11-02 02:22:15 -0500 | [diff] [blame] | 59 | |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 60 | def __init__(self, auth_provider): |
| 61 | self.auth_provider = auth_provider |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 62 | |
JordanP | 5d29b2c | 2013-12-18 13:56:03 +0000 | [diff] [blame] | 63 | self.endpoint_url = None |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 64 | self.service = None |
| 65 | # The version of the API this client implements |
| 66 | self.api_version = None |
| 67 | self._skip_path = False |
Matthew Treinish | 684d899 | 2014-01-30 16:27:40 +0000 | [diff] [blame] | 68 | self.build_interval = CONF.compute.build_interval |
| 69 | self.build_timeout = CONF.compute.build_timeout |
Attila Fazekas | 72c7a5f | 2012-12-03 17:17:23 +0100 | [diff] [blame] | 70 | self.general_header_lc = set(('cache-control', 'connection', |
| 71 | 'date', 'pragma', 'trailer', |
| 72 | 'transfer-encoding', 'via', |
| 73 | 'warning')) |
| 74 | self.response_header_lc = set(('accept-ranges', 'age', 'etag', |
| 75 | 'location', 'proxy-authenticate', |
| 76 | 'retry-after', 'server', |
| 77 | 'vary', 'www-authenticate')) |
Matthew Treinish | 684d899 | 2014-01-30 16:27:40 +0000 | [diff] [blame] | 78 | dscv = CONF.identity.disable_ssl_certificate_validation |
Mate Lakat | 23a58a3 | 2013-08-23 02:06:22 +0100 | [diff] [blame] | 79 | self.http_obj = http.ClosingHttp( |
| 80 | disable_ssl_certificate_validation=dscv) |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 81 | |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 82 | def _get_type(self): |
| 83 | return self.TYPE |
| 84 | |
| 85 | def get_headers(self, accept_type=None, send_type=None): |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 86 | if accept_type is None: |
| 87 | accept_type = self._get_type() |
| 88 | if send_type is None: |
| 89 | send_type = self._get_type() |
| 90 | return {'Content-Type': 'application/%s' % send_type, |
| 91 | 'Accept': 'application/%s' % accept_type} |
| 92 | |
DennyZhang | 7be7500 | 2013-09-19 06:55:11 -0500 | [diff] [blame] | 93 | def __str__(self): |
| 94 | STRING_LIMIT = 80 |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 95 | str_format = ("config:%s, service:%s, base_url:%s, " |
| 96 | "filters: %s, build_interval:%s, build_timeout:%s" |
DennyZhang | 7be7500 | 2013-09-19 06:55:11 -0500 | [diff] [blame] | 97 | "\ntoken:%s..., \nheaders:%s...") |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 98 | return str_format % (CONF, self.service, self.base_url, |
| 99 | self.filters, self.build_interval, |
| 100 | self.build_timeout, |
DennyZhang | 7be7500 | 2013-09-19 06:55:11 -0500 | [diff] [blame] | 101 | str(self.token)[0:STRING_LIMIT], |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 102 | str(self.get_headers())[0:STRING_LIMIT]) |
DennyZhang | 7be7500 | 2013-09-19 06:55:11 -0500 | [diff] [blame] | 103 | |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 104 | def _get_region(self, service): |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 105 | """ |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 106 | Returns the region for a specific service |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 107 | """ |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 108 | service_region = None |
| 109 | for cfgname in dir(CONF._config): |
| 110 | # Find all config.FOO.catalog_type and assume FOO is a service. |
| 111 | cfg = getattr(CONF, cfgname) |
| 112 | catalog_type = getattr(cfg, 'catalog_type', None) |
| 113 | if catalog_type == service: |
| 114 | service_region = getattr(cfg, 'region', None) |
| 115 | if not service_region: |
| 116 | service_region = CONF.identity.region |
| 117 | return service_region |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 118 | |
JordanP | 5d29b2c | 2013-12-18 13:56:03 +0000 | [diff] [blame] | 119 | def _get_endpoint_type(self, service): |
| 120 | """ |
| 121 | Returns the endpoint type for a specific service |
| 122 | """ |
| 123 | # If the client requests a specific endpoint type, then be it |
| 124 | if self.endpoint_url: |
| 125 | return self.endpoint_url |
| 126 | endpoint_type = None |
| 127 | for cfgname in dir(CONF._config): |
| 128 | # Find all config.FOO.catalog_type and assume FOO is a service. |
| 129 | cfg = getattr(CONF, cfgname) |
| 130 | catalog_type = getattr(cfg, 'catalog_type', None) |
| 131 | if catalog_type == service: |
| 132 | endpoint_type = getattr(cfg, 'endpoint_type', 'publicURL') |
| 133 | break |
| 134 | # Special case for compute v3 service which hasn't its own |
| 135 | # configuration group |
| 136 | else: |
| 137 | if service == CONF.compute.catalog_v3_type: |
| 138 | endpoint_type = CONF.compute.endpoint_type |
| 139 | return endpoint_type |
| 140 | |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 141 | @property |
| 142 | def user(self): |
| 143 | return self.auth_provider.credentials.get('username', None) |
Li Ma | 216550f | 2013-06-12 11:26:08 -0700 | [diff] [blame] | 144 | |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 145 | @property |
| 146 | def tenant_name(self): |
| 147 | return self.auth_provider.credentials.get('tenant_name', None) |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 148 | |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 149 | @property |
| 150 | def password(self): |
| 151 | return self.auth_provider.credentials.get('password', None) |
| 152 | |
| 153 | @property |
| 154 | def base_url(self): |
| 155 | return self.auth_provider.base_url(filters=self.filters) |
| 156 | |
| 157 | @property |
Andrea Frittoli | 77f9da4 | 2014-02-06 11:18:19 +0000 | [diff] [blame] | 158 | def token(self): |
| 159 | return self.auth_provider.get_token() |
| 160 | |
| 161 | @property |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 162 | def filters(self): |
| 163 | _filters = dict( |
| 164 | service=self.service, |
JordanP | 5d29b2c | 2013-12-18 13:56:03 +0000 | [diff] [blame] | 165 | endpoint_type=self._get_endpoint_type(self.service), |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 166 | region=self._get_region(self.service) |
| 167 | ) |
| 168 | if self.api_version is not None: |
| 169 | _filters['api_version'] = self.api_version |
| 170 | if self._skip_path: |
| 171 | _filters['skip_path'] = self._skip_path |
| 172 | return _filters |
| 173 | |
| 174 | def skip_path(self): |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 175 | """ |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 176 | When set, ignore the path part of the base URL from the catalog |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 177 | """ |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 178 | self._skip_path = True |
chris fattarsi | 5098fa2 | 2012-04-17 13:27:00 -0700 | [diff] [blame] | 179 | |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 180 | def reset_path(self): |
Attila Fazekas | b2902af | 2013-02-16 16:22:44 +0100 | [diff] [blame] | 181 | """ |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 182 | When reset, use the base URL from the catalog as-is |
Daryl Walleck | 1465d61 | 2011-11-02 02:22:15 -0500 | [diff] [blame] | 183 | """ |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 184 | self._skip_path = False |
Brant Knudson | c7ca334 | 2013-03-28 21:08:50 -0500 | [diff] [blame] | 185 | |
Attila Fazekas | 54a4286 | 2013-07-28 22:31:06 +0200 | [diff] [blame] | 186 | def expected_success(self, expected_code, read_code): |
| 187 | assert_msg = ("This function only allowed to use for HTTP status" |
| 188 | "codes which explicitly defined in the RFC 2616. {0}" |
| 189 | " is not a defined Success Code!").format(expected_code) |
| 190 | assert expected_code in HTTP_SUCCESS, assert_msg |
| 191 | |
| 192 | # NOTE(afazekas): the http status code above 400 is processed by |
| 193 | # the _error_checker method |
| 194 | if read_code < 400 and read_code != expected_code: |
| 195 | pattern = """Unexpected http success status code {0}, |
| 196 | The expected status code is {1}""" |
| 197 | details = pattern.format(read_code, expected_code) |
| 198 | raise exceptions.InvalidHttpSuccessCode(details) |
| 199 | |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 200 | def post(self, url, body, headers=None): |
Daryl Walleck | 1465d61 | 2011-11-02 02:22:15 -0500 | [diff] [blame] | 201 | return self.request('POST', url, headers, body) |
| 202 | |
Attila Fazekas | b8aa759 | 2013-01-26 01:25:45 +0100 | [diff] [blame] | 203 | def get(self, url, headers=None): |
| 204 | return self.request('GET', url, headers) |
Daryl Walleck | 1465d61 | 2011-11-02 02:22:15 -0500 | [diff] [blame] | 205 | |
Daisuke Morita | 499bba3 | 2013-11-28 18:44:49 +0900 | [diff] [blame] | 206 | def delete(self, url, headers=None, body=None): |
| 207 | return self.request('DELETE', url, headers, body) |
Daryl Walleck | 1465d61 | 2011-11-02 02:22:15 -0500 | [diff] [blame] | 208 | |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 209 | def patch(self, url, body, headers=None): |
rajalakshmi-ganesan | ab42672 | 2013-02-08 15:49:15 +0530 | [diff] [blame] | 210 | return self.request('PATCH', url, headers, body) |
| 211 | |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 212 | def put(self, url, body, headers=None): |
Daryl Walleck | 1465d61 | 2011-11-02 02:22:15 -0500 | [diff] [blame] | 213 | return self.request('PUT', url, headers, body) |
| 214 | |
dwalleck | 5d73443 | 2012-10-04 01:11:47 -0500 | [diff] [blame] | 215 | def head(self, url, headers=None): |
Larisa Ustalov | 6c3c780 | 2012-11-05 12:25:19 +0200 | [diff] [blame] | 216 | return self.request('HEAD', url, headers) |
| 217 | |
| 218 | def copy(self, url, headers=None): |
| 219 | return self.request('COPY', url, headers) |
dwalleck | 5d73443 | 2012-10-04 01:11:47 -0500 | [diff] [blame] | 220 | |
Matthew Treinish | c0f768f | 2013-03-11 14:24:16 -0400 | [diff] [blame] | 221 | def get_versions(self): |
| 222 | resp, body = self.get('') |
| 223 | body = self._parse_resp(body) |
Matthew Treinish | c0f768f | 2013-03-11 14:24:16 -0400 | [diff] [blame] | 224 | versions = map(lambda x: x['id'], body) |
| 225 | return resp, versions |
| 226 | |
Sean Dague | 9986262 | 2014-03-19 18:41:38 -0400 | [diff] [blame] | 227 | def _find_caller(self): |
| 228 | """Find the caller class and test name. |
| 229 | |
| 230 | Because we know that the interesting things that call us are |
| 231 | test_* methods, and various kinds of setUp / tearDown, we |
| 232 | can look through the call stack to find appropriate methods, |
| 233 | and the class we were in when those were called. |
| 234 | """ |
| 235 | caller_name = None |
| 236 | names = [] |
| 237 | frame = inspect.currentframe() |
| 238 | is_cleanup = False |
| 239 | # Start climbing the ladder until we hit a good method |
| 240 | while True: |
| 241 | try: |
| 242 | frame = frame.f_back |
| 243 | name = frame.f_code.co_name |
| 244 | names.append(name) |
| 245 | if re.search("^(test_|setUp|tearDown)", name): |
| 246 | cname = "" |
| 247 | if 'self' in frame.f_locals: |
| 248 | cname = frame.f_locals['self'].__class__.__name__ |
| 249 | if 'cls' in frame.f_locals: |
| 250 | cname = frame.f_locals['cls'].__name__ |
| 251 | caller_name = cname + ":" + name |
| 252 | break |
| 253 | elif re.search("^_run_cleanup", name): |
| 254 | is_cleanup = True |
| 255 | else: |
| 256 | cname = "" |
| 257 | if 'self' in frame.f_locals: |
| 258 | cname = frame.f_locals['self'].__class__.__name__ |
| 259 | if 'cls' in frame.f_locals: |
| 260 | cname = frame.f_locals['cls'].__name__ |
| 261 | |
| 262 | # the fact that we are running cleanups is indicated pretty |
| 263 | # deep in the stack, so if we see that we want to just |
| 264 | # start looking for a real class name, and declare victory |
| 265 | # once we do. |
| 266 | if is_cleanup and cname: |
| 267 | if not re.search("^RunTest", cname): |
| 268 | caller_name = cname + ":_run_cleanups" |
| 269 | break |
| 270 | except Exception: |
| 271 | break |
| 272 | # prevents frame leaks |
| 273 | del frame |
| 274 | if caller_name is None: |
| 275 | self.LOG.debug("Sane call name not found in %s" % names) |
| 276 | return caller_name |
| 277 | |
Sean Dague | 89a8591 | 2014-03-19 16:37:29 -0400 | [diff] [blame] | 278 | def _get_request_id(self, resp): |
| 279 | for i in ('x-openstack-request-id', 'x-compute-request-id'): |
| 280 | if i in resp: |
| 281 | return resp[i] |
| 282 | return "" |
Attila Fazekas | 11d2a77 | 2013-01-29 17:46:52 +0100 | [diff] [blame] | 283 | |
Sean Dague | 0cc4757 | 2014-03-20 07:34:05 -0400 | [diff] [blame^] | 284 | def _log_request(self, method, req_url, resp, secs=""): |
| 285 | # if we have the request id, put it in the right part of the log |
Sean Dague | 89a8591 | 2014-03-19 16:37:29 -0400 | [diff] [blame] | 286 | extra = dict(request_id=self._get_request_id(resp)) |
Sean Dague | 0cc4757 | 2014-03-20 07:34:05 -0400 | [diff] [blame^] | 287 | # NOTE(sdague): while we still have 6 callers to this function |
| 288 | # we're going to just provide work around on who is actually |
| 289 | # providing timings by gracefully adding no content if they don't. |
| 290 | # Once we're down to 1 caller, clean this up. |
| 291 | if secs: |
| 292 | secs = " %.3fs" % secs |
Sean Dague | 89a8591 | 2014-03-19 16:37:29 -0400 | [diff] [blame] | 293 | self.LOG.info( |
Sean Dague | 0cc4757 | 2014-03-20 07:34:05 -0400 | [diff] [blame^] | 294 | 'Request (%s): %s %s %s%s' % ( |
Sean Dague | 9986262 | 2014-03-19 18:41:38 -0400 | [diff] [blame] | 295 | self._find_caller(), |
Sean Dague | 89a8591 | 2014-03-19 16:37:29 -0400 | [diff] [blame] | 296 | resp['status'], |
| 297 | method, |
Sean Dague | 0cc4757 | 2014-03-20 07:34:05 -0400 | [diff] [blame^] | 298 | req_url, |
| 299 | secs), |
Sean Dague | 89a8591 | 2014-03-19 16:37:29 -0400 | [diff] [blame] | 300 | extra=extra) |
Daryl Walleck | 8a707db | 2012-01-25 00:46:24 -0600 | [diff] [blame] | 301 | |
Dan Smith | ba6cb16 | 2012-08-14 07:22:42 -0700 | [diff] [blame] | 302 | def _parse_resp(self, body): |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 303 | if self._get_type() is "json": |
| 304 | body = json.loads(body) |
| 305 | |
| 306 | # We assume, that if the first value of the deserialized body's |
| 307 | # item set is a dict or a list, that we just return the first value |
| 308 | # of deserialized body. |
| 309 | # Essentially "cutting out" the first placeholder element in a body |
| 310 | # that looks like this: |
| 311 | # |
| 312 | # { |
| 313 | # "users": [ |
| 314 | # ... |
| 315 | # ] |
| 316 | # } |
| 317 | try: |
| 318 | # Ensure there are not more than one top-level keys |
| 319 | if len(body.keys()) > 1: |
| 320 | return body |
| 321 | # Just return the "wrapped" element |
| 322 | first_key, first_item = body.items()[0] |
| 323 | if isinstance(first_item, (dict, list)): |
| 324 | return first_item |
| 325 | except (ValueError, IndexError): |
| 326 | pass |
| 327 | return body |
| 328 | elif self._get_type() is "xml": |
| 329 | element = etree.fromstring(body) |
| 330 | if any(s in element.tag for s in self.dict_tags): |
| 331 | # Parse dictionary-like xmls (metadata, etc) |
| 332 | dictionary = {} |
| 333 | for el in element.getchildren(): |
| 334 | dictionary[u"%s" % el.get("key")] = u"%s" % el.text |
| 335 | return dictionary |
| 336 | if any(s in element.tag for s in self.list_tags): |
| 337 | # Parse list-like xmls (users, roles, etc) |
| 338 | array = [] |
| 339 | for child in element.getchildren(): |
Masayuki Igawa | 1edf94f | 2014-03-04 18:34:16 +0900 | [diff] [blame] | 340 | array.append(common.xml_to_json(child)) |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 341 | return array |
| 342 | |
| 343 | # Parse one-item-like xmls (user, role, etc) |
Masayuki Igawa | 1edf94f | 2014-03-04 18:34:16 +0900 | [diff] [blame] | 344 | return common.xml_to_json(element) |
Dan Smith | ba6cb16 | 2012-08-14 07:22:42 -0700 | [diff] [blame] | 345 | |
Attila Fazekas | 836e478 | 2013-01-29 15:40:13 +0100 | [diff] [blame] | 346 | def response_checker(self, method, url, headers, body, resp, resp_body): |
| 347 | if (resp.status in set((204, 205, 304)) or resp.status < 200 or |
Pavel Sedlák | e267eba | 2013-04-03 15:56:36 +0200 | [diff] [blame] | 348 | method.upper() == 'HEAD') and resp_body: |
Attila Fazekas | 836e478 | 2013-01-29 15:40:13 +0100 | [diff] [blame] | 349 | raise exceptions.ResponseWithNonEmptyBody(status=resp.status) |
Attila Fazekas | c3a095b | 2013-08-17 09:15:44 +0200 | [diff] [blame] | 350 | # NOTE(afazekas): |
Attila Fazekas | 836e478 | 2013-01-29 15:40:13 +0100 | [diff] [blame] | 351 | # If the HTTP Status Code is 205 |
| 352 | # 'The response MUST NOT include an entity.' |
| 353 | # A HTTP entity has an entity-body and an 'entity-header'. |
| 354 | # In the HTTP response specification (Section 6) the 'entity-header' |
| 355 | # 'generic-header' and 'response-header' are in OR relation. |
| 356 | # All headers not in the above two group are considered as entity |
| 357 | # header in every interpretation. |
| 358 | |
| 359 | if (resp.status == 205 and |
| 360 | 0 != len(set(resp.keys()) - set(('status',)) - |
| 361 | self.response_header_lc - self.general_header_lc)): |
| 362 | raise exceptions.ResponseWithEntity() |
Attila Fazekas | c3a095b | 2013-08-17 09:15:44 +0200 | [diff] [blame] | 363 | # NOTE(afazekas) |
Attila Fazekas | 836e478 | 2013-01-29 15:40:13 +0100 | [diff] [blame] | 364 | # Now the swift sometimes (delete not empty container) |
| 365 | # returns with non json error response, we can create new rest class |
| 366 | # for swift. |
| 367 | # Usually RFC2616 says error responses SHOULD contain an explanation. |
| 368 | # The warning is normal for SHOULD/SHOULD NOT case |
| 369 | |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 370 | # Likely it will cause an error |
| 371 | if not resp_body and resp.status >= 400: |
Attila Fazekas | 11d2a77 | 2013-01-29 17:46:52 +0100 | [diff] [blame] | 372 | self.LOG.warning("status >= 400 response with empty body") |
Attila Fazekas | 836e478 | 2013-01-29 15:40:13 +0100 | [diff] [blame] | 373 | |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 374 | def _request(self, method, url, headers=None, body=None): |
Daryl Walleck | e5b83d4 | 2011-11-10 14:39:02 -0600 | [diff] [blame] | 375 | """A simple HTTP request interface.""" |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 376 | # Authenticate the request with the auth provider |
| 377 | req_url, req_headers, req_body = self.auth_provider.auth_request( |
| 378 | method, url, headers, body, self.filters) |
Sean Dague | 89a8591 | 2014-03-19 16:37:29 -0400 | [diff] [blame] | 379 | |
Sean Dague | 0cc4757 | 2014-03-20 07:34:05 -0400 | [diff] [blame^] | 380 | # Do the actual request, and time it |
| 381 | start = time.time() |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 382 | resp, resp_body = self.http_obj.request( |
| 383 | req_url, method, headers=req_headers, body=req_body) |
Sean Dague | 0cc4757 | 2014-03-20 07:34:05 -0400 | [diff] [blame^] | 384 | end = time.time() |
| 385 | self._log_request(method, req_url, resp, secs=(end - start)) |
Andrea Frittoli | 8bbdb16 | 2014-01-06 11:06:13 +0000 | [diff] [blame] | 386 | # Verify HTTP response codes |
| 387 | self.response_checker(method, url, req_headers, req_body, resp, |
| 388 | resp_body) |
Attila Fazekas | 72c7a5f | 2012-12-03 17:17:23 +0100 | [diff] [blame] | 389 | |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 390 | return resp, resp_body |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 391 | |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 392 | def request(self, method, url, headers=None, body=None): |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 393 | retry = 0 |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 394 | |
| 395 | if headers is None: |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 396 | # NOTE(vponomaryov): if some client do not need headers, |
| 397 | # it should explicitly pass empty dict |
| 398 | headers = self.get_headers() |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 399 | |
| 400 | resp, resp_body = self._request(method, url, |
| 401 | headers=headers, body=body) |
| 402 | |
| 403 | while (resp.status == 413 and |
| 404 | 'retry-after' in resp and |
| 405 | not self.is_absolute_limit( |
| 406 | resp, self._parse_resp(resp_body)) and |
| 407 | retry < MAX_RECURSION_DEPTH): |
| 408 | retry += 1 |
| 409 | delay = int(resp['retry-after']) |
| 410 | time.sleep(delay) |
| 411 | resp, resp_body = self._request(method, url, |
| 412 | headers=headers, body=body) |
| 413 | self._error_checker(method, url, headers, body, |
| 414 | resp, resp_body) |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 415 | return resp, resp_body |
| 416 | |
| 417 | def _error_checker(self, method, url, |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 418 | headers, body, resp, resp_body): |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 419 | |
| 420 | # NOTE(mtreinish): Check for httplib response from glance_http. The |
| 421 | # object can't be used here because importing httplib breaks httplib2. |
| 422 | # If another object from a class not imported were passed here as |
| 423 | # resp this could possibly fail |
| 424 | if str(type(resp)) == "<type 'instance'>": |
| 425 | ctype = resp.getheader('content-type') |
| 426 | else: |
| 427 | try: |
| 428 | ctype = resp['content-type'] |
| 429 | # NOTE(mtreinish): Keystone delete user responses doesn't have a |
| 430 | # content-type header. (They don't have a body) So just pretend it |
| 431 | # is set. |
| 432 | except KeyError: |
| 433 | ctype = 'application/json' |
| 434 | |
Attila Fazekas | e72b7cd | 2013-03-26 18:34:21 +0100 | [diff] [blame] | 435 | # It is not an error response |
| 436 | if resp.status < 400: |
| 437 | return |
| 438 | |
Sergey Murashov | c10cca5 | 2014-01-16 12:48:47 +0400 | [diff] [blame] | 439 | JSON_ENC = ['application/json', 'application/json; charset=utf-8'] |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 440 | # NOTE(mtreinish): This is for compatibility with Glance and swift |
| 441 | # APIs. These are the return content types that Glance api v1 |
| 442 | # (and occasionally swift) are using. |
Sergey Murashov | c10cca5 | 2014-01-16 12:48:47 +0400 | [diff] [blame] | 443 | TXT_ENC = ['text/plain', 'text/html', 'text/html; charset=utf-8', |
| 444 | 'text/plain; charset=utf-8'] |
| 445 | XML_ENC = ['application/xml', 'application/xml; charset=utf-8'] |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 446 | |
Sergey Murashov | c10cca5 | 2014-01-16 12:48:47 +0400 | [diff] [blame] | 447 | if ctype.lower() in JSON_ENC or ctype.lower() in XML_ENC: |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 448 | parse_resp = True |
Sergey Murashov | c10cca5 | 2014-01-16 12:48:47 +0400 | [diff] [blame] | 449 | elif ctype.lower() in TXT_ENC: |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 450 | parse_resp = False |
| 451 | else: |
vponomaryov | 6cb6d19 | 2014-03-07 09:39:05 +0200 | [diff] [blame] | 452 | raise exceptions.InvalidContentType(str(resp.status)) |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 453 | |
Rohit Karajgi | 6b1e154 | 2012-05-14 05:55:54 -0700 | [diff] [blame] | 454 | if resp.status == 401 or resp.status == 403: |
Daryl Walleck | ced8eb8 | 2012-03-19 13:52:37 -0500 | [diff] [blame] | 455 | raise exceptions.Unauthorized() |
Jay Pipes | 5135bfc | 2012-01-05 15:46:49 -0500 | [diff] [blame] | 456 | |
| 457 | if resp.status == 404: |
Daryl Walleck | 8a707db | 2012-01-25 00:46:24 -0600 | [diff] [blame] | 458 | raise exceptions.NotFound(resp_body) |
Jay Pipes | 5135bfc | 2012-01-05 15:46:49 -0500 | [diff] [blame] | 459 | |
Daryl Walleck | adea1fa | 2011-11-15 18:36:39 -0600 | [diff] [blame] | 460 | if resp.status == 400: |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 461 | if parse_resp: |
| 462 | resp_body = self._parse_resp(resp_body) |
David Kranz | 28e35c5 | 2012-07-10 10:14:38 -0400 | [diff] [blame] | 463 | raise exceptions.BadRequest(resp_body) |
Daryl Walleck | adea1fa | 2011-11-15 18:36:39 -0600 | [diff] [blame] | 464 | |
David Kranz | 5a23d86 | 2012-02-14 09:48:55 -0500 | [diff] [blame] | 465 | if resp.status == 409: |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 466 | if parse_resp: |
| 467 | resp_body = self._parse_resp(resp_body) |
Anju5 | c3e510c | 2013-10-18 06:40:29 +0530 | [diff] [blame] | 468 | raise exceptions.Conflict(resp_body) |
David Kranz | 5a23d86 | 2012-02-14 09:48:55 -0500 | [diff] [blame] | 469 | |
Daryl Walleck | ed8bef3 | 2011-12-05 23:02:08 -0600 | [diff] [blame] | 470 | if resp.status == 413: |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 471 | if parse_resp: |
| 472 | resp_body = self._parse_resp(resp_body) |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 473 | if self.is_absolute_limit(resp, resp_body): |
| 474 | raise exceptions.OverLimit(resp_body) |
| 475 | else: |
| 476 | raise exceptions.RateLimitExceeded(resp_body) |
Brian Lamar | 12d9b29 | 2011-12-08 12:41:21 -0500 | [diff] [blame] | 477 | |
Wangpan | a9b54c6 | 2013-02-28 11:04:32 +0800 | [diff] [blame] | 478 | if resp.status == 422: |
| 479 | if parse_resp: |
| 480 | resp_body = self._parse_resp(resp_body) |
| 481 | raise exceptions.UnprocessableEntity(resp_body) |
| 482 | |
Daryl Walleck | ed8bef3 | 2011-12-05 23:02:08 -0600 | [diff] [blame] | 483 | if resp.status in (500, 501): |
Matthew Treinish | 7e5a3ec | 2013-02-08 13:53:58 -0500 | [diff] [blame] | 484 | message = resp_body |
| 485 | if parse_resp: |
Rohan Kanade | 433994a | 2013-12-05 22:34:07 +0530 | [diff] [blame] | 486 | try: |
| 487 | resp_body = self._parse_resp(resp_body) |
| 488 | except ValueError: |
| 489 | # If response body is a non-json string message. |
| 490 | # Use resp_body as is and raise InvalidResponseBody |
| 491 | # exception. |
| 492 | raise exceptions.InvalidHTTPResponseBody(message) |
| 493 | else: |
vponomaryov | 6cb6d19 | 2014-03-07 09:39:05 +0200 | [diff] [blame] | 494 | if isinstance(resp_body, dict): |
| 495 | # I'm seeing both computeFault |
| 496 | # and cloudServersFault come back. |
| 497 | # Will file a bug to fix, but leave as is for now. |
| 498 | if 'cloudServersFault' in resp_body: |
| 499 | message = resp_body['cloudServersFault']['message'] |
| 500 | elif 'computeFault' in resp_body: |
| 501 | message = resp_body['computeFault']['message'] |
| 502 | elif 'error' in resp_body: # Keystone errors |
| 503 | message = resp_body['error']['message'] |
| 504 | raise exceptions.IdentityError(message) |
| 505 | elif 'message' in resp_body: |
| 506 | message = resp_body['message'] |
| 507 | else: |
| 508 | message = resp_body |
Dan Prince | a4b709c | 2012-10-10 12:27:59 -0400 | [diff] [blame] | 509 | |
Anju5 | c3e510c | 2013-10-18 06:40:29 +0530 | [diff] [blame] | 510 | raise exceptions.ServerFault(message) |
Daryl Walleck | ed8bef3 | 2011-12-05 23:02:08 -0600 | [diff] [blame] | 511 | |
David Kranz | 5a23d86 | 2012-02-14 09:48:55 -0500 | [diff] [blame] | 512 | if resp.status >= 400: |
vponomaryov | 6cb6d19 | 2014-03-07 09:39:05 +0200 | [diff] [blame] | 513 | raise exceptions.UnexpectedResponseCode(str(resp.status)) |
David Kranz | 5a23d86 | 2012-02-14 09:48:55 -0500 | [diff] [blame] | 514 | |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 515 | def is_absolute_limit(self, resp, resp_body): |
| 516 | if (not isinstance(resp_body, collections.Mapping) or |
Pavel Sedlák | e267eba | 2013-04-03 15:56:36 +0200 | [diff] [blame] | 517 | 'retry-after' not in resp): |
Attila Fazekas | 55f6d8c | 2013-03-10 10:32:54 +0100 | [diff] [blame] | 518 | return True |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 519 | if self._get_type() is "json": |
| 520 | over_limit = resp_body.get('overLimit', None) |
| 521 | if not over_limit: |
| 522 | return True |
| 523 | return 'exceed' in over_limit.get('message', 'blabla') |
| 524 | elif self._get_type() is "xml": |
| 525 | return 'exceed' in resp_body.get('message', 'blabla') |
rajalakshmi-ganesan | 0275a0d | 2013-01-11 18:26:05 +0530 | [diff] [blame] | 526 | |
David Kranz | 6aceb4a | 2012-06-05 14:05:45 -0400 | [diff] [blame] | 527 | def wait_for_resource_deletion(self, id): |
Sean Dague | f237ccb | 2013-01-04 15:19:14 -0500 | [diff] [blame] | 528 | """Waits for a resource to be deleted.""" |
David Kranz | 6aceb4a | 2012-06-05 14:05:45 -0400 | [diff] [blame] | 529 | start_time = int(time.time()) |
| 530 | while True: |
| 531 | if self.is_resource_deleted(id): |
| 532 | return |
| 533 | if int(time.time()) - start_time >= self.build_timeout: |
| 534 | raise exceptions.TimeoutException |
| 535 | time.sleep(self.build_interval) |
| 536 | |
| 537 | def is_resource_deleted(self, id): |
| 538 | """ |
| 539 | Subclasses override with specific deletion detection. |
| 540 | """ |
Attila Fazekas | d236b4e | 2013-01-26 00:44:12 +0100 | [diff] [blame] | 541 | message = ('"%s" does not implement is_resource_deleted' |
| 542 | % self.__class__.__name__) |
| 543 | raise NotImplementedError(message) |
Dan Smith | ba6cb16 | 2012-08-14 07:22:42 -0700 | [diff] [blame] | 544 | |
Chris Yeoh | c266b28 | 2014-03-13 18:19:00 +1030 | [diff] [blame] | 545 | @classmethod |
| 546 | def validate_response(cls, schema, resp, body): |
| 547 | # Only check the response if the status code is a success code |
| 548 | # TODO(cyeoh): Eventually we should be able to verify that a failure |
| 549 | # code if it exists is something that we expect. This is explicitly |
| 550 | # declared in the V3 API and so we should be able to export this in |
| 551 | # the response schema. For now we'll ignore it. |
| 552 | if str(resp.status).startswith('2'): |
| 553 | response_code = schema['status_code'] |
| 554 | if resp.status not in response_code: |
| 555 | msg = ("The status code(%s) is different than the expected " |
| 556 | "one(%s)") % (resp.status, response_code) |
| 557 | raise exceptions.InvalidHttpSuccessCode(msg) |
| 558 | response_schema = schema.get('response_body') |
| 559 | if response_schema: |
| 560 | try: |
| 561 | jsonschema.validate(body, response_schema) |
| 562 | except jsonschema.ValidationError as ex: |
| 563 | msg = ("HTTP response body is invalid (%s)") % ex |
| 564 | raise exceptions.InvalidHTTPResponseBody(msg) |
| 565 | else: |
| 566 | if body: |
| 567 | msg = ("HTTP response body should not exist (%s)") % body |
| 568 | raise exceptions.InvalidHTTPResponseBody(msg) |
| 569 | |
Dan Smith | ba6cb16 | 2012-08-14 07:22:42 -0700 | [diff] [blame] | 570 | |
Marc Koderer | 24eb89c | 2014-01-31 11:23:33 +0100 | [diff] [blame] | 571 | class NegativeRestClient(RestClient): |
| 572 | """ |
| 573 | Version of RestClient that does not raise exceptions. |
| 574 | """ |
| 575 | def _error_checker(self, method, url, |
| 576 | headers, body, resp, resp_body): |
| 577 | pass |
| 578 | |
| 579 | def send_request(self, method, url_template, resources, body=None): |
| 580 | url = url_template % tuple(resources) |
| 581 | if method == "GET": |
| 582 | resp, body = self.get(url) |
| 583 | elif method == "POST": |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 584 | resp, body = self.post(url, body) |
Marc Koderer | 24eb89c | 2014-01-31 11:23:33 +0100 | [diff] [blame] | 585 | elif method == "PUT": |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 586 | resp, body = self.put(url, body) |
Marc Koderer | 24eb89c | 2014-01-31 11:23:33 +0100 | [diff] [blame] | 587 | elif method == "PATCH": |
vponomaryov | 67b58fe | 2014-02-06 19:05:41 +0200 | [diff] [blame] | 588 | resp, body = self.patch(url, body) |
Marc Koderer | 24eb89c | 2014-01-31 11:23:33 +0100 | [diff] [blame] | 589 | elif method == "HEAD": |
| 590 | resp, body = self.head(url) |
| 591 | elif method == "DELETE": |
| 592 | resp, body = self.delete(url) |
| 593 | elif method == "COPY": |
| 594 | resp, body = self.copy(url) |
| 595 | else: |
| 596 | assert False |
| 597 | |
| 598 | return resp, body |