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    #  "ResetType@Redfish.AllowableValues": [
22    #    "On",
23    #    "ForceOff",
24    #    "ForceOn",
25    #    "ForceRestart",
26    #    "GracefulRestart",
27    #    "GracefulShutdown"
28    #    "PowerCycle",
29    #    "Nmi"
30    #  ],
31    #  "target": "/redfish/v1/Systems/system/Actions/ComputerSystem.Reset"
32    #  }
33    # }
34
35    ${target}=  redfish_utils.Get Target Actions  /redfish/v1/Systems/system/  ComputerSystem.Reset
36    ${payload}=  Create Dictionary  ResetType=${reset_type}
37    ${resp}=  Redfish.Post  ${target}  body=&{payload}
38
39
40Redfish BMC Reset Operation
41    [Documentation]  Do Redfish BMC reset operation.
42    [Arguments]  ${reset_type}=GracefulRestart
43
44    # Example:
45    # "Actions": {
46    # "#Manager.Reset": {
47    #  "ResetType@Redfish.AllowableValues": [
48    #    "GracefulRestart",
49    #    "ForceRestart"
50    #  ],
51    #  "target": "/redfish/v1/Managers/bmc/Actions/Manager.Reset"
52    # }
53
54    ${target}=  redfish_utils.Get Target Actions  /redfish/v1/Managers/bmc/  Manager.Reset
55    ${payload}=  Create Dictionary  ResetType=${reset_type}
56    Redfish.Post  ${target}  body=&{payload}
57
58
59Reset BIOS Via Redfish
60    [Documentation]  Do BIOS reset through Redfish.
61
62    ${target}=  redfish_utils.Get Target Actions  /redfish/v1/Systems/system/Bios/  Bios.ResetBios
63    Redfish.Post  ${target}  valid_status_codes=[${HTTP_OK}]
64
65
66Redfish Delete Session
67    [Documentation]  Redfish delete session.
68    [Arguments]  ${session_info}
69
70    # Description of argument(s):
71    # session_info      Session information are stored in dictionary.
72
73    # ${session_info} = {
74    #     'SessionIDs': 'XXXXXXXXX',
75    #     'ClientID': 'XXXXXX',
76    #     'SessionToken': 'XXXXXXXXX',
77    #     'SessionResp': session response from redfish login
78    # }
79
80    # SessionIDs   : Session IDs
81    # ClientID     : Client ID
82    # SessionToken : Session token
83    # SessionResp  : Response of creating an redfish login session
84
85    Redfish.Delete  /redfish/v1/SessionService/Sessions/${session_info["SessionIDs"]}
86
87
88Redfish Delete List Of Session
89    [Documentation]  Redfish delete session from list of session records, individual session information
90    ...              are stored in dictionary.
91    [Arguments]  ${session_info_list}
92
93    # Description of argument(s):
94    # session_info_list    List contains individual session record are stored in dictionary.
95
96    # ${session_info_list} = [{
97    #     'SessionIDs': 'XXXXXXXXX',
98    #     'ClientID': 'XXXXXX',
99    #     'SessionToken': 'XXXXXXXXX',
100    #     'SessionResp': session response from redfish login
101    # }]
102
103    # SessionIDs   : Session IDs
104    # ClientID     : Client ID
105    # SessionToken : Session token
106    # SessionResp  : Response of creating an redfish login session
107
108    FOR  ${session_record}  IN  @{session_info_list}
109      Redfish.Delete  /redfish/v1/SessionService/Sessions/${session_record["SessionIDs"]}
110    END
111
112
113Delete All Redfish Sessions
114    [Documentation]  Delete all active redfish sessions.
115
116    ${saved_session_info}=  Redfish_Utils.Get Redfish Session Info
117
118    ${resp_list}=  Redfish_Utils.Get Member List
119    ...  /redfish/v1/SessionService/Sessions
120
121    # Remove the current login session from the list.
122    Remove Values From List  ${resp_list}  ${saved_session_info["location"]}
123
124    # Remove session with client_id populated from the list.
125    ${client_id_list}=  Get Session With Client Id  ${resp_list}
126    Log To Console  Client sessions skip list: ${client_id_list}
127    FOR  ${client_session}  IN  @{client_id_list}
128        Remove Values From List  ${resp_list}  ${client_session}
129    END
130
131    FOR  ${session}  IN  @{resp_list}
132        Run Keyword And Ignore Error  Redfish.Delete  ${session}
133    END
134
135
136Get Session With Client Id
137    [Documentation]  Iterate through the active sessions and return sessions populated with client id.
138    [Arguments]  ${session_list}
139
140    # Description of argument(s):
141    # session_list   Active session list from SessionService.
142
143    #  "Oem": {
144    #    "OpenBMC": {
145    #        "@odata.type": "#OemSession.v1_0_0.Session",
146    #        "ClientID": "MYID=Vd57f62*2811504"
147    #    }
148
149    ${client_id_sessions}=  Create List
150    FOR  ${session}  IN  @{session_list}
151        ${resp}=  Redfish.Get  ${session}   valid_status_codes=[200,404]
152        Run Keyword If  '${resp.dict["Oem"]["OpenBMC"]["ClientID"]}' != '${EMPTY}'
153        ...    Append To List  ${client_id_sessions}  ${session}
154    END
155
156    [Return]  ${client_id_sessions}
157
158
159Get Valid FRUs
160    [Documentation]  Return a dictionary containing all of the valid FRU records for the given fru_type.
161    [Arguments]  ${fru_type}
162
163    # NOTE: A valid FRU record will have a "State" key of "Enabled" and a "Health" key of "OK".
164
165    # Description of argument(s):
166    # fru_type  The type of fru (e.g. "Processors", "Memory", etc.).
167
168    ${fru_records}=  Redfish_Utils.Enumerate Request
169    ...  /redfish/v1/Systems/system/${fru_type}  return_json=0
170    ${fru_records}=  Filter Struct  ${fru_records}  [('State', 'Enabled'), ('Health', 'OK')]
171
172    [Return]  ${fru_records}
173
174
175Get Num Valid FRUs
176    [Documentation]  Return the number of valid FRU records for the given fru_type.
177    [Arguments]  ${fru_type}
178
179    # Description of argument(s):
180    # fru_type  The type of fru (e.g. "Processors", "Memory", etc.).
181
182    ${fru_records}=  Get Valid FRUs  ${fru_type}
183    ${num_valid_frus}=  Get length  ${fru_records}
184
185    [Return]  ${num_valid_frus}
186
187
188Verify Valid Records
189    [Documentation]  Verify all records retrieved with the given arguments are valid.
190    [Arguments]  ${record_type}  ${redfish_uri}  ${reading_type}
191
192    # Description of Argument(s):
193    # record_type    The sensor record type (e.g. "PowerSupplies")
194    # redfish_uri    The power supply URI (e.g. /redfish/v1/Chassis/chassis/Power)
195    # reading_type   The power watt readings (e.g. "PowerInputWatts")
196
197    # A valid record will have "State" key "Enabled" and "Health" key "OK".
198    ${records}=  Redfish.Get Attribute  ${redfish_uri}  ${record_type}
199
200    Rprint Vars  records
201
202    # Example output:
203    # records:
204    #   [0]:
205    #     [@odata.id]:                 /redfish/v1/Chassis/chassis/Power#/PowerControl/0
206    #     [@odata.type]:               #Power.v1_0_0.PowerControl
207    #     [MemberId]:                  0
208    #     [Name]:                      Chassis Power Control
209    #     [PowerConsumedWatts]:        264.0
210    #     [PowerLimit]:
211    #       [LimitInWatts]:            None
212    #     [PowerMetrics]:
213    #       [AverageConsumedWatts]:    325
214    #       [IntervalInMin]:           3
215    #       [MaxConsumedWatts]:        538
216    #     [Status]:
217    #       [Health]:                  OK
218    #       [State]:                   Enabled
219
220    ${invalid_records}=  Filter Struct  ${records}
221    ...  [('Health', '^OK$'), ('State', '^Enabled$'), ('${reading_type}', '')]  regex=1  invert=1
222    Valid Length  invalid_records  max_length=0
223
224    [Return]  ${records}
225
226
227Redfish Create User
228    [Documentation]  Redfish create user.
229    [Arguments]   ${user_name}  ${password}  ${role_id}  ${enabled}  ${force}=${False}
230
231    # Description of argument(s):
232    # user_name           The user name to be created.
233    # password            The password to be assigned.
234    # role_id             The role ID of the user to be created.
235    #                     (e.g. "Administrator", "Operator", etc.).
236    # enabled             Indicates whether the username being created.
237    #                     should be enabled (${True}, ${False}).
238    # force               Delete user account and re-create if force is True.
239
240    ${curr_role}=  Run Keyword And Ignore Error  Get User Role  ${user_name}
241    # Ex: ${curr_role} = ('PASS', 'Administrator')
242
243    ${user_exists}=  Run Keyword And Return Status  Should Be Equal As Strings  ${curr_role}[0]  PASS
244
245    # Delete user account when force is True.
246    Run Keyword If  ${force} == ${True}  Redfish.Delete  ${REDFISH_ACCOUNTS_URI}${user_name}
247    ...  valid_status_codes=[${HTTP_OK}, ${HTTP_NOT_FOUND}]
248
249    # Create specified user when force is True or User does not exist.
250    ${payload}=  Create Dictionary
251    ...  UserName=${user_name}  Password=${password}  RoleId=${role_id}  Enabled=${enabled}
252
253    Run Keyword If  ${force} == ${True} or ${user_exists} == ${False}
254    ...  Redfish.Post  ${REDFISH_ACCOUNTS_URI}  body=&{payload}
255    ...  valid_status_codes=[${HTTP_CREATED}]
256
257
258Get User Role
259    [Documentation]  Get User Role.
260    [Arguments]  ${user_name}
261
262    # Description of argument(s):
263    # user_name    User name to get it's role.
264
265    ${role_config}=  Redfish_Utils.Get Attribute
266    ...  ${REDFISH_ACCOUNTS_URI}${user_name}  RoleId
267
268    [Return]  ${role_config}
269
270
271Create Users With Different Roles
272    [Documentation]  Create users with different roles.
273    [Arguments]  ${users}  ${force}=${False}
274
275    # Description of argument(s):
276    # users    Dictionary of roles and user credentails to be created.
277    #          Ex:  {'Administrator': '[admin_user, TestPwd123]', 'Operator': '[operator_user, TestPwd123]'}
278    # force    Delete given user account if already exists when force is True.
279
280    FOR  ${role}  IN  @{users}
281      Redfish Create User  ${users['${role}'][0]}  ${users['${role}']}[1]  ${role}  ${True}  ${force}
282    END
283
284
285Delete BMC Users Via Redfish
286    [Documentation]  Delete BMC users via redfish.
287    [Arguments]  ${users}
288
289    # Description of argument(s):
290    # users    Dictionary of roles and user credentials to be deleted.
291
292    FOR  ${role}  IN  @{users}
293        Redfish.Delete  /redfish/v1/AccountService/Accounts/${users['${role}'][0]}
294        ...  valid_status_codes=[${HTTP_OK}, ${HTTP_NOT_FOUND}]
295    END
296
297
298Expire And Update New Password Via Redfish
299    [Documentation]  Expire and change password and verify using password.
300    [Arguments]  ${username}  ${password}  ${new_password}
301
302    # Description of argument(s):
303    # username        The username to be used to login to the BMC.
304    # password        The password to be used to login to the BMC.
305    # new_password    The new password to be used to update password.
306
307    # Expire admin password using ssh.
308    Open Connection And Log In  ${OPENBMC_USERNAME}  ${OPENBMC_PASSWORD}
309    ${output}  ${stderr}  ${rc}=  BMC Execute Command  passwd --expire ${username}
310    Should Contain Any  ${output}  password expiry information changed
311    ...  password changed
312
313    # Verify user password expired using Redfish
314    Verify User Password Expired Using Redfish  ${username}  ${password}
315
316    # Change user password.
317    Redfish.Patch  /redfish/v1/AccountService/Accounts/${username}
318    ...  body={'Password': '${new_password}'}
319    Redfish.Logout
320
321
322Verify User Password Expired Using Redfish
323    [Documentation]  Checking whether user password expired or not using redfish.
324
325    # Description of argument(s):
326    # username        The username to be used to login to the BMC.
327    # password        The password to be used to login to the BMC.
328
329    [Arguments]  ${username}  ${password}  ${expected_result}=${True}
330    Redfish.Login  ${username}  ${password}
331    ${resp}=  Redfish.Get  /redfish/v1/AccountService/Accounts/${username}
332    Should Be Equal  ${resp.dict["PasswordChangeRequired"]}  ${expected_result}
333
334