| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
from __future__ import (absolute_import, division, print_function) |
| 29 |
|
| 30 |
__metaclass__ = type |
| 31 |
|
| 32 |
CHANGES_MSG = "Changes found to be applied." |
| 33 |
NO_CHANGES_MSG = "No changes found to be applied." |
| 34 |
RESET_UNTRACK = "iDRAC reset is in progress. Until the iDRAC is reset, the changes would not apply." |
| 35 |
RESET_SUCCESS = "iDRAC has been reset successfully." |
| 36 |
RESET_FAIL = "Unable to reset the iDRAC. For changes to reflect, manually reset the iDRAC." |
| 37 |
INVALID_ID_MSG = "Unable to complete the operation because " + \ |
| 38 |
"the value `{0}` for the input `{1}` parameter is invalid." |
| 39 |
UNSUPPORTED_LC_STATUS_MSG = "Lifecycle controller status check is not supported." |
| 40 |
LC_STATUS_MSG = "Lifecycle controller status check is {lc_status} after {retries} number of retries, Exiting.." |
| 41 |
SYSTEM_ID = "System.Embedded.1" |
| 42 |
MANAGER_ID = "iDRAC.Embedded.1" |
| 43 |
SYSTEMS_URI = "/redfish/v1/Systems" |
| 44 |
MANAGERS_URI = "/redfish/v1/Managers" |
| 45 |
CHASSIS_URI = "/redfish/v1/Chassis" |
| 46 |
IDRAC_RESET_URI = "/redfish/v1/Managers/{res_id}/Actions/Manager.Reset" |
| 47 |
SYSTEM_RESET_URI = "/redfish/v1/Systems/{res_id}/Actions/ComputerSystem.Reset" |
| 48 |
MANAGER_JOB_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs?$expand=*($levels=1)" |
| 49 |
MANAGER_JOB_ID_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/{0}" |
| 50 |
MANAGER_JOB_URI_10 = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs?$expand=*($levels=1)" |
| 51 |
MANAGER_JOB_ID_URI_10 = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/{0}" |
| 52 |
GET_IDRAC_FIRMWARE_VER_URI = "/redfish/v1/Managers/iDRAC.Embedded.1?$select=FirmwareVersion" |
| 53 |
HOSTNAME_REGEX = r"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$" |
| 54 |
OME_INFO = "ApplicationService/Info" |
| 55 |
ODATA_ID = "@odata.id" |
| 56 |
POWER_CHECK_RETRIES = 30 |
| 57 |
POWER_CHECK_INTERVAL = 10 |
| 58 |
GET_IDRAC_FIRMWARE_DETAILS_URI_10 = "/redfish/v1/UpdateService/Oem/Dell/DellSoftwareInventory?$select=Members" |
| 59 |
GET_IDRAC_FIRMWARE_URI_10 = "/redfish/v1/UpdateService/Oem/Dell/DellSoftwareInventory" |
| 60 |
TIMEOUT_NEGATIVE_OR_ZERO_MSG = "The value for the 'job_wait_timeout' parameter cannot be negative or zero." |
| 61 |
INVALID_TIME_FORMAT_MSG = "Invalid value for time. Enter the value in positive integer." |
| 62 |
|
| 63 |
import time |
| 64 |
from datetime import datetime |
| 65 |
from inspect import getfullargspec |
| 66 |
import re |
| 67 |
from ansible.module_utils.six.moves.urllib.error import HTTPError |
| 68 |
from ansible.module_utils.urls import ConnectionError, SSLValidationError |
| 69 |
from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError |
| 70 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.\ |
| 71 |
idrac_utils.info.firmware import IDRACFirmwareInfo |
| 72 |
import logging |
| 73 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.logging_handler \ |
| 74 |
import CustomRotatingFileHandler |
| 75 |
|
| 76 |
|
| 77 |
def strip_substr_dict(odata_dict, chkstr='@odata.', case_sensitive=False): |
| 78 |
''' |
| 79 |
:param odata_dict: the dict to be stripped of unwanted keys |
| 80 |
:param chkstr: the substring to be checked among the keys |
| 81 |
:param case_sensitive: should the match be case sensitive or not |
| 82 |
:return: dict |
| 83 |
''' |
| 84 |
cp = odata_dict.copy() |
| 85 |
klist = cp.keys() |
| 86 |
if not case_sensitive: |
| 87 |
chkstr = chkstr.lower() |
| 88 |
for k in klist: |
| 89 |
if case_sensitive: |
| 90 |
lk = k |
| 91 |
else: |
| 92 |
lk = str(k).lower() |
| 93 |
if chkstr in lk: |
| 94 |
odata_dict.pop(k, None) |
| 95 |
return odata_dict |
| 96 |
|
| 97 |
|
| 98 |
def config_ipv6(hostname): |
| 99 |
ip_addr, port = hostname, None |
| 100 |
if hostname.count(':') == 1: |
| 101 |
ip_addr, port = hostname.split(':') |
| 102 |
if not re.match(HOSTNAME_REGEX, ip_addr): |
| 103 |
if ']:' in ip_addr: |
| 104 |
ip_addr, port = ip_addr.split(']:') |
| 105 |
ip_addr = ip_addr.strip('[]') |
| 106 |
ip_addr = compress_ipv6(ip_addr) |
| 107 |
if port is None or port == "": |
| 108 |
hostname = "[{0}]".format(ip_addr) |
| 109 |
else: |
| 110 |
hostname = "[{0}]:{1}".format(ip_addr, port) |
| 111 |
return hostname |
| 112 |
|
| 113 |
|
| 114 |
def compress_ipv6(ipv6_long): |
| 115 |
groups = ipv6_long.split(':') |
| 116 |
temp = [] |
| 117 |
for group in groups: |
| 118 |
group = re.sub(r'^0+', '', group) |
| 119 |
group = group.lower() |
| 120 |
if 0 == len(group): |
| 121 |
group = '0' |
| 122 |
temp.append(group) |
| 123 |
tempstr = ':'.join(temp) |
| 124 |
ipv6_short = re.sub(r'(:0)+', ':', tempstr, 1) |
| 125 |
return ipv6_short |
| 126 |
|
| 127 |
|
| 128 |
def job_tracking(rest_obj, job_uri, max_job_wait_sec=600, job_state_var=('LastRunStatus', 'Id'), |
| 129 |
job_complete_states=(2060, 2020, 2090), job_fail_states=(2070, 2101, 2102, 2103), |
| 130 |
job_running_states=(2050, 2040, 2030, 2100), |
| 131 |
sleep_interval_secs=10, max_unresponsive_wait=30, initial_wait=1): |
| 132 |
''' |
| 133 |
:param rest_obj: the rest_obj either of the below |
| 134 |
ansible_collections.dellemc.openmanage.plugins.module_utils.ome.RestOME |
| 135 |
:param job_uri: the uri to fetch the job response dict |
| 136 |
:param max_job_wait_sec: max time the job will wait |
| 137 |
:param job_state_var: The nested dict traversal path |
| 138 |
:param job_complete_states: |
| 139 |
:param job_fail_states: |
| 140 |
:param job_running_states: |
| 141 |
:param sleep_interval_secs: |
| 142 |
:param max_unresponsive_wait: |
| 143 |
:param initial_wait: |
| 144 |
:return: |
| 145 |
''' |
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
max_retries = max_job_wait_sec // sleep_interval_secs |
| 153 |
unresp = max_unresponsive_wait // sleep_interval_secs |
| 154 |
loop_ctr = 0 |
| 155 |
job_failed = True |
| 156 |
job_dict = {} |
| 157 |
wait_time = 0 |
| 158 |
if set(job_complete_states) & set(job_fail_states): |
| 159 |
return job_failed, "Overlapping job states found.", job_dict, wait_time |
| 160 |
msg = "Job tracking started." |
| 161 |
time.sleep(initial_wait) |
| 162 |
while loop_ctr < max_retries: |
| 163 |
loop_ctr += 1 |
| 164 |
try: |
| 165 |
job_resp = rest_obj.invoke_request('GET', job_uri) |
| 166 |
job_dict = job_resp.json_data |
| 167 |
job_status = job_dict |
| 168 |
for x in job_state_var: |
| 169 |
job_status = job_status.get(x, {}) |
| 170 |
if job_status in job_complete_states: |
| 171 |
job_failed = False |
| 172 |
msg = "Job tracking completed." |
| 173 |
loop_ctr = max_retries |
| 174 |
elif job_status in job_fail_states: |
| 175 |
job_failed = True |
| 176 |
msg = "Job is in Failed state." |
| 177 |
loop_ctr = max_retries |
| 178 |
if job_running_states: |
| 179 |
if job_status in job_running_states: |
| 180 |
time.sleep(sleep_interval_secs) |
| 181 |
wait_time = wait_time + sleep_interval_secs |
| 182 |
else: |
| 183 |
time.sleep(sleep_interval_secs) |
| 184 |
wait_time = wait_time + sleep_interval_secs |
| 185 |
except Exception as err: |
| 186 |
if unresp: |
| 187 |
time.sleep(sleep_interval_secs) |
| 188 |
wait_time = wait_time + sleep_interval_secs |
| 189 |
else: |
| 190 |
job_failed = True |
| 191 |
msg = "Exception in job tracking " + str(err) |
| 192 |
break |
| 193 |
unresp = unresp - 1 |
| 194 |
return job_failed, msg, job_dict, wait_time |
| 195 |
|
| 196 |
|
| 197 |
def idrac_redfish_job_tracking( |
| 198 |
rest_obj, job_uri, max_job_wait_sec=600, job_state_var='JobState', |
| 199 |
job_complete_states=("Completed", "Downloaded", "CompletedWithErrors", "RebootCompleted"), |
| 200 |
job_fail_states=("Failed", "RebootFailed", "Unknown"), |
| 201 |
job_running_states=("Running", "RebootPending", "Scheduling", "Scheduled", "Downloading", "Waiting", "Paused", |
| 202 |
"New", "PendingActivation", "ReadyForExecution"), |
| 203 |
sleep_interval_secs=10, max_unresponsive_wait=30, initial_wait=1): |
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
max_retries = max_job_wait_sec // sleep_interval_secs |
| 208 |
unresp = max_unresponsive_wait // sleep_interval_secs |
| 209 |
loop_ctr = 0 |
| 210 |
job_failed = True |
| 211 |
job_dict = {} |
| 212 |
wait_time = 0 |
| 213 |
if set(job_complete_states) & set(job_fail_states): |
| 214 |
return job_failed, "Overlapping job states found.", job_dict, wait_time |
| 215 |
msg = "Job tracking started." |
| 216 |
time.sleep(initial_wait) |
| 217 |
while loop_ctr < max_retries: |
| 218 |
loop_ctr += 1 |
| 219 |
try: |
| 220 |
job_resp = rest_obj.invoke_request(job_uri, 'GET') |
| 221 |
job_dict = job_resp.json_data |
| 222 |
job_status = job_dict |
| 223 |
job_status = job_status.get(job_state_var, "Unknown") |
| 224 |
if job_status in job_running_states: |
| 225 |
time.sleep(sleep_interval_secs) |
| 226 |
wait_time = wait_time + sleep_interval_secs |
| 227 |
elif job_status in job_complete_states: |
| 228 |
job_failed = False |
| 229 |
msg = "Job tracking completed." |
| 230 |
loop_ctr = max_retries |
| 231 |
elif job_status in job_fail_states: |
| 232 |
job_failed = True |
| 233 |
msg = "Job is in {0} state.".format(job_status) |
| 234 |
loop_ctr = max_retries |
| 235 |
else: |
| 236 |
time.sleep(sleep_interval_secs) |
| 237 |
wait_time = wait_time + sleep_interval_secs |
| 238 |
except Exception as err: |
| 239 |
if unresp: |
| 240 |
time.sleep(sleep_interval_secs) |
| 241 |
wait_time = wait_time + sleep_interval_secs |
| 242 |
else: |
| 243 |
job_failed = True |
| 244 |
msg = "Exception in job tracking " + str(err) |
| 245 |
break |
| 246 |
unresp = unresp - 1 |
| 247 |
return job_failed, msg, job_dict, wait_time |
| 248 |
|
| 249 |
|
| 250 |
def get_rest_items(rest_obj, uri="DeviceService/Devices", key="Id", value="Identifier", selector="value"): |
| 251 |
item_dict = {} |
| 252 |
resp = rest_obj.get_all_items_with_pagination(uri) |
| 253 |
if resp.get(selector): |
| 254 |
item_dict = dict((item.get(key), item.get(value)) for item in resp[selector]) |
| 255 |
return item_dict |
| 256 |
|
| 257 |
|
| 258 |
def get_item_and_list(rest_obj, name, uri, key='Name', value='value'): |
| 259 |
resp = rest_obj.invoke_request('GET', uri) |
| 260 |
tlist = [] |
| 261 |
if resp.success and resp.json_data.get(value): |
| 262 |
tlist = resp.json_data.get(value, []) |
| 263 |
for xtype in tlist: |
| 264 |
if xtype.get(key, "") == name: |
| 265 |
return xtype, tlist |
| 266 |
return {}, tlist |
| 267 |
|
| 268 |
|
| 269 |
def apply_diff_key(src, dest, klist): |
| 270 |
diff_cnt = 0 |
| 271 |
for k in klist: |
| 272 |
v = src.get(k) |
| 273 |
if v is not None and v != dest.get(k): |
| 274 |
dest[k] = v |
| 275 |
diff_cnt = diff_cnt + 1 |
| 276 |
return diff_cnt |
| 277 |
|
| 278 |
|
| 279 |
def wait_for_job_completion(redfish_obj, uri, job_wait=True, wait_timeout=120, sleep_time=10): |
| 280 |
max_sleep_time = wait_timeout |
| 281 |
sleep_interval = sleep_time |
| 282 |
if job_wait: |
| 283 |
while max_sleep_time: |
| 284 |
if max_sleep_time > sleep_interval: |
| 285 |
max_sleep_time = max_sleep_time - sleep_interval |
| 286 |
else: |
| 287 |
sleep_interval = max_sleep_time |
| 288 |
max_sleep_time = 0 |
| 289 |
time.sleep(sleep_interval) |
| 290 |
job_resp = redfish_obj.invoke_request("GET", uri) |
| 291 |
if job_resp.json_data.get("PercentComplete") == 100: |
| 292 |
time.sleep(10) |
| 293 |
return job_resp, "" |
| 294 |
else: |
| 295 |
job_resp = redfish_obj.invoke_request("GET", uri) |
| 296 |
time.sleep(10) |
| 297 |
return job_resp, "" |
| 298 |
return {}, "The job is not complete after {0} seconds.".format(wait_timeout) |
| 299 |
|
| 300 |
|
| 301 |
def wait_after_idrac_reset(idrac, wait_time_sec, interval=30): |
| 302 |
time.sleep(interval // 2) |
| 303 |
msg = RESET_UNTRACK |
| 304 |
wait = wait_time_sec |
| 305 |
track_failed = True |
| 306 |
while wait > 0: |
| 307 |
try: |
| 308 |
idrac.invoke_request(MANAGERS_URI, 'GET') |
| 309 |
time.sleep(interval // 2) |
| 310 |
msg = RESET_SUCCESS |
| 311 |
track_failed = False |
| 312 |
break |
| 313 |
except Exception: |
| 314 |
time.sleep(interval) |
| 315 |
wait = wait - interval |
| 316 |
return track_failed, msg |
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
def reset_idrac(idrac_restobj, wait_time_sec=300, res_id=MANAGER_ID, interval=30): |
| 321 |
track_failed = True |
| 322 |
reset_msg = "iDRAC reset triggered successfully." |
| 323 |
try: |
| 324 |
idrac_restobj.invoke_request(IDRAC_RESET_URI.format(res_id=res_id), 'POST', |
| 325 |
data={"ResetType": "GracefulRestart"}) |
| 326 |
if wait_time_sec: |
| 327 |
track_failed, reset_msg = wait_after_idrac_reset(idrac_restobj, wait_time_sec, interval) |
| 328 |
reset = True |
| 329 |
except Exception: |
| 330 |
reset = False |
| 331 |
reset_msg = RESET_FAIL |
| 332 |
return reset, track_failed, reset_msg |
| 333 |
|
| 334 |
|
| 335 |
def get_manager_res_id(idrac): |
| 336 |
try: |
| 337 |
resp = idrac.invoke_request(MANAGERS_URI, "GET") |
| 338 |
membs = resp.json_data.get("Members") |
| 339 |
res_uri = membs[0].get(ODATA_ID) |
| 340 |
res_id = res_uri.split("/")[-1] |
| 341 |
except HTTPError: |
| 342 |
res_id = MANAGER_ID |
| 343 |
return res_id |
| 344 |
|
| 345 |
|
| 346 |
def wait_for_idrac_job_completion(idrac, uri, job_wait=True, wait_timeout=120, sleep_time=10): |
| 347 |
max_sleep_time = wait_timeout |
| 348 |
sleep_interval = sleep_time |
| 349 |
job_msg = "The job is not complete after {0} seconds.".format(wait_timeout) |
| 350 |
if job_wait: |
| 351 |
while max_sleep_time: |
| 352 |
if max_sleep_time > sleep_interval: |
| 353 |
max_sleep_time = max_sleep_time - sleep_interval |
| 354 |
else: |
| 355 |
sleep_interval = max_sleep_time |
| 356 |
max_sleep_time = 0 |
| 357 |
time.sleep(sleep_interval) |
| 358 |
job_resp = idrac.invoke_request(uri, "GET") |
| 359 |
if job_resp.json_data.get("PercentComplete") == 100: |
| 360 |
time.sleep(10) |
| 361 |
return job_resp, "" |
| 362 |
if job_resp.json_data.get("JobState") == "RebootFailed": |
| 363 |
time.sleep(10) |
| 364 |
return job_resp, job_msg |
| 365 |
else: |
| 366 |
job_resp = idrac.invoke_request(uri, "GET") |
| 367 |
time.sleep(10) |
| 368 |
return job_resp, "" |
| 369 |
return {}, "The job is not complete after {0} seconds.".format(wait_timeout) |
| 370 |
|
| 371 |
|
| 372 |
def idrac_system_reset(idrac, res_id, payload=None, job_wait=True, wait_time_sec=300, interval=30): |
| 373 |
track_failed, reset, job_resp = True, False, {} |
| 374 |
reset_msg = RESET_UNTRACK |
| 375 |
try: |
| 376 |
resp = idrac.invoke_request(SYSTEM_RESET_URI.format(res_id=res_id), 'POST', data=payload) |
| 377 |
if resp.status_code == 204: |
| 378 |
reset = True |
| 379 |
return reset, track_failed, reset_msg, job_resp |
| 380 |
time.sleep(10) |
| 381 |
if wait_time_sec: |
| 382 |
resp = idrac.invoke_request(MANAGER_JOB_URI_10, "GET") |
| 383 |
job = list(filter(lambda d: d["JobState"] in ["RebootPending", "RebootCompleted"], resp.json_data["Members"])) |
| 384 |
if job: |
| 385 |
job_resp, msg = wait_for_idrac_job_completion(idrac, MANAGER_JOB_ID_URI_10.format(job[0]["Id"]), |
| 386 |
job_wait=job_wait, wait_timeout=wait_time_sec) |
| 387 |
if "job is not complete" in msg: |
| 388 |
reset, reset_msg = False, msg |
| 389 |
if not msg: |
| 390 |
reset = True |
| 391 |
except Exception: |
| 392 |
reset = False |
| 393 |
reset_msg = RESET_FAIL |
| 394 |
return reset, track_failed, reset_msg, job_resp |
| 395 |
|
| 396 |
|
| 397 |
def get_system_res_id(idrac): |
| 398 |
res_id = SYSTEM_ID |
| 399 |
error_msg = "" |
| 400 |
try: |
| 401 |
resp = idrac.invoke_request(SYSTEMS_URI, "GET") |
| 402 |
except HTTPError: |
| 403 |
error_msg = "Unable to complete the request because the resource URI " \ |
| 404 |
"does not exist or is not implemented." |
| 405 |
else: |
| 406 |
member = resp.json_data.get("Members") |
| 407 |
res_uri = member[0].get(ODATA_ID) |
| 408 |
res_id = res_uri.split("/")[-1] |
| 409 |
return res_id, error_msg |
| 410 |
|
| 411 |
|
| 412 |
def get_all_data_with_pagination(ome_obj, uri, query_param=None): |
| 413 |
"""To get all the devices with pagination based on the filter provided.""" |
| 414 |
query, resp, report_list = "", None, [] |
| 415 |
try: |
| 416 |
resp = ome_obj.invoke_request('GET', uri, query_param=query_param) |
| 417 |
next_uri = resp.json_data.get("@odata.nextLink", None) |
| 418 |
report_list = resp.json_data.get("value") |
| 419 |
if query_param is not None: |
| 420 |
for k, v in query_param.items(): |
| 421 |
query += "{0}={1}".format(k, v.replace(" ", "%20")) |
| 422 |
while next_uri is not None: |
| 423 |
next_uri_query = "{0}&{1}".format(next_uri.strip("/api"), query) if query else next_uri.strip("/api") |
| 424 |
resp = ome_obj.invoke_request('GET', next_uri_query) |
| 425 |
report_list.extend(resp.json_data.get("value")) |
| 426 |
next_uri = resp.json_data.get("@odata.nextLink", None) |
| 427 |
except (URLError, HTTPError, SSLValidationError, ConnectionError, TypeError, ValueError) as err: |
| 428 |
raise err |
| 429 |
return {"resp_obj": resp, "report_list": report_list} |
| 430 |
|
| 431 |
|
| 432 |
def remove_key(data, regex_pattern='@odata.'): |
| 433 |
''' |
| 434 |
:param data: the dict/list to be stripped of unwanted keys |
| 435 |
:param remove_char: the substring to be checked among the keys |
| 436 |
:return: dict/list |
| 437 |
''' |
| 438 |
try: |
| 439 |
if isinstance(data, dict): |
| 440 |
for key in list(data.keys()): |
| 441 |
if re.match(regex_pattern, key): |
| 442 |
data.pop(key, None) |
| 443 |
else: |
| 444 |
remove_key(data[key], regex_pattern) |
| 445 |
elif isinstance(data, list): |
| 446 |
for item in data: |
| 447 |
remove_key(item, regex_pattern) |
| 448 |
except Exception: |
| 449 |
pass |
| 450 |
return data |
| 451 |
|
| 452 |
|
| 453 |
def wait_for_redfish_reboot_job(redfish_obj, res_id, payload=None, wait_time_sec=300): |
| 454 |
reset, job_resp, msg = False, {}, "" |
| 455 |
try: |
| 456 |
resp = redfish_obj.invoke_request('POST', SYSTEM_RESET_URI.format(res_id=res_id), data=payload, api_timeout=120) |
| 457 |
time.sleep(10) |
| 458 |
if wait_time_sec and resp.status_code == 204: |
| 459 |
resp = redfish_obj.invoke_request("GET", get_job_uri(redfish_obj)) |
| 460 |
reboot_job_lst = list(filter(lambda d: (d["JobType"] in ["RebootNoForce"]), resp.json_data["Members"])) |
| 461 |
job_resp = max(reboot_job_lst, key=lambda d: datetime.strptime(d["StartTime"], "%Y-%m-%dT%H:%M:%S")) |
| 462 |
if job_resp: |
| 463 |
reset = True |
| 464 |
else: |
| 465 |
msg = RESET_FAIL |
| 466 |
except Exception: |
| 467 |
reset = False |
| 468 |
return job_resp, reset, msg |
| 469 |
|
| 470 |
|
| 471 |
def is_job_complete(percent_complete, job_state, check_completion): |
| 472 |
return percent_complete == 100 and (not check_completion or job_state in {"Completed", "Failed"}) |
| 473 |
|
| 474 |
|
| 475 |
def wait_for_redfish_job_complete(redfish_obj, job_uri, job_wait=True, wait_timeout=120, sleep_time=10, check_completion=False): |
| 476 |
max_sleep_time = wait_timeout |
| 477 |
sleep_interval = sleep_time |
| 478 |
job_msg = "The job is not complete after {0} seconds.".format(wait_timeout) |
| 479 |
job_resp = {} |
| 480 |
|
| 481 |
if job_wait: |
| 482 |
while max_sleep_time: |
| 483 |
if max_sleep_time > sleep_interval: |
| 484 |
max_sleep_time = max_sleep_time - sleep_interval |
| 485 |
else: |
| 486 |
sleep_interval = max_sleep_time |
| 487 |
max_sleep_time = 0 |
| 488 |
time.sleep(sleep_interval) |
| 489 |
job_resp = redfish_obj.invoke_request("GET", job_uri, api_timeout=120) |
| 490 |
job_data = job_resp.json_data |
| 491 |
job_state = job_data.get("JobState") |
| 492 |
percent_complete = job_data.get("PercentComplete") |
| 493 |
|
| 494 |
if is_job_complete(percent_complete, job_state, check_completion): |
| 495 |
time.sleep(10) |
| 496 |
return job_resp, "" |
| 497 |
if job_state == "RebootFailed": |
| 498 |
time.sleep(10) |
| 499 |
return job_resp, job_msg |
| 500 |
else: |
| 501 |
time.sleep(10) |
| 502 |
job_resp = redfish_obj.invoke_request("GET", job_uri, api_timeout=120) |
| 503 |
return job_resp, "" |
| 504 |
|
| 505 |
return job_resp, job_msg |
| 506 |
|
| 507 |
|
| 508 |
def get_dynamic_uri(idrac_obj, base_uri, search_label=''): |
| 509 |
args = getfullargspec(idrac_obj.invoke_request)[0] |
| 510 |
data = {'uri': base_uri} if 'uri' in args else {'path': base_uri} |
| 511 |
resp = idrac_obj.invoke_request(method='GET', **data).json_data |
| 512 |
if search_label: |
| 513 |
if search_label in resp: |
| 514 |
return resp[search_label] |
| 515 |
return None |
| 516 |
return resp |
| 517 |
|
| 518 |
|
| 519 |
def get_scheduled_job_resp(idrac_obj, job_type): |
| 520 |
job_state = {"Scheduled", "New", "Running"} |
| 521 |
args = getfullargspec(idrac_obj.invoke_request)[0] |
| 522 |
data = {'uri': get_job_uri(idrac_obj)} if 'uri' in args else {'path': get_job_uri(idrac_obj)} |
| 523 |
job_list = idrac_obj.invoke_request(method="GET", **data).json_data.get('Members', []) |
| 524 |
if isinstance(job_type, str): |
| 525 |
job_resp = next((j for j in job_list if (j.get("JobState") in job_state) and (j.get("JobType") == job_type)), {}) |
| 526 |
elif isinstance(job_type, list): |
| 527 |
job_resp = next((j for j in job_list if (j.get("JobState") in job_state) and (j.get("JobType") in job_type)), {}) |
| 528 |
return remove_key(job_resp, regex_pattern='(.*?)@odata') |
| 529 |
|
| 530 |
|
| 531 |
def delete_job(idrac_obj, job_id): |
| 532 |
resp = idrac_obj.invoke_request(uri=get_job_uri_id(idrac_obj).format(job_id), method="DELETE") |
| 533 |
return resp.json_data |
| 534 |
|
| 535 |
|
| 536 |
def get_current_time(redfish_obj): |
| 537 |
res_id = get_manager_res_id(redfish_obj) |
| 538 |
resp = redfish_obj.invoke_request(MANAGERS_URI + '/' + res_id, "GET") |
| 539 |
curr_time = resp.json_data.get("DateTime") |
| 540 |
date_offset = resp.json_data.get("DateTimeLocalOffset") |
| 541 |
return curr_time, date_offset |
| 542 |
|
| 543 |
|
| 544 |
def xml_data_conversion(attr_dict, fqdd=None, custom_payload_to_add=None): |
| 545 |
component = """<Component FQDD="{0}">{1}</Component>""" |
| 546 |
attr = "" |
| 547 |
for k, v in attr_dict.items(): |
| 548 |
key = re.sub(r"\.(?!\d)", "#", k) |
| 549 |
attr += '<Attribute Name="{0}">{1}</Attribute>'.format(key, v) |
| 550 |
if custom_payload_to_add: |
| 551 |
attr += custom_payload_to_add |
| 552 |
root = component.format(fqdd, attr) |
| 553 |
return root |
| 554 |
|
| 555 |
|
| 556 |
def validate_and_get_first_resource_id_uri(resource_id, idrac, base_uri): |
| 557 |
found = False |
| 558 |
res_id_uri = None |
| 559 |
if resource_id and not isinstance(resource_id, str): |
| 560 |
resource_id = resource_id.params.get('resource_id') |
| 561 |
res_id_members = get_dynamic_uri(idrac, base_uri, 'Members') |
| 562 |
for each in res_id_members: |
| 563 |
if resource_id and resource_id == each[ODATA_ID].split('/')[-1]: |
| 564 |
res_id_uri = each[ODATA_ID] |
| 565 |
found = True |
| 566 |
break |
| 567 |
if not found and resource_id: |
| 568 |
return res_id_uri, INVALID_ID_MSG.format( |
| 569 |
resource_id, 'resource_id') |
| 570 |
elif resource_id is None: |
| 571 |
res_id_uri = res_id_members[0][ODATA_ID] |
| 572 |
return res_id_uri, '' |
| 573 |
|
| 574 |
|
| 575 |
def get_idrac_firmware_version(idrac): |
| 576 |
args = getfullargspec(idrac.invoke_request)[0] |
| 577 |
data = {'uri': GET_IDRAC_FIRMWARE_VER_URI} if 'uri' in args else {'path': GET_IDRAC_FIRMWARE_VER_URI} |
| 578 |
firm_version = idrac.invoke_request(method='GET', **data) |
| 579 |
return firm_version.json_data.get('FirmwareVersion', '') |
| 580 |
|
| 581 |
|
| 582 |
def get_ome_version(ome_obj): |
| 583 |
resp = ome_obj.invoke_request('GET', OME_INFO) |
| 584 |
return resp.json_data.get("Version") |
| 585 |
|
| 586 |
|
| 587 |
def trigger_restart_operation(idrac, restart_type="GracefulRestart", resource_id=None): |
| 588 |
resp, error_msg = {}, {} |
| 589 |
uri, error_msg = validate_and_get_first_resource_id_uri(resource_id, idrac, SYSTEMS_URI) |
| 590 |
if error_msg: |
| 591 |
return resp, error_msg |
| 592 |
actions_uri = get_dynamic_uri(idrac, uri, 'Actions').get("#ComputerSystem.Reset", {}).get("target", '') |
| 593 |
payload = {"ResetType": restart_type} |
| 594 |
resp = idrac.invoke_request(method='POST', uri=actions_uri, data=payload) |
| 595 |
return resp, error_msg |
| 596 |
|
| 597 |
|
| 598 |
def wait_for_lc_status(idrac, job_wait_timeout=300, resource_id=None, interval=10): |
| 599 |
lc_status_completed, error_msg = False, '' |
| 600 |
lcstatus = "" |
| 601 |
retry_count = 1 |
| 602 |
|
| 603 |
|
| 604 |
waiting_before_lc_status_check = 12 * interval |
| 605 |
if job_wait_timeout >= waiting_before_lc_status_check: |
| 606 |
time.sleep(waiting_before_lc_status_check) |
| 607 |
job_wait_timeout = job_wait_timeout - waiting_before_lc_status_check |
| 608 |
max_idrac_reset_try = job_wait_timeout // interval |
| 609 |
uri, error_msg = validate_and_get_first_resource_id_uri(resource_id, idrac, MANAGERS_URI) |
| 610 |
if error_msg: |
| 611 |
return lc_status_completed, error_msg |
| 612 |
resp = get_dynamic_uri(idrac, uri, "Links") |
| 613 |
url = resp.get("Oem", {}).get("Dell", {}).get('DellLCService', {}).get(ODATA_ID, {}) |
| 614 |
if url: |
| 615 |
action_resp = get_dynamic_uri(idrac, url) |
| 616 |
lc_url = action_resp.get('Actions', {}).get('#DellLCService.GetRemoteServicesAPIStatus', {}).get('target', {}) |
| 617 |
else: |
| 618 |
return lc_status_completed, UNSUPPORTED_LC_STATUS_MSG |
| 619 |
lc_resp = idrac.invoke_request(lc_url, "POST", data="{}", dump=False) |
| 620 |
lcstatus = lc_resp.json_data.get('LCStatus') |
| 621 |
while retry_count < max_idrac_reset_try: |
| 622 |
try: |
| 623 |
lc_resp = idrac.invoke_request(lc_url, "POST", data="{}", dump=False) |
| 624 |
lcstatus = lc_resp.json_data.get('LCStatus') |
| 625 |
if lcstatus == 'Ready': |
| 626 |
lc_status_completed = True |
| 627 |
break |
| 628 |
time.sleep(interval) |
| 629 |
retry_count = retry_count + 1 |
| 630 |
except URLError: |
| 631 |
time.sleep(interval) |
| 632 |
retry_count = retry_count + 1 |
| 633 |
if retry_count == max_idrac_reset_try: |
| 634 |
error_msg = LC_STATUS_MSG.format(lc_status='unreachable', retries=max_idrac_reset_try) |
| 635 |
break |
| 636 |
if retry_count == max_idrac_reset_try and lcstatus != "Ready": |
| 637 |
error_msg = LC_STATUS_MSG.format(lc_status=lcstatus, retries=retry_count) |
| 638 |
return lc_status_completed, error_msg |
| 639 |
|
| 640 |
|
| 641 |
def get_lc_log_or_current_log_time(idrac, curr_time=None, lc_log_ids_list=None, resource_id=None): |
| 642 |
lc_log_found = False |
| 643 |
msg = "No LC log found." |
| 644 |
|
| 645 |
uri, error_msg = validate_and_get_first_resource_id_uri( |
| 646 |
resource_id, idrac, MANAGERS_URI |
| 647 |
) |
| 648 |
if error_msg: |
| 649 |
return lc_log_found, error_msg |
| 650 |
|
| 651 |
log_services_uri = get_dynamic_uri(idrac, uri, "LogServices").get( |
| 652 |
ODATA_ID, {} |
| 653 |
) |
| 654 |
log_svc_member = get_dynamic_uri(idrac, log_services_uri, "Members") |
| 655 |
log_lc_uri = [ |
| 656 |
each[ODATA_ID] |
| 657 |
for each in log_svc_member |
| 658 |
if each[ODATA_ID].split("/")[-1] == "Lclog" |
| 659 |
][0] |
| 660 |
log_entries_uri = get_dynamic_uri( |
| 661 |
idrac, log_lc_uri, "Entries" |
| 662 |
).get(ODATA_ID, {}) |
| 663 |
|
| 664 |
try: |
| 665 |
resp = idrac.invoke_request(log_lc_uri, "GET") |
| 666 |
logs_list = idrac.invoke_request(log_entries_uri, "GET").json_data.get( |
| 667 |
"Members" |
| 668 |
) |
| 669 |
|
| 670 |
if not curr_time: |
| 671 |
curr_time = resp.json_data.get("DateTime") |
| 672 |
|
| 673 |
if not lc_log_ids_list: |
| 674 |
return curr_time |
| 675 |
|
| 676 |
for log in logs_list: |
| 677 |
if log.get("Created") >= curr_time: |
| 678 |
for err_id in lc_log_ids_list: |
| 679 |
if err_id in log.get("MessageId"): |
| 680 |
lc_log_found = True |
| 681 |
msg = log.get("Message") |
| 682 |
break |
| 683 |
|
| 684 |
except Exception: |
| 685 |
msg = "No LC log found." |
| 686 |
|
| 687 |
return lc_log_found, msg |
| 688 |
|
| 689 |
|
| 690 |
def expand_ipv6(ip): |
| 691 |
sections = ip.split(':') |
| 692 |
num_sections = len(sections) |
| 693 |
double_colon_index = sections.index('') if '' in sections else -1 |
| 694 |
if double_colon_index != -1: |
| 695 |
missing_sections = 8 - num_sections + 1 |
| 696 |
sections[double_colon_index:double_colon_index + 1] = ['0000'] * missing_sections |
| 697 |
sections = [section.zfill(4) for section in sections] |
| 698 |
expanded_ip = ':'.join(sections) |
| 699 |
return expanded_ip |
| 700 |
|
| 701 |
|
| 702 |
def cert_file_format_string(ip, prefix="", |
| 703 |
postfix="", |
| 704 |
datetime_format="%Y%m%d_%H%M%S"): |
| 705 |
now = datetime.now() |
| 706 |
hostname = expand_ipv6(ip).replace(":", ".") |
| 707 |
data = f"{prefix}{hostname}_{now.strftime(datetime_format)}{postfix}" |
| 708 |
return data |
| 709 |
|
| 710 |
|
| 711 |
def track_power_state(idrac, base_uri, desired_state, retries=POWER_CHECK_RETRIES, interval=POWER_CHECK_INTERVAL): |
| 712 |
count = retries |
| 713 |
while count: |
| 714 |
ps = get_power_state(idrac, base_uri) |
| 715 |
if ps in desired_state: |
| 716 |
achieved = True |
| 717 |
break |
| 718 |
else: |
| 719 |
time.sleep(interval) |
| 720 |
count = count - 1 |
| 721 |
else: |
| 722 |
achieved = False |
| 723 |
return achieved |
| 724 |
|
| 725 |
|
| 726 |
def get_power_state(idrac, base_uri): |
| 727 |
retries = 10 |
| 728 |
pstate = "Unknown" |
| 729 |
while retries > 0: |
| 730 |
try: |
| 731 |
resp = idrac.invoke_request(base_uri, "GET") |
| 732 |
pstate = resp.json_data.get("PowerState") |
| 733 |
break |
| 734 |
except Exception: |
| 735 |
retries = retries - 1 |
| 736 |
return pstate |
| 737 |
|
| 738 |
|
| 739 |
def power_act_host(idrac, system_uri, p_state): |
| 740 |
try: |
| 741 |
_resp, error_msg = {}, {} |
| 742 |
uri, error_msg = validate_and_get_first_resource_id_uri(None, idrac, system_uri) |
| 743 |
if error_msg: |
| 744 |
return False |
| 745 |
actions_uri = get_dynamic_uri(idrac, uri, 'Actions').get("#ComputerSystem.Reset", {}).get("target", '') |
| 746 |
idrac.invoke_request(actions_uri, "POST", data={'ResetType': p_state}) |
| 747 |
p_act = True |
| 748 |
except HTTPError: |
| 749 |
p_act = False |
| 750 |
return p_act |
| 751 |
|
| 752 |
|
| 753 |
def reset_host(idrac, restart_type, system_uri, base_uri): |
| 754 |
p_state = 'On' |
| 755 |
ps = get_power_state(idrac, base_uri) |
| 756 |
on_state = ["On"] |
| 757 |
if ps in on_state: |
| 758 |
p_state = 'GracefulShutdown' |
| 759 |
if 'Force' in restart_type: |
| 760 |
p_state = 'ForceOff' |
| 761 |
p_act = power_act_host(idrac, system_uri, p_state) |
| 762 |
if not p_act: |
| 763 |
return False |
| 764 |
state_achieved = track_power_state(idrac, base_uri, ["Off"]) |
| 765 |
p_state = "On" |
| 766 |
if not state_achieved: |
| 767 |
time.sleep(10) |
| 768 |
p_state = "ForceRestart" |
| 769 |
p_act = power_act_host(idrac, system_uri, p_state) |
| 770 |
if not p_act: |
| 771 |
return False |
| 772 |
state_achieved = track_power_state(idrac, base_uri, on_state) |
| 773 |
return state_achieved |
| 774 |
|
| 775 |
|
| 776 |
def validate_job_wait(module): |
| 777 |
""" |
| 778 |
Validates job_wait and job_wait_timeout parameters. |
| 779 |
:param module: The Ansible module instance. |
| 780 |
:param job_wait_param: The name of the job wait parameter to check (default is "job_wait"). |
| 781 |
:param job_wait_timeout_param: The name of the job wait timeout parameter to check (default is "job_wait_timeout"). |
| 782 |
""" |
| 783 |
job_wait = module.params.get('job_wait') |
| 784 |
job_wait_timeout = module.params.get('job_wait_timeout') |
| 785 |
|
| 786 |
if job_wait and (job_wait_timeout is None or job_wait_timeout <= 0): |
| 787 |
return True |
| 788 |
|
| 789 |
return False |
| 790 |
|
| 791 |
|
| 792 |
def validate_time(time, module): |
| 793 |
|
| 794 |
if not isinstance(time, str): |
| 795 |
module.exit_json(msg="Time must be a string in HH:MM format", failed=True) |
| 796 |
|
| 797 |
|
| 798 |
if time and not re.match(r"^(?:[01]\d|2[0-3]):[0-5]\d$", time): |
| 799 |
module.exit_json(msg=INVALID_TIME_FORMAT_MSG, failed=True) |
| 800 |
|
| 801 |
|
| 802 |
def get_job_uri_id(rest_obj): |
| 803 |
firmware_obj = IDRACFirmwareInfo(rest_obj) |
| 804 |
job_uri_id = MANAGER_JOB_ID_URI |
| 805 |
if not firmware_obj.is_omsdk_required(): |
| 806 |
job_uri_id = MANAGER_JOB_ID_URI_10 |
| 807 |
return job_uri_id |
| 808 |
|
| 809 |
|
| 810 |
def get_job_uri(rest_obj): |
| 811 |
firmware_obj = IDRACFirmwareInfo(rest_obj) |
| 812 |
job_uri = MANAGER_JOB_URI |
| 813 |
if not firmware_obj.is_omsdk_required(): |
| 814 |
job_uri = MANAGER_JOB_URI_10 |
| 815 |
return job_uri |
| 816 |
|
| 817 |
|
| 818 |
def get_logger(module_name, log_file_name='ansible_openmanage.log', |
| 819 |
log_devel=logging.INFO): |
| 820 |
FORMAT = '%(asctime)-15s %(filename)s %(levelname)s : %(message)s' |
| 821 |
max_bytes = 5 * 1024 * 1024 |
| 822 |
logging.basicConfig(filename=log_file_name, format=FORMAT) |
| 823 |
LOG = logging.getLogger(module_name) |
| 824 |
LOG.setLevel(log_devel) |
| 825 |
handler = CustomRotatingFileHandler(log_file_name, |
| 826 |
maxBytes=max_bytes, |
| 827 |
backupCount=5) |
| 828 |
formatter = logging.Formatter(FORMAT) |
| 829 |
handler.setFormatter(formatter) |
| 830 |
LOG.addHandler(handler) |
| 831 |
LOG.propagate = False |
| 832 |
return LOG |