1*** Settings ***
2Documentation   BMC and host redfish utility keywords.
3
4Resource        resource.robot
5Resource        bmc_redfish_resource.robot
6
7
8*** Keywords ***
9
10Redfish Power Operation
11    [Documentation]  Do Redfish host power operation.
12    [Arguments]      ${reset_type}
13
14    # Description of arguments:
15    # reset_type     Type of power operation.
16    #                (e.g. On/ForceOff/GracefulRestart/GracefulShutdown)
17
18    # Example:
19    # "Actions": {
20    # "#ComputerSystem.Reset": {
21    #        "@Redfish.ActionInfo": "/redfish/v1/Systems/${SYSTEM_ID}/ResetActionInfo",
22    #        "target": "/redfish/v1/Systems/${SYSTEM_ID}/Actions/ComputerSystem.Reset"
23    #    }
24
25    # Parameters allowable values  /redfish/v1/Systems/${SYSTEM_ID}/ResetActionInfo
26
27    # "@odata.id": "/redfish/v1/Systems/${SYSTEM_ID}/ResetActionInfo",
28    # "@odata.type": "#ActionInfo.v1_1_2.ActionInfo",
29    # "Id": "ResetActionInfo",
30    # "Name": "Reset Action Info",
31    # "Parameters": [
32    #    {
33    #        "AllowableValues": [
34    #            "ForceOff",
35    #            "PowerCycle",
36    #            "Nmi",
37    #            "GracefulShutdown",
38    #            "On",
39    #            "ForceOn",
40    #            "GracefulRestart",
41    #            "ForceRestart"
42    #        ],
43    #        "DataType": "String",
44    #        "Name": "ResetType",
45    #        "Required": true
46    #    }
47    # ]
48
49    ${target}=  Wait Until Keyword Succeeds  1 min  20 sec
50    ...  redfish_utils.Get Target Actions  /redfish/v1/Systems/${SYSTEM_ID}/  ComputerSystem.Reset
51    ${payload}=  Create Dictionary  ResetType=${reset_type}
52    ${resp}=  Redfish.Post  ${target}  body=&{payload}
53    ...  valid_status_codes=[${HTTP_OK}, ${HTTP_NO_CONTENT}]
54
55
56Redfish BMC Reset Operation
57    [Documentation]  Do Redfish BMC reset operation.
58    [Arguments]  ${reset_type}=GracefulRestart
59
60    # Example:
61    # "Actions": {
62    #    "#Manager.Reset": {
63    #        "@Redfish.ActionInfo": "/redfish/v1/Managers/${MANAGER_ID}/ResetActionInfo",
64    #        "target": "/redfish/v1/Managers/${MANAGER_ID}/Actions/Manager.Reset"
65    #    },
66    #    "#Manager.ResetToDefaults": {
67    #        "ResetType@Redfish.AllowableValues": [
68    #            "ResetAll"
69    #        ],
70    #        "target": "/redfish/v1/Managers/${MANAGER_ID}/Actions/Manager.ResetToDefaults"
71    #    }
72    # },
73
74    # Parameters allowable values  /redfish/v1/Managers/${MANAGER_ID}/ResetActionInfo
75
76    # "@odata.id": "/redfish/v1/Managers/${MANAGER_ID}/ResetActionInfo",
77    # "@odata.type": "#ActionInfo.v1_1_2.ActionInfo",
78    # "Id": "ResetActionInfo",
79    # "Name": "Reset Action Info",
80    # "Parameters": [
81    #    {
82    #        "AllowableValues": [
83    #            "GracefulRestart",
84    #            "ForceRestart"
85    #        ],
86    #        "DataType": "String",
87    #        "Name": "ResetType",
88    #        "Required": true
89    #    }
90    # ]
91
92    ${target}=  Wait Until Keyword Succeeds  1 min  20 sec
93    ...  redfish_utils.Get Target Actions  /redfish/v1/Managers/${MANAGER_ID}/  Manager.Reset
94    ${payload}=  Create Dictionary  ResetType=${reset_type}
95    Redfish.Post  ${target}  body=&{payload}
96
97
98Reset BIOS Via Redfish
99    [Documentation]  Do BIOS reset through Redfish.
100
101    ${target}=  redfish_utils.Get Target Actions  /redfish/v1/Systems/${SYSTEM_ID}/Bios/  Bios.ResetBios
102    Redfish.Post  ${target}  valid_status_codes=[${HTTP_OK}]
103
104
105Set Redfish Delete Session Flag
106    [Documentation]  Disable or enable delete redfish while performing the power operation keyword.
107    [Arguments]  ${set_flag}
108
109    # Description of argument(s):
110    # set_flag    Set user specified enable(1) or disable(0).
111
112    Set Suite Variable  ${REDFISH_DELETE_SESSIONS}  ${set_flag}
113
114
115Redfish Delete Session
116    [Documentation]  Redfish delete session.
117    [Arguments]  ${session_info}
118
119    # Description of argument(s):
120    # session_info      Session information are stored in dictionary.
121
122    # ${session_info} = {
123    #     'SessionIDs': 'XXXXXXXXX',
124    #     'ClientID': 'XXXXXX',
125    #     'SessionToken': 'XXXXXXXXX',
126    #     'SessionResp': session response from redfish login
127    # }
128
129    # SessionIDs   : Session IDs
130    # ClientID     : Client ID
131    # SessionToken : Session token
132    # SessionResp  : Response of creating an redfish login session
133
134    Redfish.Delete  /redfish/v1/SessionService/Sessions/${session_info["SessionIDs"]}
135
136
137Redfish Delete List Of Session
138    [Documentation]  Redfish delete session from list of session records, individual session information
139    ...              are stored in dictionary.
140    [Arguments]  ${session_info_list}
141
142    # Description of argument(s):
143    # session_info_list    List contains individual session record are stored in dictionary.
144
145    # ${session_info_list} = [{
146    #     'SessionIDs': 'XXXXXXXXX',
147    #     'ClientID': 'XXXXXX',
148    #     'SessionToken': 'XXXXXXXXX',
149    #     'SessionResp': session response from redfish login
150    # }]
151
152    # SessionIDs   : Session IDs
153    # ClientID     : Client ID
154    # SessionToken : Session token
155    # SessionResp  : Response of creating an redfish login session
156
157    FOR  ${session_record}  IN  @{session_info_list}
158      Redfish.Delete  /redfish/v1/SessionService/Sessions/${session_record["SessionIDs"]}
159    END
160
161
162Delete All Redfish Sessions
163    [Documentation]  Delete all active redfish sessions.
164
165    ${saved_session_info}=  Redfish_Utils.Get Redfish Session Info
166
167    ${resp_list}=  Redfish_Utils.Get Member List
168    ...  /redfish/v1/SessionService/Sessions
169
170    # Remove the current login session from the list.
171    Remove Values From List  ${resp_list}  ${saved_session_info["location"]}
172
173    # Remove session with client_id populated from the list.
174    ${client_id_list}=  Get Session With Client Id  ${resp_list}
175    Log To Console  Client sessions skip list: ${client_id_list}
176    FOR  ${client_session}  IN  @{client_id_list}
177        Remove Values From List  ${resp_list}  ${client_session}
178    END
179
180    FOR  ${session}  IN  @{resp_list}
181        Run Keyword And Ignore Error  Redfish.Delete  ${session}
182    END
183
184
185Get Session With Client Id
186    [Documentation]  Iterate through the active sessions and return sessions
187    ...              populated with Context.
188    [Arguments]  ${session_list}
189
190    # Description of argument(s):
191    # session_list   Active session list from SessionService.
192
193    # "@odata.type": "#Session.v1_5_0.Session",
194    # "ClientOriginIPAddress": "xx.xx.xx.xx",
195    # "Context": "MYID-01"
196
197    ${client_id_sessions}=  Create List
198    FOR  ${session}  IN  @{session_list}
199        ${resp}=  Redfish.Get  ${session}   valid_status_codes=[200,404]
200        # This prevents dictionary KeyError exception when the Context
201        # attribute is not populated in generic session response.
202        ${context_var}=  Get Variable Value  ${resp.dict["Context"]}  ${EMPTY}
203        # Handle backward compatibility for OEM.
204        ${oem_var}=  Get Variable Value  ${resp.dict["Oem"]["OpenBMC"]["ClientID"]}  ${EMPTY}
205        Run Keyword If  '${context_var}' != '${EMPTY}'
206        ...    Append To List  ${client_id_sessions}  ${session}
207        Run Keyword If  '${oem_var}' != '${EMPTY}'
208        ...    Append To List  ${client_id_sessions}  ${session}
209    END
210
211    RETURN  ${client_id_sessions}
212
213
214Get Valid FRUs
215    [Documentation]  Return a dictionary containing all of the valid FRU records for the given fru_type.
216    [Arguments]  ${fru_type}
217
218    # NOTE: A valid FRU record will have a "State" key of "Enabled" and a "Health" key of "OK".
219
220    # Description of argument(s):
221    # fru_type  The type of fru (e.g. "Processors", "Memory", etc.).
222
223    ${fru_records}=  Redfish_Utils.Enumerate Request
224    ...  /redfish/v1/Systems/${SYSTEM_ID}/${fru_type}  return_json=0
225    ${fru_records}=  Filter Struct  ${fru_records}  [('State', 'Enabled'), ('Health', 'OK')]
226
227    RETURN  ${fru_records}
228
229
230Get Num Valid FRUs
231    [Documentation]  Return the number of valid FRU records for the given fru_type.
232    [Arguments]  ${fru_type}
233
234    # Description of argument(s):
235    # fru_type  The type of fru (e.g. "Processors", "Memory", etc.).
236
237    ${fru_records}=  Get Valid FRUs  ${fru_type}
238    ${num_valid_frus}=  Get length  ${fru_records}
239
240    RETURN  ${num_valid_frus}
241
242
243Verify Valid Records
244    [Documentation]  Verify all records retrieved with the given arguments are valid.
245    [Arguments]  ${record_type}  ${redfish_uri}  ${reading_type}
246
247    # Description of Argument(s):
248    # record_type    The sensor record type (e.g. "PowerSupplies")
249    # redfish_uri    The power supply URI (e.g. /redfish/v1/Chassis/chassis/Power)
250    # reading_type   The power watt readings (e.g. "PowerInputWatts")
251
252    # A valid record will have "State" key "Enabled" and "Health" key "OK".
253    ${records}=  Redfish.Get Attribute  ${redfish_uri}  ${record_type}
254
255    Rprint Vars  records
256
257    # Example output:
258    # records:
259    #   [0]:
260    #     [@odata.id]:                 /redfish/v1/Chassis/chassis/Power#/PowerControl/0
261    #     [@odata.type]:               #Power.v1_0_0.PowerControl
262    #     [MemberId]:                  0
263    #     [Name]:                      Chassis Power Control
264    #     [PowerConsumedWatts]:        264.0
265    #     [PowerLimit]:
266    #       [LimitInWatts]:            None
267    #     [PowerMetrics]:
268    #       [AverageConsumedWatts]:    325
269    #       [IntervalInMin]:           3
270    #       [MaxConsumedWatts]:        538
271    #     [Status]:
272    #       [Health]:                  OK
273    #       [State]:                   Enabled
274
275    ${invalid_records}=  Filter Struct  ${records}
276    ...  [('Health', '^OK$'), ('State', '^Enabled$'), ('${reading_type}', '')]  regex=1  invert=1
277    Valid Length  invalid_records  max_length=0
278
279    RETURN  ${records}
280
281
282Redfish Create User
283    [Documentation]  Redfish create user.
284    [Arguments]   ${user_name}  ${password}  ${role_id}  ${enabled}  ${force}=${False}
285
286    # Description of argument(s):
287    # user_name           The user name to be created.
288    # password            The password to be assigned.
289    # role_id             The role ID of the user to be created.
290    #                     (e.g. "Administrator", "Operator", etc.).
291    # enabled             Indicates whether the username being created.
292    #                     should be enabled (${True}, ${False}).
293    # force               Delete user account and re-create if force is True.
294
295    ${curr_role}=  Run Keyword And Ignore Error  Get User Role  ${user_name}
296    # Ex: ${curr_role} = ('PASS', 'Administrator')
297
298    ${user_exists}=  Run Keyword And Return Status  Should Be Equal As Strings  ${curr_role}[0]  PASS
299
300    # Delete user account when force is True.
301    Run Keyword If  ${force} == ${True}  Redfish.Delete  ${REDFISH_ACCOUNTS_URI}${user_name}
302    ...  valid_status_codes=[${HTTP_OK}, ${HTTP_NOT_FOUND}]
303
304    # Create specified user when force is True or User does not exist.
305    ${payload}=  Create Dictionary
306    ...  UserName=${user_name}  Password=${password}  RoleId=${role_id}  Enabled=${enabled}
307
308    Run Keyword If  ${force} == ${True} or ${user_exists} == ${False}
309    ...  Redfish.Post  ${REDFISH_ACCOUNTS_URI}  body=&{payload}
310    ...  valid_status_codes=[${HTTP_CREATED}]
311
312
313Get User Role
314    [Documentation]  Get User Role.
315    [Arguments]  ${user_name}
316
317    # Description of argument(s):
318    # user_name    User name to get it's role.
319
320    ${role_config}=  Redfish_Utils.Get Attribute
321    ...  ${REDFISH_ACCOUNTS_URI}${user_name}  RoleId
322
323    RETURN  ${role_config}
324
325
326Create Users With Different Roles
327    [Documentation]  Create users with different roles.
328    [Arguments]  ${users}  ${force}=${False}
329
330    # Description of argument(s):
331    # users    Dictionary of roles and user credentials to be created.
332    #          Ex:  {'Administrator': '[admin_user, TestPwd123]', 'Operator': '[operator_user, TestPwd123]'}
333    # force    Delete given user account if already exists when force is True.
334
335    FOR  ${role}  IN  @{users}
336      Redfish Create User  ${users['${role}'][0]}  ${users['${role}']}[1]  ${role}  ${True}  ${force}
337    END
338
339
340Delete BMC Users Via Redfish
341    [Documentation]  Delete BMC users via redfish.
342    [Arguments]  ${users}
343
344    # Description of argument(s):
345    # users    Dictionary of roles and user credentials to be deleted.
346
347    FOR  ${role}  IN  @{users}
348        Redfish.Delete  /redfish/v1/AccountService/Accounts/${users['${role}'][0]}
349        ...  valid_status_codes=[${HTTP_OK}, ${HTTP_NOT_FOUND}]
350    END
351
352
353Expire And Update New Password Via Redfish
354    [Documentation]  Expire and change password and verify using password.
355    [Arguments]  ${username}  ${password}  ${new_password}
356
357    # Description of argument(s):
358    # username        The username to be used to login to the BMC.
359    # password        The password to be used to login to the BMC.
360    # new_password    The new password to be used to update password.
361
362    # Expire admin password using ssh.
363    Open Connection And Log In  ${OPENBMC_USERNAME}  ${OPENBMC_PASSWORD}
364    ${output}  ${stderr}  ${rc}=  BMC Execute Command  passwd --expire ${username}
365    Should Contain Any  ${output}  password expiry information changed
366    ...  password changed
367
368    # Verify user password expired using Redfish
369    Verify User Password Expired Using Redfish  ${username}  ${password}
370
371    # Change user password.
372    Redfish.Patch  /redfish/v1/AccountService/Accounts/${username}
373    ...  body={'Password': '${new_password}'}
374    Redfish.Logout
375
376
377Verify User Password Expired Using Redfish
378    [Documentation]  Checking whether user password expired or not using redfish.
379    [Arguments]  ${username}  ${password}  ${expected_result}=${True}
380
381    # Description of argument(s):
382    # username        The username to be used to login to the BMC.
383    # password        The password to be used to login to the BMC.
384
385    Redfish.Login  ${username}  ${password}
386    ${resp}=  Redfish.Get  /redfish/v1/AccountService/Accounts/${username}
387    Should Be Equal  ${resp.dict["PasswordChangeRequired"]}  ${expected_result}
388
389
390Is BMC LastResetTime Changed
391    [Documentation]  Return fail if BMC last reset time is not changed.
392    [Arguments]  ${reset_time}
393
394    # Description of argument(s):
395    # reset_time  Last BMC reset time.
396
397    ${last_reset_time}=  Get BMC Last Reset Time
398    Should Not Be Equal  ${last_reset_time}  ${reset_time}
399
400
401Redfish BMC Reboot
402    [Documentation]  Use Redfish API reboot BMC and wait for BMC ready.
403
404    #  Get BMC last reset time for compare
405    ${last_reset_time}=  Get BMC Last Reset Time
406
407    # Reboot BMC by Redfish API
408    Redfish BMC Reset Operation
409
410    # Wait for BMC real reboot and Redfish API ready
411    Wait Until Keyword Succeeds  3 min  10 sec  Is BMC LastResetTime Changed  ${last_reset_time}
412
413
414Get BMC Last Reset Time
415    [Documentation]  Return BMC LastResetTime.
416
417    ${last_reset_time}=  Redfish.Get Attribute  /redfish/v1/Managers/${MANAGER_ID}  LastResetTime
418
419    RETURN  ${last_reset_time}
420