blob: 4510b5b33a391b00e7aeebb607612fa8c1ea25d5 [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
12
13class bmc_redfish_utils(object):
14
George Keishingeb1fe352020-06-19 03:02:22 -050015 ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
16
George Keishingf2613b72019-02-13 12:45:59 -060017 def __init__(self):
18 r"""
19 Initialize the bmc_redfish_utils object.
20 """
21 # Obtain a reference to the global redfish object.
George Keishingeb1fe352020-06-19 03:02:22 -050022 self.__inited__ = False
George Keishingf2613b72019-02-13 12:45:59 -060023 self._redfish_ = BuiltIn().get_library_instance('redfish')
24
George Keishingeb1fe352020-06-19 03:02:22 -050025 # There is a possibility that a given driver support both redfish and
26 # legacy REST.
27 self._redfish_.login()
28 self._rest_response_ = \
29 self._redfish_.get("/xyz/openbmc_project/", valid_status_codes=[200, 404])
30
31 # If REST URL /xyz/openbmc_project/ is supported.
32 if self._rest_response_.status == 200:
33 self.__inited__ = True
34
35 BuiltIn().set_global_variable("${REDFISH_REST_SUPPORTED}", self.__inited__)
36
George Keishing374e6842019-02-20 08:57:18 -060037 def get_redfish_session_info(self):
38 r"""
39 Returns redfish sessions info dictionary.
40
41 {
42 'key': 'yLXotJnrh5nDhXj5lLiH' ,
43 'location': '/redfish/v1/SessionService/Sessions/nblYY4wlz0'
44 }
45 """
46 session_dict = {
George Keishing97c93942019-03-04 12:45:07 -060047 "key": self._redfish_.get_session_key(),
48 "location": self._redfish_.get_session_location()
George Keishing374e6842019-02-20 08:57:18 -060049 }
50 return session_dict
51
Sandhya Somashekar37122b62019-06-18 06:02:02 -050052 def get_attribute(self, resource_path, attribute, verify=None):
George Keishingf2613b72019-02-13 12:45:59 -060053 r"""
54 Get resource attribute.
55
56 Description of argument(s):
Michael Walshc86a2f72019-03-19 13:24:37 -050057 resource_path URI resource absolute path (e.g.
58 "/redfish/v1/Systems/1").
59 attribute Name of the attribute (e.g. 'PowerState').
George Keishingf2613b72019-02-13 12:45:59 -060060 """
61
62 resp = self._redfish_.get(resource_path)
Sandhya Somashekar37122b62019-06-18 06:02:02 -050063
64 if verify:
65 if resp.dict[attribute] == verify:
66 return resp.dict[attribute]
67 else:
68 raise ValueError("Attribute value is not equal")
69 elif attribute in resp.dict:
George Keishingf2613b72019-02-13 12:45:59 -060070 return resp.dict[attribute]
71
72 return None
73
George Keishingc3c05c22019-02-19 01:04:54 -060074 def get_properties(self, resource_path):
75 r"""
76 Returns dictionary of attributes for the resource.
77
78 Description of argument(s):
Michael Walshc86a2f72019-03-19 13:24:37 -050079 resource_path URI resource absolute path (e.g.
Sandhya Somashekar37122b62019-06-18 06:02:02 -050080 /redfish/v1/Systems/1").
George Keishingc3c05c22019-02-19 01:04:54 -060081 """
82
83 resp = self._redfish_.get(resource_path)
84 return resp.dict
85
George Keishing789c3b42020-07-14 08:44:47 -050086 def get_members_uri(self, resource_path, attribute):
87 r"""
88 Returns the list of valid path which has a given attribute.
89
90 Description of argument(s):
91 resource_path URI resource base path (e.g.
92 '/redfish/v1/Systems/',
93 '/redfish/v1/Chassis/').
94 attribute Name of the attribute (e.g. 'PowerSupplies').
95 """
96
George Keishingd5f179e2020-07-14 16:07:31 -050097 # Set quiet variable to keep subordinate get() calls quiet.
98 quiet = 1
99
George Keishing789c3b42020-07-14 08:44:47 -0500100 # Get the member id list.
101 # e.g. ['/redfish/v1/Chassis/foo', '/redfish/v1/Chassis/bar']
102 resource_path_list = self.get_member_list(resource_path)
George Keishing789c3b42020-07-14 08:44:47 -0500103
104 valid_path_list = []
105
106 for path_idx in resource_path_list:
107 # Get all the child object path under the member id e.g.
108 # ['/redfish/v1/Chassis/foo/Power','/redfish/v1/Chassis/bar/Power']
109 child_path_list = self.list_request(path_idx)
George Keishing789c3b42020-07-14 08:44:47 -0500110
111 # Iterate and check if path object has the attribute.
112 for child_path_idx in child_path_list:
113 if self.get_attribute(child_path_idx, attribute):
114 valid_path_list.append(child_path_idx)
115
George Keishingd5f179e2020-07-14 16:07:31 -0500116 BuiltIn().log_to_console(valid_path_list)
George Keishing789c3b42020-07-14 08:44:47 -0500117 return valid_path_list
118
George Keishing3a6f0732020-07-13 14:21:23 -0500119 def get_endpoint_path_list(self, resource_path, end_point_prefix):
120 r"""
121 Returns list with entries ending in "/endpoint".
122
123 Description of argument(s):
124 resource_path URI resource base path (e.g. "/redfish/v1/Chassis/").
125 end_point_prefix Name of the enpoint (e.g. 'Power').
126
127 Find all list entries ending in "/endpoint" combination such as
128 /redfish/v1/Chassis/<foo>/Power
129 /redfish/v1/Chassis/<bar>/Power
130 """
131
132 end_point_list = self.list_request(resource_path)
133
134 # Regex to match entries ending in "/prefix" with optional underscore.
135 regex = ".*/" + end_point_prefix + "[_]?[0-9]*?"
136 return [x for x in end_point_list if re.match(regex, x, re.IGNORECASE)]
137
George Keishing7ec45932019-02-27 14:02:16 -0600138 def get_target_actions(self, resource_path, target_attribute):
139 r"""
140 Returns resource target entry of the searched target attribute.
141
142 Description of argument(s):
143 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000144 (e.g. "/redfish/v1/Systems/system").
George Keishing7ec45932019-02-27 14:02:16 -0600145 target_attribute Name of the attribute (e.g. 'ComputerSystem.Reset').
146
147 Example:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500148 "Actions": {
149 "#ComputerSystem.Reset": {
150 "ResetType@Redfish.AllowableValues": [
George Keishing7ec45932019-02-27 14:02:16 -0600151 "On",
152 "ForceOff",
153 "GracefulRestart",
154 "GracefulShutdown"
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500155 ],
156 "target": "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset"
157 }
158 }
George Keishing7ec45932019-02-27 14:02:16 -0600159 """
160
161 global target_list
162 target_list = []
163
164 resp_dict = self.get_attribute(resource_path, "Actions")
165 if resp_dict is None:
166 return None
167
168 # Recursively search the "target" key in the nested dictionary.
169 # Populate the target_list of target entries.
170 self.get_key_value_nested_dict(resp_dict, "target")
George Keishing7ec45932019-02-27 14:02:16 -0600171 # Return the matching target URL entry.
172 for target in target_list:
173 # target "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset"
174 if target_attribute in target:
175 return target
176
177 return None
178
George Keishingdabf38f2019-03-10 09:52:40 -0500179 def get_member_list(self, resource_path):
180 r"""
181 Perform a GET list request and return available members entries.
182
183 Description of argument(s):
184 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000185 (e.g. "/redfish/v1/SessionService/Sessions").
George Keishingdabf38f2019-03-10 09:52:40 -0500186
187 "Members": [
188 {
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500189 "@odata.id": "/redfish/v1/SessionService/Sessions/Z5HummWPZ7"
George Keishingdabf38f2019-03-10 09:52:40 -0500190 }
191 {
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500192 "@odata.id": "/redfish/v1/SessionService/Sessions/46CmQmEL7H"
George Keishingdabf38f2019-03-10 09:52:40 -0500193 }
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500194 ],
George Keishingdabf38f2019-03-10 09:52:40 -0500195 """
196
197 member_list = []
198 resp_list_dict = self.get_attribute(resource_path, "Members")
199 if resp_list_dict is None:
200 return member_list
201
202 for member_id in range(0, len(resp_list_dict)):
203 member_list.append(resp_list_dict[member_id]["@odata.id"])
204
205 return member_list
206
George Keishingf2613b72019-02-13 12:45:59 -0600207 def list_request(self, resource_path):
208 r"""
209 Perform a GET list request and return available resource paths.
George Keishingf2613b72019-02-13 12:45:59 -0600210 Description of argument(s):
211 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000212 (e.g. "/redfish/v1/SessionService/Sessions").
George Keishingf2613b72019-02-13 12:45:59 -0600213 """
Michael Walshc86a2f72019-03-19 13:24:37 -0500214 gp.qprint_executing(style=gp.func_line_style_short)
Michael Walshc86a2f72019-03-19 13:24:37 -0500215 # Set quiet variable to keep subordinate get() calls quiet.
216 quiet = 1
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500217 self.__pending_enumeration = set()
Michael Walshc86a2f72019-03-19 13:24:37 -0500218 self._rest_response_ = \
George Keishingf8acde92019-04-19 19:46:48 +0000219 self._redfish_.get(resource_path,
220 valid_status_codes=[200, 404, 500])
George Keishingf2613b72019-02-13 12:45:59 -0600221
222 # Return empty list.
223 if self._rest_response_.status != 200:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500224 return self.__pending_enumeration
George Keishingf2613b72019-02-13 12:45:59 -0600225 self.walk_nested_dict(self._rest_response_.dict)
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500226 if not self.__pending_enumeration:
227 return resource_path
228 for resource in self.__pending_enumeration.copy():
Michael Walshc86a2f72019-03-19 13:24:37 -0500229 self._rest_response_ = \
George Keishingf8acde92019-04-19 19:46:48 +0000230 self._redfish_.get(resource,
231 valid_status_codes=[200, 404, 500])
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500232
George Keishingf2613b72019-02-13 12:45:59 -0600233 if self._rest_response_.status != 200:
234 continue
235 self.walk_nested_dict(self._rest_response_.dict)
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500236 return list(sorted(self.__pending_enumeration))
George Keishingf2613b72019-02-13 12:45:59 -0600237
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600238 def enumerate_request(self, resource_path, return_json=1,
239 include_dead_resources=False):
George Keishingf2613b72019-02-13 12:45:59 -0600240 r"""
241 Perform a GET enumerate request and return available resource paths.
242
243 Description of argument(s):
Michael Walsh37e028f2019-05-22 16:16:32 -0500244 resource_path URI resource absolute path (e.g.
245 "/redfish/v1/SessionService/Sessions").
246 return_json Indicates whether the result should be
247 returned as a json string or as a
248 dictionary.
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600249 include_dead_resources Check and return a list of dead/broken URI
250 resources.
George Keishingf2613b72019-02-13 12:45:59 -0600251 """
252
Michael Walshc86a2f72019-03-19 13:24:37 -0500253 gp.qprint_executing(style=gp.func_line_style_short)
254
Michael Walsh37e028f2019-05-22 16:16:32 -0500255 return_json = int(return_json)
256
Michael Walshc86a2f72019-03-19 13:24:37 -0500257 # Set quiet variable to keep subordinate get() calls quiet.
258 quiet = 1
259
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500260 # Variable to hold enumerated data.
261 self.__result = {}
George Keishingf2613b72019-02-13 12:45:59 -0600262
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500263 # Variable to hold the pending list of resources for which enumeration.
264 # is yet to be obtained.
265 self.__pending_enumeration = set()
George Keishingf2613b72019-02-13 12:45:59 -0600266
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500267 self.__pending_enumeration.add(resource_path)
George Keishingf2613b72019-02-13 12:45:59 -0600268
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500269 # Variable having resources for which enumeration is completed.
270 enumerated_resources = set()
George Keishingf2613b72019-02-13 12:45:59 -0600271
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600272 if include_dead_resources:
273 dead_resources = {}
274
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500275 resources_to_be_enumerated = (resource_path,)
276
277 while resources_to_be_enumerated:
278 for resource in resources_to_be_enumerated:
Anusha Dathatri6d2d42f2019-11-20 06:17:51 -0600279 # JsonSchemas, SessionService or URLs containing # are not
280 # required in enumeration.
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500281 # Example: '/redfish/v1/JsonSchemas/' and sub resources.
Anusha Dathatricdb77db2019-09-10 08:10:29 -0500282 # '/redfish/v1/SessionService'
Anusha Dathatri6d2d42f2019-11-20 06:17:51 -0600283 # '/redfish/v1/Managers/bmc#/Oem'
284 if ('JsonSchemas' in resource) or ('SessionService' in resource)\
285 or ('#' in resource):
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500286 continue
287
288 self._rest_response_ = \
289 self._redfish_.get(resource, valid_status_codes=[200, 404, 500])
290 # Enumeration is done for available resources ignoring the
291 # ones for which response is not obtained.
292 if self._rest_response_.status != 200:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600293 if include_dead_resources:
294 try:
295 dead_resources[self._rest_response_.status].append(
296 resource)
297 except KeyError:
298 dead_resources[self._rest_response_.status] = \
299 [resource]
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500300 continue
301
302 self.walk_nested_dict(self._rest_response_.dict, url=resource)
303
304 enumerated_resources.update(set(resources_to_be_enumerated))
305 resources_to_be_enumerated = \
306 tuple(self.__pending_enumeration - enumerated_resources)
307
Michael Walsh37e028f2019-05-22 16:16:32 -0500308 if return_json:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600309 if include_dead_resources:
310 return json.dumps(self.__result, sort_keys=True,
311 indent=4, separators=(',', ': ')), dead_resources
312 else:
313 return json.dumps(self.__result, sort_keys=True,
314 indent=4, separators=(',', ': '))
Michael Walsh37e028f2019-05-22 16:16:32 -0500315 else:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600316 if include_dead_resources:
317 return self.__result, dead_resources
318 else:
319 return self.__result
George Keishingf2613b72019-02-13 12:45:59 -0600320
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500321 def walk_nested_dict(self, data, url=''):
George Keishingf2613b72019-02-13 12:45:59 -0600322 r"""
323 Parse through the nested dictionary and get the resource id paths.
George Keishingf2613b72019-02-13 12:45:59 -0600324 Description of argument(s):
325 data Nested dictionary data from response message.
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500326 url Resource for which the response is obtained in data.
George Keishingf2613b72019-02-13 12:45:59 -0600327 """
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500328 url = url.rstrip('/')
George Keishingf2613b72019-02-13 12:45:59 -0600329
330 for key, value in data.items():
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500331
332 # Recursion if nested dictionary found.
George Keishingf2613b72019-02-13 12:45:59 -0600333 if isinstance(value, dict):
334 self.walk_nested_dict(value)
335 else:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500336 # Value contains a list of dictionaries having member data.
George Keishingf2613b72019-02-13 12:45:59 -0600337 if 'Members' == key:
338 if isinstance(value, list):
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500339 for memberDict in value:
340 self.__pending_enumeration.add(memberDict['@odata.id'])
George Keishingf2613b72019-02-13 12:45:59 -0600341 if '@odata.id' == key:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500342 value = value.rstrip('/')
343 # Data for the given url.
344 if value == url:
345 self.__result[url] = data
346 # Data still needs to be looked up,
347 else:
348 self.__pending_enumeration.add(value)
George Keishing7ec45932019-02-27 14:02:16 -0600349
350 def get_key_value_nested_dict(self, data, key):
351 r"""
352 Parse through the nested dictionary and get the searched key value.
353
354 Description of argument(s):
355 data Nested dictionary data from response message.
356 key Search dictionary key element.
357 """
358
359 for k, v in data.items():
360 if isinstance(v, dict):
361 self.get_key_value_nested_dict(v, key)
362
363 if k == key:
364 target_list.append(v)