blob: 6da4af327ab9c80e421866cfeed21649cdb77483 [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
97 # Get the member id list.
98 # e.g. ['/redfish/v1/Chassis/foo', '/redfish/v1/Chassis/bar']
99 resource_path_list = self.get_member_list(resource_path)
100 BuiltIn().log_to_console(resource_path_list)
101
102 valid_path_list = []
103
104 for path_idx in resource_path_list:
105 # Get all the child object path under the member id e.g.
106 # ['/redfish/v1/Chassis/foo/Power','/redfish/v1/Chassis/bar/Power']
107 child_path_list = self.list_request(path_idx)
108 BuiltIn().log_to_console(child_path_list)
109
110 # Iterate and check if path object has the attribute.
111 for child_path_idx in child_path_list:
112 if self.get_attribute(child_path_idx, attribute):
113 valid_path_list.append(child_path_idx)
114
115 return valid_path_list
116
George Keishing3a6f0732020-07-13 14:21:23 -0500117 def get_endpoint_path_list(self, resource_path, end_point_prefix):
118 r"""
119 Returns list with entries ending in "/endpoint".
120
121 Description of argument(s):
122 resource_path URI resource base path (e.g. "/redfish/v1/Chassis/").
123 end_point_prefix Name of the enpoint (e.g. 'Power').
124
125 Find all list entries ending in "/endpoint" combination such as
126 /redfish/v1/Chassis/<foo>/Power
127 /redfish/v1/Chassis/<bar>/Power
128 """
129
130 end_point_list = self.list_request(resource_path)
131
132 # Regex to match entries ending in "/prefix" with optional underscore.
133 regex = ".*/" + end_point_prefix + "[_]?[0-9]*?"
134 return [x for x in end_point_list if re.match(regex, x, re.IGNORECASE)]
135
George Keishing7ec45932019-02-27 14:02:16 -0600136 def get_target_actions(self, resource_path, target_attribute):
137 r"""
138 Returns resource target entry of the searched target attribute.
139
140 Description of argument(s):
141 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000142 (e.g. "/redfish/v1/Systems/system").
George Keishing7ec45932019-02-27 14:02:16 -0600143 target_attribute Name of the attribute (e.g. 'ComputerSystem.Reset').
144
145 Example:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500146 "Actions": {
147 "#ComputerSystem.Reset": {
148 "ResetType@Redfish.AllowableValues": [
George Keishing7ec45932019-02-27 14:02:16 -0600149 "On",
150 "ForceOff",
151 "GracefulRestart",
152 "GracefulShutdown"
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500153 ],
154 "target": "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset"
155 }
156 }
George Keishing7ec45932019-02-27 14:02:16 -0600157 """
158
159 global target_list
160 target_list = []
161
162 resp_dict = self.get_attribute(resource_path, "Actions")
163 if resp_dict is None:
164 return None
165
166 # Recursively search the "target" key in the nested dictionary.
167 # Populate the target_list of target entries.
168 self.get_key_value_nested_dict(resp_dict, "target")
George Keishing7ec45932019-02-27 14:02:16 -0600169 # Return the matching target URL entry.
170 for target in target_list:
171 # target "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset"
172 if target_attribute in target:
173 return target
174
175 return None
176
George Keishingdabf38f2019-03-10 09:52:40 -0500177 def get_member_list(self, resource_path):
178 r"""
179 Perform a GET list request and return available members entries.
180
181 Description of argument(s):
182 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000183 (e.g. "/redfish/v1/SessionService/Sessions").
George Keishingdabf38f2019-03-10 09:52:40 -0500184
185 "Members": [
186 {
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500187 "@odata.id": "/redfish/v1/SessionService/Sessions/Z5HummWPZ7"
George Keishingdabf38f2019-03-10 09:52:40 -0500188 }
189 {
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500190 "@odata.id": "/redfish/v1/SessionService/Sessions/46CmQmEL7H"
George Keishingdabf38f2019-03-10 09:52:40 -0500191 }
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500192 ],
George Keishingdabf38f2019-03-10 09:52:40 -0500193 """
194
195 member_list = []
196 resp_list_dict = self.get_attribute(resource_path, "Members")
197 if resp_list_dict is None:
198 return member_list
199
200 for member_id in range(0, len(resp_list_dict)):
201 member_list.append(resp_list_dict[member_id]["@odata.id"])
202
203 return member_list
204
George Keishingf2613b72019-02-13 12:45:59 -0600205 def list_request(self, resource_path):
206 r"""
207 Perform a GET list request and return available resource paths.
George Keishingf2613b72019-02-13 12:45:59 -0600208 Description of argument(s):
209 resource_path URI resource absolute path
George Keishingf8acde92019-04-19 19:46:48 +0000210 (e.g. "/redfish/v1/SessionService/Sessions").
George Keishingf2613b72019-02-13 12:45:59 -0600211 """
Michael Walshc86a2f72019-03-19 13:24:37 -0500212 gp.qprint_executing(style=gp.func_line_style_short)
Michael Walshc86a2f72019-03-19 13:24:37 -0500213 # Set quiet variable to keep subordinate get() calls quiet.
214 quiet = 1
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500215 self.__pending_enumeration = set()
Michael Walshc86a2f72019-03-19 13:24:37 -0500216 self._rest_response_ = \
George Keishingf8acde92019-04-19 19:46:48 +0000217 self._redfish_.get(resource_path,
218 valid_status_codes=[200, 404, 500])
George Keishingf2613b72019-02-13 12:45:59 -0600219
220 # Return empty list.
221 if self._rest_response_.status != 200:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500222 return self.__pending_enumeration
George Keishingf2613b72019-02-13 12:45:59 -0600223 self.walk_nested_dict(self._rest_response_.dict)
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500224 if not self.__pending_enumeration:
225 return resource_path
226 for resource in self.__pending_enumeration.copy():
Michael Walshc86a2f72019-03-19 13:24:37 -0500227 self._rest_response_ = \
George Keishingf8acde92019-04-19 19:46:48 +0000228 self._redfish_.get(resource,
229 valid_status_codes=[200, 404, 500])
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500230
George Keishingf2613b72019-02-13 12:45:59 -0600231 if self._rest_response_.status != 200:
232 continue
233 self.walk_nested_dict(self._rest_response_.dict)
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500234 return list(sorted(self.__pending_enumeration))
George Keishingf2613b72019-02-13 12:45:59 -0600235
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600236 def enumerate_request(self, resource_path, return_json=1,
237 include_dead_resources=False):
George Keishingf2613b72019-02-13 12:45:59 -0600238 r"""
239 Perform a GET enumerate request and return available resource paths.
240
241 Description of argument(s):
Michael Walsh37e028f2019-05-22 16:16:32 -0500242 resource_path URI resource absolute path (e.g.
243 "/redfish/v1/SessionService/Sessions").
244 return_json Indicates whether the result should be
245 returned as a json string or as a
246 dictionary.
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600247 include_dead_resources Check and return a list of dead/broken URI
248 resources.
George Keishingf2613b72019-02-13 12:45:59 -0600249 """
250
Michael Walshc86a2f72019-03-19 13:24:37 -0500251 gp.qprint_executing(style=gp.func_line_style_short)
252
Michael Walsh37e028f2019-05-22 16:16:32 -0500253 return_json = int(return_json)
254
Michael Walshc86a2f72019-03-19 13:24:37 -0500255 # Set quiet variable to keep subordinate get() calls quiet.
256 quiet = 1
257
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500258 # Variable to hold enumerated data.
259 self.__result = {}
George Keishingf2613b72019-02-13 12:45:59 -0600260
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500261 # Variable to hold the pending list of resources for which enumeration.
262 # is yet to be obtained.
263 self.__pending_enumeration = set()
George Keishingf2613b72019-02-13 12:45:59 -0600264
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500265 self.__pending_enumeration.add(resource_path)
George Keishingf2613b72019-02-13 12:45:59 -0600266
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500267 # Variable having resources for which enumeration is completed.
268 enumerated_resources = set()
George Keishingf2613b72019-02-13 12:45:59 -0600269
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600270 if include_dead_resources:
271 dead_resources = {}
272
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500273 resources_to_be_enumerated = (resource_path,)
274
275 while resources_to_be_enumerated:
276 for resource in resources_to_be_enumerated:
Anusha Dathatri6d2d42f2019-11-20 06:17:51 -0600277 # JsonSchemas, SessionService or URLs containing # are not
278 # required in enumeration.
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500279 # Example: '/redfish/v1/JsonSchemas/' and sub resources.
Anusha Dathatricdb77db2019-09-10 08:10:29 -0500280 # '/redfish/v1/SessionService'
Anusha Dathatri6d2d42f2019-11-20 06:17:51 -0600281 # '/redfish/v1/Managers/bmc#/Oem'
282 if ('JsonSchemas' in resource) or ('SessionService' in resource)\
283 or ('#' in resource):
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500284 continue
285
286 self._rest_response_ = \
287 self._redfish_.get(resource, valid_status_codes=[200, 404, 500])
288 # Enumeration is done for available resources ignoring the
289 # ones for which response is not obtained.
290 if self._rest_response_.status != 200:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600291 if include_dead_resources:
292 try:
293 dead_resources[self._rest_response_.status].append(
294 resource)
295 except KeyError:
296 dead_resources[self._rest_response_.status] = \
297 [resource]
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500298 continue
299
300 self.walk_nested_dict(self._rest_response_.dict, url=resource)
301
302 enumerated_resources.update(set(resources_to_be_enumerated))
303 resources_to_be_enumerated = \
304 tuple(self.__pending_enumeration - enumerated_resources)
305
Michael Walsh37e028f2019-05-22 16:16:32 -0500306 if return_json:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600307 if include_dead_resources:
308 return json.dumps(self.__result, sort_keys=True,
309 indent=4, separators=(',', ': ')), dead_resources
310 else:
311 return json.dumps(self.__result, sort_keys=True,
312 indent=4, separators=(',', ': '))
Michael Walsh37e028f2019-05-22 16:16:32 -0500313 else:
Anusha Dathatri3e7930d2019-11-06 03:55:35 -0600314 if include_dead_resources:
315 return self.__result, dead_resources
316 else:
317 return self.__result
George Keishingf2613b72019-02-13 12:45:59 -0600318
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500319 def walk_nested_dict(self, data, url=''):
George Keishingf2613b72019-02-13 12:45:59 -0600320 r"""
321 Parse through the nested dictionary and get the resource id paths.
George Keishingf2613b72019-02-13 12:45:59 -0600322 Description of argument(s):
323 data Nested dictionary data from response message.
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500324 url Resource for which the response is obtained in data.
George Keishingf2613b72019-02-13 12:45:59 -0600325 """
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500326 url = url.rstrip('/')
George Keishingf2613b72019-02-13 12:45:59 -0600327
328 for key, value in data.items():
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500329
330 # Recursion if nested dictionary found.
George Keishingf2613b72019-02-13 12:45:59 -0600331 if isinstance(value, dict):
332 self.walk_nested_dict(value)
333 else:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500334 # Value contains a list of dictionaries having member data.
George Keishingf2613b72019-02-13 12:45:59 -0600335 if 'Members' == key:
336 if isinstance(value, list):
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500337 for memberDict in value:
338 self.__pending_enumeration.add(memberDict['@odata.id'])
George Keishingf2613b72019-02-13 12:45:59 -0600339 if '@odata.id' == key:
Anusha Dathatri62dfb862019-04-23 06:52:16 -0500340 value = value.rstrip('/')
341 # Data for the given url.
342 if value == url:
343 self.__result[url] = data
344 # Data still needs to be looked up,
345 else:
346 self.__pending_enumeration.add(value)
George Keishing7ec45932019-02-27 14:02:16 -0600347
348 def get_key_value_nested_dict(self, data, key):
349 r"""
350 Parse through the nested dictionary and get the searched key value.
351
352 Description of argument(s):
353 data Nested dictionary data from response message.
354 key Search dictionary key element.
355 """
356
357 for k, v in data.items():
358 if isinstance(v, dict):
359 self.get_key_value_nested_dict(v, key)
360
361 if k == key:
362 target_list.append(v)