blob: f2cffd502abf05763e843d8df486e490dc24ab22 [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
Dmitry Tantsurb294d962024-08-08 15:00:50 +020026# Interfaces that can be set via the baremetal client and by logic in scenario
27# managers.
28SUPPORTED_INTERFACES = ['bios', 'deploy', 'rescue', 'boot', 'raid',
29 'management', 'power', 'inspect']
30
Yuiko Takadab6527002015-12-07 11:49:12 +090031
Vasyl Saienko4ddbeec2017-01-20 16:26:04 +000032def set_baremetal_api_microversion(baremetal_microversion):
33 global BAREMETAL_MICROVERSION
34 BAREMETAL_MICROVERSION = baremetal_microversion
35
36
37def reset_baremetal_api_microversion():
38 global BAREMETAL_MICROVERSION
39 BAREMETAL_MICROVERSION = None
40
41
Yuiko Takadab6527002015-12-07 11:49:12 +090042def handle_errors(f):
43 """A decorator that allows to ignore certain types of errors."""
44
Takashi Kajinami6bddaab2022-05-10 00:58:56 +090045 @functools.wraps(f)
Yuiko Takadab6527002015-12-07 11:49:12 +090046 def wrapper(*args, **kwargs):
47 param_name = 'ignore_errors'
48 ignored_errors = kwargs.get(param_name, tuple())
49
50 if param_name in kwargs:
51 del kwargs[param_name]
52
53 try:
54 return f(*args, **kwargs)
55 except ignored_errors:
56 # Silently ignore errors
57 pass
58
59 return wrapper
60
61
62class BaremetalClient(rest_client.RestClient):
63 """Base Tempest REST client for Ironic API."""
64
Yuiko Takadaff785002015-12-17 15:56:42 +090065 api_microversion_header_name = 'X-OpenStack-Ironic-API-Version'
Yuiko Takadab6527002015-12-07 11:49:12 +090066 uri_prefix = ''
67
Yuiko Takadaff785002015-12-17 15:56:42 +090068 def get_headers(self):
69 headers = super(BaremetalClient, self).get_headers()
70 if BAREMETAL_MICROVERSION:
Julia Kreger0eb9ae72024-03-26 08:47:26 -070071 # NOTE(TheJulia): This is not great, because it can blind a test
72 # to the actual version supported.
Yuiko Takadaff785002015-12-17 15:56:42 +090073 headers[self.api_microversion_header_name] = BAREMETAL_MICROVERSION
74 return headers
75
Julia Kreger0eb9ae72024-03-26 08:47:26 -070076 def get_raw_headers(self):
77 """A proper get headers without guessing the microversion."""
78 return super(BaremetalClient, self).get_headers()
79
80 def get_min_max_api_microversions(self):
81 """Returns a tuple of minimum and remote microversions."""
82 _, resp_body = self._show_request(None, uri='/')
83 version = resp_body.get('default_version', {})
84 api_min = version.get('min_version')
85 api_max = version.get('version')
86 return (api_min, api_max)
87
Vasyl Saienkof20979c2016-05-27 11:25:01 +030088 def request(self, *args, **kwargs):
89 resp, resp_body = super(BaremetalClient, self).request(*args, **kwargs)
Riccardo Pittau441c5062020-03-30 15:06:28 +020090 latest_microversion = api_version_utils.LATEST_MICROVERSION
91 if (BAREMETAL_MICROVERSION
92 and BAREMETAL_MICROVERSION != latest_microversion):
Yuiko Takadaff785002015-12-17 15:56:42 +090093 api_version_utils.assert_version_header_matches_request(
94 self.api_microversion_header_name,
95 BAREMETAL_MICROVERSION,
96 resp)
97 return resp, resp_body
98
Yuiko Takadab6527002015-12-07 11:49:12 +090099 def serialize(self, object_dict):
100 """Serialize an Ironic object."""
101
102 return json.dumps(object_dict)
103
104 def deserialize(self, object_str):
105 """Deserialize an Ironic object."""
106
107 return json.loads(object_str)
108
Dmitry Tantsure7548052018-07-16 17:48:32 +0200109 def _get_uri(self, resource_name, uuid=None, permanent=False,
110 params=None):
Yuiko Takadab6527002015-12-07 11:49:12 +0900111 """Get URI for a specific resource or object.
112
113 :param resource_name: The name of the REST resource, e.g., 'nodes'.
114 :param uuid: The unique identifier of an object in UUID format.
115 :returns: Relative URI for the resource or object.
116
117 """
118 prefix = self.uri_prefix if not permanent else ''
Dmitry Tantsure7548052018-07-16 17:48:32 +0200119 if params:
120 params = '?' + '&'.join('%s=%s' % tpl for tpl in params.items())
121 else:
122 params = ''
Yuiko Takadab6527002015-12-07 11:49:12 +0900123
Dmitry Tantsure7548052018-07-16 17:48:32 +0200124 return '{pref}/{res}{uuid}{params}'.format(
125 pref=prefix, res=resource_name,
126 uuid='/%s' % uuid if uuid else '',
127 params=params)
Yuiko Takadab6527002015-12-07 11:49:12 +0900128
129 def _make_patch(self, allowed_attributes, **kwargs):
130 """Create a JSON patch according to RFC 6902.
131
132 :param allowed_attributes: An iterable object that contains a set of
133 allowed attributes for an object.
134 :param **kwargs: Attributes and new values for them.
135 :returns: A JSON path that sets values of the specified attributes to
136 the new ones.
137
138 """
139 def get_change(kwargs, path='/'):
Luong Anh Tuane22fbe12016-09-12 16:32:14 +0700140 for name, value in kwargs.items():
Yuiko Takadab6527002015-12-07 11:49:12 +0900141 if isinstance(value, dict):
142 for ch in get_change(value, path + '%s/' % name):
143 yield ch
144 else:
145 if value is None:
146 yield {'path': path + name,
147 'op': 'remove'}
148 else:
149 yield {'path': path + name,
150 'value': value,
151 'op': 'replace'}
152
153 patch = [ch for ch in get_change(kwargs)
154 if ch['path'].lstrip('/') in allowed_attributes]
155
156 return patch
157
Sam Betts462e9e62016-11-30 18:43:35 +0000158 def _list_request(self, resource, permanent=False, headers=None,
159 extra_headers=False, **kwargs):
Yuiko Takadab6527002015-12-07 11:49:12 +0900160 """Get the list of objects of the specified type.
161
162 :param resource: The name of the REST resource, e.g., 'nodes'.
Sam Betts462e9e62016-11-30 18:43:35 +0000163 :param headers: List of headers to use in request.
164 :param extra_headers: Specify whether to use headers.
Yuiko Takadab6527002015-12-07 11:49:12 +0900165 :param **kwargs: Parameters for the request.
166 :returns: A tuple with the server response and deserialized JSON list
167 of objects
168
169 """
170 uri = self._get_uri(resource, permanent=permanent)
171 if kwargs:
Takashi Kajinami6bddaab2022-05-10 00:58:56 +0900172 uri += "?%s" % urllib_parse.urlencode(kwargs)
Yuiko Takadab6527002015-12-07 11:49:12 +0900173
Sam Betts462e9e62016-11-30 18:43:35 +0000174 resp, body = self.get(uri, headers=headers,
175 extra_headers=extra_headers)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600176 self.expected_success(http_client.OK, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900177
178 return resp, self.deserialize(body)
179
SofiiaAndriichenko569f0a42016-12-08 05:02:17 -0500180 def _show_request(self,
181 resource,
182 uuid=None,
183 permanent=False,
Mark Goddard56399cc2018-02-16 13:37:25 +0000184 headers=None,
185 extra_headers=False,
SofiiaAndriichenko569f0a42016-12-08 05:02:17 -0500186 **kwargs):
Yuiko Takadab6527002015-12-07 11:49:12 +0900187 """Gets a specific object of the specified type.
188
189 :param uuid: Unique identifier of the object in UUID format.
Mark Goddard56399cc2018-02-16 13:37:25 +0000190 :param headers: List of headers to use in request.
191 :param extra_headers: Specify whether to use headers.
Yuiko Takadab6527002015-12-07 11:49:12 +0900192 :returns: Serialized object as a dictionary.
193
194 """
195 if 'uri' in kwargs:
196 uri = kwargs['uri']
197 else:
198 uri = self._get_uri(resource, uuid=uuid, permanent=permanent)
Mark Goddard56399cc2018-02-16 13:37:25 +0000199 resp, body = self.get(uri, headers=headers,
200 extra_headers=extra_headers)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600201 self.expected_success(http_client.OK, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900202
203 return resp, self.deserialize(body)
204
205 def _create_request(self, resource, object_dict):
206 """Create an object of the specified type.
207
208 :param resource: The name of the REST resource, e.g., 'nodes'.
209 :param object_dict: A Python dict that represents an object of the
210 specified type.
211 :returns: A tuple with the server response and the deserialized created
212 object.
213
214 """
215 body = self.serialize(object_dict)
216 uri = self._get_uri(resource)
217
218 resp, body = self.post(uri, body=body)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600219 self.expected_success(http_client.CREATED, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900220
221 return resp, self.deserialize(body)
222
Sam Betts462e9e62016-11-30 18:43:35 +0000223 def _create_request_no_response_body(self, resource, object_dict):
224 """Create an object of the specified type.
225
226 Do not expect any body in the response.
227
228 :param resource: The name of the REST resource, e.g., 'nodes'.
229 :param object_dict: A Python dict that represents an object of the
230 specified type.
231 :returns: The server response.
232 """
233
234 body = self.serialize(object_dict)
235 uri = self._get_uri(resource)
236
237 resp, body = self.post(uri, body=body)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600238 self.expected_success(http_client.NO_CONTENT, resp.status)
Sam Betts462e9e62016-11-30 18:43:35 +0000239
240 return resp
241
Yolanda Roblaabd90112018-05-15 17:11:54 +0200242 def _delete_request(self, resource, uuid,
243 expected_status=http_client.NO_CONTENT):
Yuiko Takadab6527002015-12-07 11:49:12 +0900244 """Delete specified object.
245
246 :param resource: The name of the REST resource, e.g., 'nodes'.
247 :param uuid: The unique identifier of an object in UUID format.
Yolanda Roblaabd90112018-05-15 17:11:54 +0200248 :param expected_status: Expected response status code. By default is
249 http_client.NO_CONTENT (204)
Yuiko Takadab6527002015-12-07 11:49:12 +0900250 :returns: A tuple with the server response and the response body.
251
252 """
253 uri = self._get_uri(resource, uuid)
254
255 resp, body = self.delete(uri)
Yolanda Roblaabd90112018-05-15 17:11:54 +0200256 self.expected_success(expected_status, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900257 return resp, body
258
Dmitry Tantsure7548052018-07-16 17:48:32 +0200259 def _patch_request(self, resource, uuid, patch_object, params=None):
Yuiko Takadab6527002015-12-07 11:49:12 +0900260 """Update specified object with JSON-patch.
261
262 :param resource: The name of the REST resource, e.g., 'nodes'.
263 :param uuid: The unique identifier of an object in UUID format.
Dmitry Tantsure7548052018-07-16 17:48:32 +0200264 :param params: query parameters to pass.
Yuiko Takadab6527002015-12-07 11:49:12 +0900265 :returns: A tuple with the server response and the serialized patched
266 object.
267
268 """
Dmitry Tantsure7548052018-07-16 17:48:32 +0200269 uri = self._get_uri(resource, uuid, params=params)
Yuiko Takadab6527002015-12-07 11:49:12 +0900270 patch_body = json.dumps(patch_object)
271
272 resp, body = self.patch(uri, body=patch_body)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600273 self.expected_success(http_client.OK, resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900274 return resp, self.deserialize(body)
275
276 @handle_errors
277 def get_api_description(self):
278 """Retrieves all versions of the Ironic API."""
279
280 return self._list_request('', permanent=True)
281
282 @handle_errors
283 def get_version_description(self, version='v1'):
Kyrylo Romanenko36000542016-09-16 15:07:40 +0300284 """Retrieves the description of the API.
Yuiko Takadab6527002015-12-07 11:49:12 +0900285
286 :param version: The version of the API. Default: 'v1'.
287 :returns: Serialized description of API resources.
288
289 """
290 return self._list_request(version, permanent=True)
291
292 def _put_request(self, resource, put_object):
293 """Update specified object with JSON-patch."""
294 uri = self._get_uri(resource)
295 put_body = json.dumps(put_object)
296
297 resp, body = self.put(uri, body=put_body)
Solio Sarabiaf78122e2017-02-23 16:17:34 -0600298 self.expected_success([http_client.ACCEPTED, http_client.NO_CONTENT],
299 resp.status)
Yuiko Takadab6527002015-12-07 11:49:12 +0900300 return resp, body