blob: f23310fbf6719ddb82ff77ac5b457b2aa60a1a38 [file] [log] [blame]
Yuiko Takadab6527002015-12-07 11:49:12 +09001# Licensed under the Apache License, Version 2.0 (the "License"); you may
2# not use this file except in compliance with the License. You may obtain
3# a copy of the License at
4#
5# http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10# License for the specific language governing permissions and limitations
11# under the License.
12
Yuiko Takadab6527002015-12-07 11:49:12 +090013
Takashi Kajinami6bddaab2022-05-10 00:58:56 +090014import functools
15from http import client as http_client
16from urllib import parse as urllib_parse
17
Yuiko Takadab6527002015-12-07 11:49:12 +090018from oslo_serialization import jsonutils as json
Yuiko Takadaff785002015-12-17 15:56:42 +090019from tempest.lib.common import api_version_utils
Lenny Verkhovsky88625042016-03-08 17:44:00 +020020from tempest.lib.common import rest_client
Yuiko Takadab6527002015-12-07 11:49:12 +090021
Vasyl Saienko4ddbeec2017-01-20 16:26:04 +000022# NOTE(vsaienko): concurrent tests work because they are launched in
23# separate processes so global variables are not shared among them.
Yuiko Takadaff785002015-12-17 15:56:42 +090024BAREMETAL_MICROVERSION = None
25
Yuiko Takadab6527002015-12-07 11:49:12 +090026
Vasyl Saienko4ddbeec2017-01-20 16:26:04 +000027def set_baremetal_api_microversion(baremetal_microversion):
28 global BAREMETAL_MICROVERSION
29 BAREMETAL_MICROVERSION = baremetal_microversion
30
31
32def reset_baremetal_api_microversion():
33 global BAREMETAL_MICROVERSION
34 BAREMETAL_MICROVERSION = None
35
36
Yuiko Takadab6527002015-12-07 11:49:12 +090037def handle_errors(f):
38 """A decorator that allows to ignore certain types of errors."""
39
Takashi Kajinami6bddaab2022-05-10 00:58:56 +090040 @functools.wraps(f)
Yuiko Takadab6527002015-12-07 11:49:12 +090041 def wrapper(*args, **kwargs):
42 param_name = 'ignore_errors'
43 ignored_errors = kwargs.get(param_name, tuple())
44
45 if param_name in kwargs:
46 del kwargs[param_name]
47
48 try:
49 return f(*args, **kwargs)
50 except ignored_errors:
51 # Silently ignore errors
52 pass
53
54 return wrapper
55
56
57class BaremetalClient(rest_client.RestClient):
58 """Base Tempest REST client for Ironic API."""
59
Yuiko Takadaff785002015-12-17 15:56:42 +090060 api_microversion_header_name = 'X-OpenStack-Ironic-API-Version'
Yuiko Takadab6527002015-12-07 11:49:12 +090061 uri_prefix = ''
62
Yuiko Takadaff785002015-12-17 15:56:42 +090063 def get_headers(self):
64 headers = super(BaremetalClient, self).get_headers()
65 if BAREMETAL_MICROVERSION:
Julia Kreger0eb9ae72024-03-26 08:47:26 -070066 # NOTE(TheJulia): This is not great, because it can blind a test
67 # to the actual version supported.
Yuiko Takadaff785002015-12-17 15:56:42 +090068 headers[self.api_microversion_header_name] = BAREMETAL_MICROVERSION
69 return headers
70
Julia Kreger0eb9ae72024-03-26 08:47:26 -070071 def get_raw_headers(self):
72 """A proper get headers without guessing the microversion."""
73 return super(BaremetalClient, self).get_headers()
74
75 def get_min_max_api_microversions(self):
76 """Returns a tuple of minimum and remote microversions."""
77 _, resp_body = self._show_request(None, uri='/')
78 version = resp_body.get('default_version', {})
79 api_min = version.get('min_version')
80 api_max = version.get('version')
81 return (api_min, api_max)
82
Vasyl Saienkof20979c2016-05-27 11:25:01 +030083 def request(self, *args, **kwargs):
84 resp, resp_body = super(BaremetalClient, self).request(*args, **kwargs)
Riccardo Pittau441c5062020-03-30 15:06:28 +020085 latest_microversion = api_version_utils.LATEST_MICROVERSION
86 if (BAREMETAL_MICROVERSION
87 and BAREMETAL_MICROVERSION != latest_microversion):
Yuiko Takadaff785002015-12-17 15:56:42 +090088 api_version_utils.assert_version_header_matches_request(
89 self.api_microversion_header_name,
90 BAREMETAL_MICROVERSION,
91 resp)
92 return resp, resp_body
93
Yuiko Takadab6527002015-12-07 11:49:12 +090094 def serialize(self, object_dict):
95 """Serialize an Ironic object."""
96
97 return json.dumps(object_dict)
98
99 def deserialize(self, object_str):
100 """Deserialize an Ironic object."""
101
102 return json.loads(object_str)
103
Dmitry Tantsure7548052018-07-16 17:48:32 +0200104 def _get_uri(self, resource_name, uuid=None, permanent=False,
105 params=None):
Yuiko Takadab6527002015-12-07 11:49:12 +0900106 """Get URI for a specific resource or object.
107
108 :param resource_name: The name of the REST resource, e.g., 'nodes'.
109 :param uuid: The unique identifier of an object in UUID format.
110 :returns: Relative URI for the resource or object.
111
112 """
113 prefix = self.uri_prefix if not permanent else ''
Dmitry Tantsure7548052018-07-16 17:48:32 +0200114 if params:
115 params = '?' + '&'.join('%s=%s' % tpl for tpl in params.items())
116 else:
117 params = ''
Yuiko Takadab6527002015-12-07 11:49:12 +0900118
Dmitry Tantsure7548052018-07-16 17:48:32 +0200119 return '{pref}/{res}{uuid}{params}'.format(
120 pref=prefix, res=resource_name,
121 uuid='/%s' % uuid if uuid else '',
122 params=params)
Yuiko Takadab6527002015-12-07 11:49:12 +0900123
124 def _make_patch(self, allowed_attributes, **kwargs):
125 """Create a JSON patch according to RFC 6902.
126
127 :param allowed_attributes: An iterable object that contains a set of
128 allowed attributes for an object.
129 :param **kwargs: Attributes and new values for them.
130 :returns: A JSON path that sets values of the specified attributes to
131 the new ones.
132
133 """
134 def get_change(kwargs, path='/'):
Luong Anh Tuane22fbe12016-09-12 16:32:14 +0700135 for name, value in kwargs.items():
Yuiko Takadab6527002015-12-07 11:49:12 +0900136 if isinstance(value, dict):
137 for ch in get_change(value, path + '%s/' % name):
138 yield ch
139 else:
140 if value is None:
141 yield {'path': path + name,
142 'op': 'remove'}
143 else:
144 yield {'path': path + name,
145 'value': value,
146 'op': 'replace'}
147
148 patch = [ch for ch in get_change(kwargs)
149 if ch['path'].lstrip('/') in allowed_attributes]
150
151 return patch
152
Sam Betts462e9e62016-11-30 18:43:35 +0000153 def _list_request(self, resource, permanent=False, headers=None,
154 extra_headers=False, **kwargs):
Yuiko Takadab6527002015-12-07 11:49:12 +0900155 """Get the list of objects of the specified type.
156
157 :param resource: The name of the REST resource, e.g., 'nodes'.
Sam Betts462e9e62016-11-30 18:43:35 +0000158 :param headers: List of headers to use in request.
159 :param extra_headers: Specify whether to use headers.
Yuiko Takadab6527002015-12-07 11:49:12 +0900160 :param **kwargs: Parameters for the request.
161 :returns: A tuple with the server response and deserialized JSON list
162 of objects
163
164 """
165 uri = self._get_uri(resource, permanent=permanent)
166 if kwargs:
Takashi Kajinami6bddaab2022-05-10 00:58:56 +0900167 uri += "?%s" % urllib_parse.urlencode(kwargs)
Yuiko Takadab6527002015-12-07 11:49:12 +0900168
Sam Betts462e9e62016-11-30 18:43:35 +0000169 resp, body = self.get(uri, headers=headers,
170 extra_headers=extra_headers)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600171 self.expected_success(http_client.OK, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900172
173 return resp, self.deserialize(body)
174
SofiiaAndriichenko569f0a42016-12-08 05:02:17 -0500175 def _show_request(self,
176 resource,
177 uuid=None,
178 permanent=False,
Mark Goddard56399cc2018-02-16 13:37:25 +0000179 headers=None,
180 extra_headers=False,
SofiiaAndriichenko569f0a42016-12-08 05:02:17 -0500181 **kwargs):
Yuiko Takadab6527002015-12-07 11:49:12 +0900182 """Gets a specific object of the specified type.
183
184 :param uuid: Unique identifier of the object in UUID format.
Mark Goddard56399cc2018-02-16 13:37:25 +0000185 :param headers: List of headers to use in request.
186 :param extra_headers: Specify whether to use headers.
Yuiko Takadab6527002015-12-07 11:49:12 +0900187 :returns: Serialized object as a dictionary.
188
189 """
190 if 'uri' in kwargs:
191 uri = kwargs['uri']
192 else:
193 uri = self._get_uri(resource, uuid=uuid, permanent=permanent)
Mark Goddard56399cc2018-02-16 13:37:25 +0000194 resp, body = self.get(uri, headers=headers,
195 extra_headers=extra_headers)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600196 self.expected_success(http_client.OK, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900197
198 return resp, self.deserialize(body)
199
200 def _create_request(self, resource, object_dict):
201 """Create an object of the specified type.
202
203 :param resource: The name of the REST resource, e.g., 'nodes'.
204 :param object_dict: A Python dict that represents an object of the
205 specified type.
206 :returns: A tuple with the server response and the deserialized created
207 object.
208
209 """
210 body = self.serialize(object_dict)
211 uri = self._get_uri(resource)
212
213 resp, body = self.post(uri, body=body)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600214 self.expected_success(http_client.CREATED, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900215
216 return resp, self.deserialize(body)
217
Sam Betts462e9e62016-11-30 18:43:35 +0000218 def _create_request_no_response_body(self, resource, object_dict):
219 """Create an object of the specified type.
220
221 Do not expect any body in the response.
222
223 :param resource: The name of the REST resource, e.g., 'nodes'.
224 :param object_dict: A Python dict that represents an object of the
225 specified type.
226 :returns: The server response.
227 """
228
229 body = self.serialize(object_dict)
230 uri = self._get_uri(resource)
231
232 resp, body = self.post(uri, body=body)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600233 self.expected_success(http_client.NO_CONTENT, resp.status)
Sam Betts462e9e62016-11-30 18:43:35 +0000234
235 return resp
236
Yolanda Roblaabd90112018-05-15 17:11:54 +0200237 def _delete_request(self, resource, uuid,
238 expected_status=http_client.NO_CONTENT):
Yuiko Takadab6527002015-12-07 11:49:12 +0900239 """Delete specified object.
240
241 :param resource: The name of the REST resource, e.g., 'nodes'.
242 :param uuid: The unique identifier of an object in UUID format.
Yolanda Roblaabd90112018-05-15 17:11:54 +0200243 :param expected_status: Expected response status code. By default is
244 http_client.NO_CONTENT (204)
Yuiko Takadab6527002015-12-07 11:49:12 +0900245 :returns: A tuple with the server response and the response body.
246
247 """
248 uri = self._get_uri(resource, uuid)
249
250 resp, body = self.delete(uri)
Yolanda Roblaabd90112018-05-15 17:11:54 +0200251 self.expected_success(expected_status, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900252 return resp, body
253
Dmitry Tantsure7548052018-07-16 17:48:32 +0200254 def _patch_request(self, resource, uuid, patch_object, params=None):
Yuiko Takadab6527002015-12-07 11:49:12 +0900255 """Update specified object with JSON-patch.
256
257 :param resource: The name of the REST resource, e.g., 'nodes'.
258 :param uuid: The unique identifier of an object in UUID format.
Dmitry Tantsure7548052018-07-16 17:48:32 +0200259 :param params: query parameters to pass.
Yuiko Takadab6527002015-12-07 11:49:12 +0900260 :returns: A tuple with the server response and the serialized patched
261 object.
262
263 """
Dmitry Tantsure7548052018-07-16 17:48:32 +0200264 uri = self._get_uri(resource, uuid, params=params)
Yuiko Takadab6527002015-12-07 11:49:12 +0900265 patch_body = json.dumps(patch_object)
266
267 resp, body = self.patch(uri, body=patch_body)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600268 self.expected_success(http_client.OK, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900269 return resp, self.deserialize(body)
270
271 @handle_errors
272 def get_api_description(self):
273 """Retrieves all versions of the Ironic API."""
274
275 return self._list_request('', permanent=True)
276
277 @handle_errors
278 def get_version_description(self, version='v1'):
Kyrylo Romanenko36000542016-09-16 15:07:40 +0300279 """Retrieves the description of the API.
Yuiko Takadab6527002015-12-07 11:49:12 +0900280
281 :param version: The version of the API. Default: 'v1'.
282 :returns: Serialized description of API resources.
283
284 """
285 return self._list_request(version, permanent=True)
286
287 def _put_request(self, resource, put_object):
288 """Update specified object with JSON-patch."""
289 uri = self._get_uri(resource)
290 put_body = json.dumps(put_object)
291
292 resp, body = self.put(uri, body=put_body)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600293 self.expected_success([http_client.ACCEPTED, http_client.NO_CONTENT],
294 resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900295 return resp, body