blob: ea39930a9d90fc4239a9011a4be60f2aff8b6ee3 [file] [log] [blame]
George Keishingf2613b72019-02-13 12:45:59 -06001#!/usr/bin/env python
2
3r"""
4BMC redfish utility functions.
5"""
6
7import json
George Keishing3a6f0732020-07-13 14:21:23 -05008import re
George Keishingf2613b72019-02-13 12:45:59 -06009from robot.libraries.BuiltIn import BuiltIn
Michael Walshc86a2f72019-03-19 13:24:37 -050010import gen_print as gp
George Keishingf2613b72019-02-13 12:45:59 -060011
Tony Lee05aa70b2021-01-28 19:18:27 +080012MTLS_ENABLED = BuiltIn().get_variable_value("${MTLS_ENABLED}")
13
George Keishingf2613b72019-02-13 12:45:59 -060014
15class bmc_redfish_utils(object):
16
George Keishingeb1fe352020-06-19 03:02:22 -050017 ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
18
George Keishingf2613b72019-02-13 12:45:59 -060019 def __init__(self):
20 r"""
21 Initialize the bmc_redfish_utils object.
22 """
23 # Obtain a reference to the global redfish object.
George Keishingeb1fe352020-06-19 03:02:22 -050024 self.__inited__ = False
George Keishingf2613b72019-02-13 12:45:59 -060025 self._redfish_ = BuiltIn().get_library_instance('redfish')
26
Tony Lee05aa70b2021-01-28 19:18:27 +080027 if MTLS_ENABLED == 'True':
George Keishingeb1fe352020-06-19 03:02:22 -050028 self.__inited__ = True
Tony Lee05aa70b2021-01-28 19:18:27 +080029 else:
30 # There is a possibility that a given driver support both redfish and
31 # legacy REST.
32 self._redfish_.login()
33 self._rest_response_ = \
34 self._redfish_.get("/xyz/openbmc_project/", valid_status_codes=[200, 404])
35
36 # If REST URL /xyz/openbmc_project/ is supported.
37 if self._rest_response_.status == 200:
38 self.__inited__ = True
George Keishingeb1fe352020-06-19 03:02:22 -050039
40 BuiltIn().set_global_variable("${REDFISH_REST_SUPPORTED}", self.__inited__)
41
George Keishing374e6842019-02-20 08:57:18 -060042 def get_redfish_session_info(self):
43 r"""
44 Returns redfish sessions info dictionary.
45
46 {
47 'key': 'yLXotJnrh5nDhXj5lLiH' ,
48 'location': '/redfish/v1/SessionService/Sessions/nblYY4wlz0'
49 }
50 """
51 session_dict = {
George Keishing97c93942019-03-04 12:45:07 -060052 "key": self._redfish_.get_session_key(),
53 "location": self._redfish_.get_session_location()
George Keishing374e6842019-02-20 08:57:18 -060054 }
55 return session_dict
56
Sandhya Somashekar37122b62019-06-18 06:02:02 -050057 def get_attribute(self, resource_path, attribute, verify=None):
George Keishingf2613b72019-02-13 12:45:59 -060058 r"""
59 Get resource attribute.
60
61 Description of argument(s):
Michael Walshc86a2f72019-03-19 13:24:37 -050062 resource_path URI resource absolute path (e.g.
63 "/redfish/v1/Systems/1").
64 attribute Name of the attribute (e.g. 'PowerState').
George Keishingf2613b72019-02-13 12:45:59 -060065 """
66
67 resp = self._redfish_.get(resource_path)
Sandhya Somashekar37122b62019-06-18 06:02:02 -050068
69 if verify:
70 if resp.dict[attribute] == verify:
71 return resp.dict[attribute]
72 else:
73 raise ValueError("Attribute value is not equal")
74 elif attribute in resp.dict:
George Keishingf2613b72019-02-13 12:45:59 -060075 return resp.dict[attribute]
76
77 return None
78
George Keishingc3c05c22019-02-19 01:04:54 -060079 def get_properties(self, resource_path):
80 r"""
81 Returns dictionary of attributes for the resource.
82
83 Description of argument(s):
Michael Walshc86a2f72019-03-19 13:24:37 -050084 resource_path URI resource absolute path (e.g.
Sandhya Somashekar37122b62019-06-18 06:02:02 -050085 /redfish/v1/Systems/1").
George Keishingc3c05c22019-02-19 01:04:54 -060086 """
87
88 resp = self._redfish_.get(resource_path)
89 return resp.dict
90
George Keishing789c3b42020-07-14 08:44:47 -050091 def get_members_uri(self, resource_path, attribute):
92 r"""
93 Returns the list of valid path which has a given attribute.
94
95 Description of argument(s):
96 resource_path URI resource base path (e.g.
97 '/redfish/v1/Systems/',
98 '/redfish/v1/Chassis/').
99 attribute Name of the attribute (e.g. 'PowerSupplies').
100 """
101
George Keishingd5f179e2020-07-14 16:07:31 -0500102 # Set quiet variable to keep subordinate get() calls quiet.
103 quiet = 1
104
George Keishing789c3b42020-07-14 08:44:47 -0500105 # Get the member id list.
106 # e.g. ['/redfish/v1/Chassis/foo', '/redfish/v1/Chassis/bar']
107 resource_path_list = self.get_member_list(resource_path)
George Keishing789c3b42020-07-14 08:44:47 -0500108
109 valid_path_list = []
110
111 for path_idx in resource_path_list:
112 # Get all the child object path under the member id e.g.
113 # ['/redfish/v1/Chassis/foo/Power','/redfish/v1/Chassis/bar/Power']
114 child_path_list = self.list_request(path_idx)
George Keishing789c3b42020-07-14 08:44:47 -0500115
116 # Iterate and check if path object has the attribute.
117 for child_path_idx in child_path_list:
George Keishing6396bc62020-07-15 06:56:46 -0500118 if ('JsonSchemas' in child_path_idx)\
119 or ('SessionService' in child_path_idx)\
120 or ('#' in child_path_idx):
121 continue
George Keishing789c3b42020-07-14 08:44:47 -0500122 if self.get_attribute(child_path_idx, attribute):
123 valid_path_list.append(child_path_idx)
124
George Keishingd5f179e2020-07-14 16:07:31 -0500125 BuiltIn().log_to_console(valid_path_list)
George Keishing789c3b42020-07-14 08:44:47 -0500126 return valid_path_list
127
George Keishing3a6f0732020-07-13 14:21:23 -0500128 def get_endpoint_path_list(self, resource_path, end_point_prefix):
129 r"""
130 Returns list with entries ending in "/endpoint".
131
132 Description of argument(s):
133 resource_path URI resource base path (e.g. "/redfish/v1/Chassis/").
George Keishinge68cbfb2020-08-12 11:11:58 -0500134 end_point_prefix Name of the endpoint (e.g. 'Power').
George Keishing3a6f0732020-07-13 14:21:23 -0500135
136 Find all list entries ending in "/endpoint" combination such as
137 /redfish/v1/Chassis/<foo>/Power
138 /redfish/v1/Chassis/<bar>/Power
139 """
140
141 end_point_list = self.list_request(resource_path)
142
143 # Regex to match entries ending in "/prefix" with optional underscore.
144 regex = ".*/" + end_point_prefix + "[_]?[0-9]*?"
145 return [x for x in end_point_list if re.match(regex, x, re.IGNORECASE)]
146
George Keishing7ec45932019-02-27 14:02:16 -0600147 def get_target_actions(self, resource_path, target_attribute):
148 r"""
149 Returns resource target entry of the searched target attribute.
150
151 Description of argument(s):
152 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000153 (e.g. "/redfish/v1/Systems/system").
George Keishing7ec45932019-02-27 14:02:16 -0600154 target_attribute Name of the attribute (e.g. 'ComputerSystem.Reset').
155
156 Example:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500157 "Actions": {
158 "#ComputerSystem.Reset": {
159 "ResetType@Redfish.AllowableValues": [
George Keishing7ec45932019-02-27 14:02:16 -0600160 "On",
161 "ForceOff",
162 "GracefulRestart",
163 "GracefulShutdown"
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500164 ],
165 "target": "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset"
166 }
167 }
George Keishing7ec45932019-02-27 14:02:16 -0600168 """
169
170 global target_list
171 target_list = []
172
173 resp_dict = self.get_attribute(resource_path, "Actions")
174 if resp_dict is None:
175 return None
176
177 # Recursively search the "target" key in the nested dictionary.
178 # Populate the target_list of target entries.
179 self.get_key_value_nested_dict(resp_dict, "target")
George Keishing7ec45932019-02-27 14:02:16 -0600180 # Return the matching target URL entry.
181 for target in target_list:
182 # target "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset"
183 if target_attribute in target:
184 return target
185
186 return None
187
George Keishingdabf38f2019-03-10 09:52:40 -0500188 def get_member_list(self, resource_path):
189 r"""
190 Perform a GET list request and return available members entries.
191
192 Description of argument(s):
193 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000194 (e.g. "/redfish/v1/SessionService/Sessions").
George Keishingdabf38f2019-03-10 09:52:40 -0500195
196 "Members": [
197 {
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500198 "@odata.id": "/redfish/v1/SessionService/Sessions/Z5HummWPZ7"
George Keishingdabf38f2019-03-10 09:52:40 -0500199 }
200 {
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500201 "@odata.id": "/redfish/v1/SessionService/Sessions/46CmQmEL7H"
George Keishingdabf38f2019-03-10 09:52:40 -0500202 }
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500203 ],
George Keishingdabf38f2019-03-10 09:52:40 -0500204 """
205
206 member_list = []
207 resp_list_dict = self.get_attribute(resource_path, "Members")
208 if resp_list_dict is None:
209 return member_list
210
211 for member_id in range(0, len(resp_list_dict)):
212 member_list.append(resp_list_dict[member_id]["@odata.id"])
213
214 return member_list
215
George Keishingf2613b72019-02-13 12:45:59 -0600216 def list_request(self, resource_path):
217 r"""
218 Perform a GET list request and return available resource paths.
George Keishingf2613b72019-02-13 12:45:59 -0600219 Description of argument(s):
220 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000221 (e.g. "/redfish/v1/SessionService/Sessions").
George Keishingf2613b72019-02-13 12:45:59 -0600222 """
Michael Walshc86a2f72019-03-19 13:24:37 -0500223 gp.qprint_executing(style=gp.func_line_style_short)
Michael Walshc86a2f72019-03-19 13:24:37 -0500224 # Set quiet variable to keep subordinate get() calls quiet.
225 quiet = 1
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500226 self.__pending_enumeration = set()
Michael Walshc86a2f72019-03-19 13:24:37 -0500227 self._rest_response_ = \
George Keishingf8acde92019-04-19 19:46:48 +0000228 self._redfish_.get(resource_path,
229 valid_status_codes=[200, 404, 500])
George Keishingf2613b72019-02-13 12:45:59 -0600230
231 # Return empty list.
232 if self._rest_response_.status != 200:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500233 return self.__pending_enumeration
George Keishingf2613b72019-02-13 12:45:59 -0600234 self.walk_nested_dict(self._rest_response_.dict)
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500235 if not self.__pending_enumeration:
236 return resource_path
237 for resource in self.__pending_enumeration.copy():
Michael Walshc86a2f72019-03-19 13:24:37 -0500238 self._rest_response_ = \
George Keishingf8acde92019-04-19 19:46:48 +0000239 self._redfish_.get(resource,
240 valid_status_codes=[200, 404, 500])
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500241
George Keishingf2613b72019-02-13 12:45:59 -0600242 if self._rest_response_.status != 200:
243 continue
244 self.walk_nested_dict(self._rest_response_.dict)
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500245 return list(sorted(self.__pending_enumeration))
George Keishingf2613b72019-02-13 12:45:59 -0600246
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600247 def enumerate_request(self, resource_path, return_json=1,
248 include_dead_resources=False):
George Keishingf2613b72019-02-13 12:45:59 -0600249 r"""
250 Perform a GET enumerate request and return available resource paths.
251
252 Description of argument(s):
Michael Walsh37e028f2019-05-22 16:16:32 -0500253 resource_path URI resource absolute path (e.g.
254 "/redfish/v1/SessionService/Sessions").
255 return_json Indicates whether the result should be
256 returned as a json string or as a
257 dictionary.
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600258 include_dead_resources Check and return a list of dead/broken URI
259 resources.
George Keishingf2613b72019-02-13 12:45:59 -0600260 """
261
Michael Walshc86a2f72019-03-19 13:24:37 -0500262 gp.qprint_executing(style=gp.func_line_style_short)
263
Michael Walsh37e028f2019-05-22 16:16:32 -0500264 return_json = int(return_json)
265
Michael Walshc86a2f72019-03-19 13:24:37 -0500266 # Set quiet variable to keep subordinate get() calls quiet.
267 quiet = 1
268
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500269 # Variable to hold enumerated data.
270 self.__result = {}
George Keishingf2613b72019-02-13 12:45:59 -0600271
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500272 # Variable to hold the pending list of resources for which enumeration.
273 # is yet to be obtained.
274 self.__pending_enumeration = set()
George Keishingf2613b72019-02-13 12:45:59 -0600275
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500276 self.__pending_enumeration.add(resource_path)
George Keishingf2613b72019-02-13 12:45:59 -0600277
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500278 # Variable having resources for which enumeration is completed.
279 enumerated_resources = set()
George Keishingf2613b72019-02-13 12:45:59 -0600280
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600281 if include_dead_resources:
282 dead_resources = {}
283
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500284 resources_to_be_enumerated = (resource_path,)
285
286 while resources_to_be_enumerated:
287 for resource in resources_to_be_enumerated:
Anusha Dathatri6d2d42f2019-11-20 06:17:51 -0600288 # JsonSchemas, SessionService or URLs containing # are not
289 # required in enumeration.
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500290 # Example: '/redfish/v1/JsonSchemas/' and sub resources.
Anusha Dathatricdb77db2019-09-10 08:10:29 -0500291 # '/redfish/v1/SessionService'
Anusha Dathatri6d2d42f2019-11-20 06:17:51 -0600292 # '/redfish/v1/Managers/bmc#/Oem'
293 if ('JsonSchemas' in resource) or ('SessionService' in resource)\
294 or ('#' in resource):
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500295 continue
296
297 self._rest_response_ = \
298 self._redfish_.get(resource, valid_status_codes=[200, 404, 500])
299 # Enumeration is done for available resources ignoring the
300 # ones for which response is not obtained.
301 if self._rest_response_.status != 200:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600302 if include_dead_resources:
303 try:
304 dead_resources[self._rest_response_.status].append(
305 resource)
306 except KeyError:
307 dead_resources[self._rest_response_.status] = \
308 [resource]
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500309 continue
310
311 self.walk_nested_dict(self._rest_response_.dict, url=resource)
312
313 enumerated_resources.update(set(resources_to_be_enumerated))
314 resources_to_be_enumerated = \
315 tuple(self.__pending_enumeration - enumerated_resources)
316
Michael Walsh37e028f2019-05-22 16:16:32 -0500317 if return_json:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600318 if include_dead_resources:
319 return json.dumps(self.__result, sort_keys=True,
320 indent=4, separators=(',', ': ')), dead_resources
321 else:
322 return json.dumps(self.__result, sort_keys=True,
323 indent=4, separators=(',', ': '))
Michael Walsh37e028f2019-05-22 16:16:32 -0500324 else:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600325 if include_dead_resources:
326 return self.__result, dead_resources
327 else:
328 return self.__result
George Keishingf2613b72019-02-13 12:45:59 -0600329
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500330 def walk_nested_dict(self, data, url=''):
George Keishingf2613b72019-02-13 12:45:59 -0600331 r"""
332 Parse through the nested dictionary and get the resource id paths.
George Keishingf2613b72019-02-13 12:45:59 -0600333 Description of argument(s):
334 data Nested dictionary data from response message.
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500335 url Resource for which the response is obtained in data.
George Keishingf2613b72019-02-13 12:45:59 -0600336 """
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500337 url = url.rstrip('/')
George Keishingf2613b72019-02-13 12:45:59 -0600338
339 for key, value in data.items():
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500340
341 # Recursion if nested dictionary found.
George Keishingf2613b72019-02-13 12:45:59 -0600342 if isinstance(value, dict):
343 self.walk_nested_dict(value)
344 else:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500345 # Value contains a list of dictionaries having member data.
George Keishingf2613b72019-02-13 12:45:59 -0600346 if 'Members' == key:
347 if isinstance(value, list):
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500348 for memberDict in value:
349 self.__pending_enumeration.add(memberDict['@odata.id'])
George Keishingf2613b72019-02-13 12:45:59 -0600350 if '@odata.id' == key:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500351 value = value.rstrip('/')
352 # Data for the given url.
353 if value == url:
354 self.__result[url] = data
355 # Data still needs to be looked up,
356 else:
357 self.__pending_enumeration.add(value)
George Keishing7ec45932019-02-27 14:02:16 -0600358
359 def get_key_value_nested_dict(self, data, key):
360 r"""
361 Parse through the nested dictionary and get the searched key value.
362
363 Description of argument(s):
364 data Nested dictionary data from response message.
365 key Search dictionary key element.
366 """
367
368 for k, v in data.items():
369 if isinstance(v, dict):
370 self.get_key_value_nested_dict(v, key)
371
372 if k == key:
373 target_list.append(v)