Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/idrac_diagnostics.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2024-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14
15 __metaclass__ = type
16
17 DOCUMENTATION = r"""
18 ---
19 module: idrac_diagnostics
20 short_description: Run and Export iDRAC diagnostics
21 version_added: "9.0.0"
22 description:
23 - This module allows you to run and export diagnostics on iDRAC.
24 extends_documentation_fragment:
25 - dellemc.openmanage.idrac_x_auth_options
26 options:
27 run:
28 description:
29 - Run the diagnostics job on iDRAC.
30 - Run the diagnostics job based on the I(run_mode) and save the report in the internal storage. I(reboot_type) is applicable.
31 type: bool
32 export:
33 description:
34 - Exports the diagnostics information to the given share.
35 - This operation requires I(share_parameters).
36 - When I(run) is C(true) and I(job_wait) is C(false), only then the run diagnostics job is triggered. I(export) is ignored.
37 type: bool
38 run_mode:
39 description:
40 - This option provides the choices to run the diagnostics.
41 - C(express) The express diagnostics runs a test package for each server subsystem. However,
42 it does not run the complete set of tests available in the package for each subsystem.
43 - C(extended) The extended diagnostics run all available tests in each test package for all subsystems.
44 - C(long_run) The long-run diagnostics runs express and extended tests.
45 type: str
46 choices: [express, extended, long_run]
47 default: express
48 reboot_type:
49 description:
50 - This option provides the choice to reboot the host immediately to run the diagnostics.
51 - This is applicable when I(run) is C(true).
52 - C(force) Forced graceful shutdown signals the operating system to turn off and wait for ten minutes.
53 If the operating system does not turn off, the iDRAC power cycles the system.
54 - C(graceful) Graceful shutdown waits for the operating system to turn off and wait for the system to restart.
55 - C(power_cycle) performs a power cycle for a hard reset on the device.
56 type: str
57 choices: [force, graceful, power_cycle]
58 default: graceful
59 scheduled_start_time:
60 description:
61 - Schedules the job at the specified time.
62 - The accepted formats are yyyymmddhhmmss and YYYY-MM-DDThh:mm:ss+HH:MM.
63 - This is applicable when I(run) is C(true) and I(reboot_type) is power_cycle.
64 type: str
65 scheduled_end_time:
66 description:
67 - Run the diagnostic until the specified end date and end time after the I(scheduled_start_time).
68 - The accepted formats are yyyymmddhhmmss and YYYY-MM-DDThh:mm:ss+HH:MM.
69 - If the run operation does not complete before the specified end time, then the operation fails.
70 - This is applicable when I(run) is C(True) and I(reboot_type) is C(power_cycle).
71 type: str
72 job_wait:
73 description:
74 - Provides the option to wait for job completion.
75 - This is applicable when I(run) is C(true) and I(reboot_type) is C(power_cycle).
76 - This is applicable only to run the diagnostics job.
77 type: bool
78 default: true
79 job_wait_timeout:
80 description:
81 - Time in seconds to wait for job completion.
82 - This is applicable when I(job_wait) is C(true).
83 type: int
84 default: 1200
85 share_parameters:
86 description:
87 - Parameters that are required for the export operation of diagnostics.
88 - I(share_parameters) is required when I(export) is C(true).
89 type: dict
90 suboptions:
91 share_type:
92 description:
93 - Share type of the network share.
94 - C(local) uses local path for I(export) operation.
95 - C(nfs) uses NFS share for I(export) operation.
96 - C(cifs) uses CIFS share for I(export) operation.
97 - C(http) uses HTTP share for I(export) operation.
98 - C(https) uses HTTPS share for I(export) operation.
99 type: str
100 choices: [local, nfs, cifs, http, https]
101 default: local
102 file_name:
103 description:
104 - Diagnostics file name for I(export) operation.
105 type: str
106 ip_address:
107 description:
108 - IP address of the network share.
109 - I(ip_address) is required when I(share_type) is C(nfs), C(cifs), C(http) or C(https).
110 type: str
111 share_name:
112 description:
113 - Network share or local path of the diagnostics file.
114 type: str
115 workgroup:
116 description:
117 - Workgroup of the network share.
118 - I(workgroup) is applicable only when I(share_type) is C(cifs).
119 type: str
120 username:
121 description:
122 - Username of the network share.
123 - I(username) is required when I(share_type) is C(cifs).
124 type: str
125 password:
126 description:
127 - Password of the network share.
128 - I(password) is required when I(share_type) is C(cifs).
129 type: str
130 ignore_certificate_warning:
131 description:
132 - Ignores the certificate warning while connecting to Share and is only applicable when I(share_type) is C(https).
133 - C(on) ignores the certificate warning.
134 - C(off) does not ignore the certificate warning.
135 type: str
136 choices: ["off", "on"]
137 default: "off"
138 proxy_support:
139 description:
140 - Specifies if proxy support must be used or not.
141 - C(off) does not use proxy settings.
142 - C(default_proxy) uses the default proxy settings.
143 - C(parameters_proxy) uses the specified proxy settings. I(proxy_server) is required when I(proxy_support) is C(parameters_proxy).
144 - I(proxy_support) is only applicable when I(share_type) is C(http) or C(https).
145 type: str
146 choices: ["off", "default_proxy", "parameters_proxy"]
147 default: "off"
148 proxy_type:
149 description:
150 - The proxy type of the proxy server.
151 - C(http) to select HTTP proxy.
152 - C(socks) to select SOCKS proxy.
153 - I(proxy_type) is only applicable when I(share_type) is C(http) or C(https) and when I(proxy_support) is C(parameters_proxy).
154 type: str
155 choices: [http, socks]
156 default: http
157 proxy_server:
158 description:
159 - The IP address of the proxy server.
160 - I(proxy_server) is required when I(proxy_support) is C(parameters_proxy).
161 - I(proxy_server) is only applicable when I(share_type) is C(http) or C(https) and when I(proxy_support) is C(parameters_proxy).
162 type: str
163 proxy_port:
164 description:
165 - The port of the proxy server.
166 - I(proxy_port) is only applicable when I(share_type) is C(http) or C(https) and when I(proxy_support) is C(parameters_proxy).
167 type: int
168 default: 80
169 proxy_username:
170 description:
171 - The username of the proxy server.
172 - I(proxy_username) is only applicable when I(share_type) is C(http) or C(https) and when I(proxy_support) is C(parameters_proxy).
173 type: str
174 proxy_password:
175 description:
176 - The password of the proxy server.
177 - I(proxy_password) is only applicable when I(share_type) is C(http) or C(https) and when I(proxy_support) is C(parameters_proxy).
178 type: str
179 resource_id:
180 type: str
181 description:
182 - Id of the resource.
183 - If the value for resource ID is not provided, the module picks the first resource ID available from the list of system resources returned by the iDRAC.
184 requirements:
185 - "python >= 3.9.6"
186 author:
187 - "Shivam Sharma(@ShivamSh3)"
188 notes:
189 - Run this module from a system that has direct access to Dell iDRAC.
190 - This module supports only iDRAC9 and above.
191 - This module supports IPv4 and IPv6 addresses.
192 - This module supports C(check_mode).
193 - This module requires 'Dell Diagnostics' firmware package to be present on the server.
194 - When I(share_type) is C(local) for I(export) operation, job_details are not displayed.
195 """
196
197 EXAMPLES = r"""
198 ---
199 - name: Run and export the diagnostics to local path
200 dellemc.openmanage.idrac_diagnostics:
201 hostname: "192.168.0.1"
202 username: "username"
203 password: "password"
204 ca_path: "path/to/ca_file"
205 run: true
206 export: true
207 share_parameters:
208 share_type: "local"
209 share_path: "/opt/local/diagnostics/"
210 file_name: "diagnostics.txt"
211
212 - name: Run the diagnostics with power cycle reboot on schedule
213 dellemc.openmanage.idrac_diagnostics:
214 hostname: "192.168.0.1"
215 username: "username"
216 password: "password"
217 ca_path: "path/to/ca_file"
218 run: true
219 run_mode: "express"
220 reboot_type: "power_cycle"
221 scheduled_start_time: 20240101101015
222
223 - name: Run and export the diagnostics to HTTPS share
224 dellemc.openmanage.idrac_diagnostics:
225 hostname: "192.168.0.1"
226 username: "username"
227 password: "password"
228 ca_path: "path/to/ca_file"
229 run: true
230 export: true
231 share_parameters:
232 share_type: "HTTPS"
233 ignore_certificate_warning: "on"
234 share_name: "/share_path/diagnostics_collection_path"
235 ip_address: "192.168.0.2"
236 file_name: "diagnostics.txt"
237
238 - name: Run and export the diagnostics to NFS share
239 dellemc.openmanage.idrac_diagnostics:
240 hostname: "192.168.0.1"
241 username: "username"
242 password: "password"
243 ca_path: "path/to/ca_file"
244 run: true
245 export: true
246 share_parameters:
247 share_type: "NFS"
248 share_name: "nfsshare/diagnostics_collection_path/"
249 ip_address: "192.168.0.3"
250 file_name: "diagnostics.txt"
251
252 - name: Export the diagnostics to CIFS share
253 dellemc.openmanage.idrac_diagnostics:
254 hostname: "192.168.0.1"
255 username: "username"
256 password: "password"
257 ca_path: "path/to/ca_file"
258 export: true
259 share_parameters:
260 share_type: "CIFS"
261 share_name: "/cifsshare/diagnostics_collection_path/"
262 ip_address: "192.168.0.4"
263 file_name: "diagnostics.txt"
264
265 - name: Export the diagnostics to HTTPS share via proxy
266 dellemc.openmanage.idrac_diagnostics:
267 hostname: "192.168.0.1"
268 username: "username"
269 password: "password"
270 ca_path: "path/to/ca_file"
271 export: true
272 share_parameters:
273 share_type: "HTTPS"
274 share_name: "/share_path/diagnostics_collection_path"
275 ignore_certificate_warning: "on"
276 ip_address: "192.168.0.2"
277 file_name: "diagnostics.txt"
278 proxy_support: parameters_proxy
279 proxy_type: http
280 proxy_server: "192.168.0.5"
281 proxy_port: 1080
282 proxy_username: "proxy_user"
283 proxy_password: "proxy_password"
284 """
285
286 RETURN = r'''
287 ---
288 msg:
289 type: str
290 description: Status of the diagnostics operation.
291 returned: always
292 sample: "Successfully ran and exported the diagnostics."
293 job_details:
294 description: Returns the output for status of the job.
295 returned: For run and export operations
296 type: dict
297 sample: {
298 "ActualRunningStartTime": "2024-01-10T10:14:31",
299 "ActualRunningStopTime": "2024-01-10T10:26:34",
300 "CompletionTime": "2024-01-10T10:26:34",
301 "Description": "Job Instance",
302 "EndTime": "2024-01-10T10:30:15",
303 "Id": "JID_XXXXXXXXXXXX",
304 "JobState": "Completed",
305 "JobType": "RemoteDiagnostics",
306 "Message": "Job completed successfully.",
307 "MessageArgs": [],
308 "[email protected]": 0,
309 "MessageId": "SYS018",
310 "Name": "Remote Diagnostics",
311 "PercentComplete": 100,
312 "StartTime": "2024-01-10T10:12:15",
313 "TargetSettingsURI": null
314 }
315 diagnostics_file_path:
316 description: Returns the full path of the diagnostics file.
317 returned: For export operation
318 type: str
319 sample: "/share_path/diagnostics_collection_path/diagnostics.txt"
320 error_info:
321 description: Details of the HTTP Error.
322 returned: on HTTP error
323 type: dict
324 sample: {
325 "error": {
326 "code": "Base.1.12.GeneralError",
327 "message": "A general error has occurred. See ExtendedInfo for more information.",
328 "@Message.ExtendedInfo": [
329 {
330 "Message": "A Remote Diagnostic (ePSA) job already exists.",
331 "MessageArgs": [],
332 "[email protected]": 0,
333 "MessageId": "IDRAC.2.9.SYS098",
334 "RelatedProperties": [],
335 "[email protected]": 0,
336 "Resolution": "A response action is not required if the scheduled start time of the existing Remote Diagnostic (ePSA) job is ok.
337 Else, delete the existing Diagnostics (ePSA) job and recreate another with an appropriate start time.",
338 "Severity": "Informational"
339 }
340 ]
341 }
342 }
343 '''
344
345 import json
346 import os
347 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import iDRACRedfishAPI, IdracAnsibleModule
348 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
349 from ansible.module_utils.urls import ConnectionError, SSLValidationError
350 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import (
351 config_ipv6, get_current_time, get_dynamic_uri, validate_and_get_first_resource_id_uri, remove_key, idrac_redfish_job_tracking)
352 from datetime import datetime
353
354 MANAGERS_URI = "/redfish/v1/Managers"
355
356 OEM = "Oem"
357 MANUFACTURER = "Dell"
358 JOBS = "Jobs"
359 JOBS_EXPAND = "?$expand=*($levels=1)"
360 LC_SERVICE = "DellLCService"
361 ACTIONS = "Actions"
362 EXPORT = "#DellLCService.ExportePSADiagnosticsResult"
363 RUN = "#DellLCService.RunePSADiagnostics"
364 TEST_SHARE = "#DellLCService.TestNetworkShare"
365 ODATA_REGEX = "(.*?)@odata"
366 ODATA = "@odata.id"
367 MESSAGE_EXTENDED_INFO = "@Message.ExtendedInfo"
368 TIME_FORMAT_FILE = "%Y%m%d_%H%M%S"
369 TIME_FORMAT_WITHOUT_OFFSET = "%Y%m%d%H%M%S"
370 TIME_FORMAT_WITH_OFFSET = "%Y-%m-%dT%H:%M:%S%z"
371 SUCCESS_EXPORT_MSG = "Successfully exported the diagnostics."
372 SUCCESS_RUN_MSG = "Successfully ran the diagnostics operation."
373 SUCCESS_RUN_AND_EXPORT_MSG = "Successfully ran and exported the diagnostics."
374 RUNNING_RUN_MSG = "Successfully triggered the job to run diagnostics."
375 ALREADY_RUN_MSG = "The diagnostics job is already present."
376 INVALID_DIRECTORY_MSG = "Provided directory path '{path}' is not valid."
377 NO_OPERATION_SKIP_MSG = "The operation is skipped."
378 INSUFFICIENT_DIRECTORY_PERMISSION_MSG = "Provided directory path '{path}' is not writable. " \
379 "Please check if the directory has appropriate permissions"
380 UNSUPPORTED_FIRMWARE_MSG = "iDRAC firmware version is not supported."
381 TIMEOUT_NEGATIVE_OR_ZERO_MSG = "The parameter `job_wait_timeout` value cannot be negative or zero."
382 WAIT_TIMEOUT_MSG = "The job is not complete after {0} seconds."
383 START_TIME = "The specified scheduled time occurs in the past, " \
384 "provide a future time to schedule the job."
385 INVALID_TIME = "The specified date and time `{0}` to schedule the diagnostics is not valid. Enter a valid date and time."
386 END_START_TIME = "The end time `{0}` to schedule the diagnostics must be greater than the start time `{1}`."
387 CHANGES_FOUND_MSG = "Changes found to be applied."
388 NO_FILE = "The diagnostics file does not exist."
389
390 PROXY_SUPPORT = {"off": "Off", "default_proxy": "DefaultProxy", "parameters_proxy": "ParametersProxy"}
391 STATUS_SUCCESS = [200, 202]
392
393
394 class Diagnostics:
395
396 def __init__(self, idrac, module):
397 self.idrac = idrac
398 self.module = module
399 self.diagnostics_file_path = None
400 self.run_url = None
401 self.export_url = None
402 self.share_name = None
403 self.file_name = None
404
405 def execute(self):
406 # To be overridden by the subclasses
407 pass
408
409 def get_payload_details(self):
410 payload = {}
411 payload["ShareType"] = self.module.params.get('share_parameters').get('share_type').upper()
412 payload["IPAddress"] = self.module.params.get('share_parameters').get('ip_address')
413 payload["ShareName"] = self.module.params.get('share_parameters').get('share_name')
414 payload["UserName"] = self.module.params.get('share_parameters').get('username')
415 payload["Password"] = self.module.params.get('share_parameters').get('password')
416 payload["FileName"] = self.module.params.get('share_parameters').get('file_name')
417 payload["IgnoreCertWarning"] = self.module.params.get('share_parameters').get('ignore_certificate_warning').capitalize()
418 if self.module.params.get('share_parameters').get('proxy_support') == "parameters_proxy":
419 payload["ProxySupport"] = PROXY_SUPPORT[self.module.params.get('share_parameters').get('proxy_support')]
420 payload["ProxyType"] = self.module.params.get('share_parameters').get('proxy_type').upper()
421 payload["ProxyServer"] = self.module.params.get('share_parameters').get('proxy_server')
422 payload["ProxyPort"] = str(self.module.params.get('share_parameters').get('proxy_port'))
423 if self.module.params.get('share_parameters').get('proxy_username') and self.module.params.get('share_parameters').get('proxy_password'):
424 payload["ProxyUname"] = self.module.params.get('share_parameters').get('proxy_username')
425 payload["ProxyPasswd"] = self.module.params.get('share_parameters').get('proxy_password')
426 return payload
427
428 def test_network_share(self):
429 payload = self.get_payload_details()
430 del payload["FileName"]
431 payload = {key: value for key, value in payload.items() if value is not None}
432 if payload.get("ShareType") == "LOCAL":
433 path = payload.get("ShareName")
434 if not (os.path.exists(path)):
435 self.module.exit_json(msg=INVALID_DIRECTORY_MSG.format(path=path), failed=True)
436 if not os.access(path, os.W_OK):
437 self.module.exit_json(msg=INSUFFICIENT_DIRECTORY_PERMISSION_MSG.format(path=path), failed=True)
438 else:
439 try:
440 test_url = self.get_test_network_share_url()
441 self.idrac.invoke_request(test_url, "POST", data=payload)
442 except HTTPError as err:
443 filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX)
444 message_details = filter_err.get('error').get(MESSAGE_EXTENDED_INFO)[0]
445 message = message_details.get('Message')
446 self.module.exit_json(msg=message, error_info=filter_err, failed=True)
447
448 def get_test_network_share_url(self):
449 uri, error_msg = validate_and_get_first_resource_id_uri(
450 self.module, self.idrac, MANAGERS_URI)
451 if error_msg:
452 self.module.exit_json(msg=error_msg, failed=True)
453 resp = get_dynamic_uri(self.idrac, uri)
454 url = resp.get('Links', {}).get(OEM, {}).get(MANUFACTURER, {}).get(LC_SERVICE, {}).get(ODATA, {})
455 action_resp = get_dynamic_uri(self.idrac, url)
456 url = action_resp.get(ACTIONS, {}).get(TEST_SHARE, {}).get('target', {})
457 return url
458
459
460 class RunDiagnostics(Diagnostics):
461
462 def execute(self):
463 msg, job_details = None, None
464 if self.module.params.get('export'):
465 self.test_network_share()
466 self.__get_run_diagnostics_url()
467 self.check_diagnostics_jobs()
468 self.__validate_job_timeout()
469 run_diagnostics_status = self.__run_diagnostics()
470 job_status = self.__perform_job_wait(run_diagnostics_status)
471 status = run_diagnostics_status.status_code
472 if status in STATUS_SUCCESS and job_status.get('JobState') == "Completed":
473 msg = SUCCESS_RUN_MSG
474 job_details = job_status
475 if status in STATUS_SUCCESS and job_status.get('JobState') in ["Scheduled", "Scheduling", "Running", "New"]:
476 msg = RUNNING_RUN_MSG
477 job_details = job_status
478 return msg, job_details, None
479
480 def __run_diagnostics(self):
481 reboot_job_types = {
482 "graceful": "GracefulRebootWithoutForcedShutdown",
483 "force": "GracefulRebootWithForcedShutdown",
484 "power_cycle": "PowerCycle"
485 }
486 run_modes = {
487 "express": "Express",
488 "extended": "Extended",
489 "long_run": "ExpressAndExtended"
490 }
491 payload = {}
492 reboot_type = self.module.params.get('reboot_type')
493 run_mode = self.module.params.get('run_mode')
494 if reboot_type == "power_cycle":
495 if self.module.params.get('scheduled_start_time'):
496 start_time = self.__validate_time_format(self.module.params.get('scheduled_start_time'))
497 if self.__validate_time(start_time):
498 payload["ScheduledStartTime"] = start_time
499 if self.module.params.get('scheduled_end_time'):
500 end_time = self.__validate_time_format(self.module.params.get('scheduled_end_time'))
501 if self.__validate_time(end_time):
502 payload["UntilTime"] = end_time
503 if (self.module.params.get('scheduled_start_time') and self.module.params.get('scheduled_end_time')
504 and self.__validate_end_time(start_time, end_time)):
505 payload["UntilTime"] = end_time
506 payload["RebootJobType"] = reboot_job_types.get(reboot_type)
507 payload["RunMode"] = run_modes.get(run_mode)
508 run_diagnostics_status = self.idrac.invoke_request(self.run_url, "POST", data=payload)
509 return run_diagnostics_status
510
511 def __get_run_diagnostics_url(self):
512 uri, error_msg = validate_and_get_first_resource_id_uri(
513 self.module, self.idrac, MANAGERS_URI)
514 if error_msg:
515 self.module.exit_json(msg=error_msg, failed=True)
516 resp = get_dynamic_uri(self.idrac, uri)
517 url = resp.get('Links', {}).get(OEM, {}).get(MANUFACTURER, {}).get(LC_SERVICE, {}).get(ODATA, {})
518 if url:
519 action_resp = get_dynamic_uri(self.idrac, url)
520 run_url = action_resp.get(ACTIONS, {}).get(RUN, {}).get('target', {})
521 self.run_url = run_url
522 else:
523 self.module.exit_json(msg=UNSUPPORTED_FIRMWARE_MSG, failed=True)
524
525 def __validate_job_timeout(self):
526 if self.module.params.get("job_wait") and self.module.params.get("job_wait_timeout") <= 0:
527 self.module.exit_json(msg=TIMEOUT_NEGATIVE_OR_ZERO_MSG, failed=True)
528
529 def __perform_job_wait(self, run_diagnostics_status):
530 job_dict = {}
531 job_wait = self.module.params.get('job_wait')
532 job_wait_timeout = self.module.params.get('job_wait_timeout')
533 job_tracking_uri = run_diagnostics_status.headers.get("Location")
534 if job_tracking_uri:
535 job_id = job_tracking_uri.split("/")[-1]
536 res_uri = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
537 job_uri = f"{res_uri[0]}/{OEM}/{MANUFACTURER}/{JOBS}/{job_id}"
538 if job_wait:
539 job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(self.idrac, job_uri,
540 max_job_wait_sec=job_wait_timeout,
541 sleep_interval_secs=1)
542 job_dict = remove_key(job_dict, regex_pattern=ODATA_REGEX)
543 if int(wait_time) >= int(job_wait_timeout):
544 self.module.exit_json(msg=WAIT_TIMEOUT_MSG.format(
545 job_wait_timeout), changed=True, job_status=job_dict)
546 if job_failed:
547 self.module.exit_json(
548 msg=job_dict.get("Message"), job_status=job_dict, failed=True)
549 else:
550 job_resp = self.idrac.invoke_request(job_uri, 'GET')
551 job_dict = job_resp.json_data
552 job_dict = remove_key(job_dict, regex_pattern=ODATA_REGEX)
553 return job_dict
554
555 def __validate_time_format(self, time):
556 try:
557 datetime_obj = datetime.strptime(time, TIME_FORMAT_WITH_OFFSET)
558 except ValueError:
559 try:
560 datetime_obj = datetime.strptime(time, TIME_FORMAT_WITHOUT_OFFSET)
561 except ValueError:
562 self.module.exit_json(failed=True, msg=INVALID_TIME.format(time))
563 formatted_time = datetime_obj.strftime(TIME_FORMAT_WITHOUT_OFFSET)
564 return formatted_time
565
566 def __validate_time(self, time):
567 curr_idrac_time, offset = get_current_time(self.idrac)
568 curr_idrac_time = datetime.strptime(curr_idrac_time, TIME_FORMAT_WITH_OFFSET)
569 curr_idrac_time = curr_idrac_time.strftime(TIME_FORMAT_WITHOUT_OFFSET)
570 currtime_obj = datetime.strptime(curr_idrac_time, TIME_FORMAT_WITHOUT_OFFSET)
571 starttime_obj = datetime.strptime(time, TIME_FORMAT_WITHOUT_OFFSET)
572 if starttime_obj < currtime_obj:
573 self.module.exit_json(failed=True, msg=START_TIME)
574 return True
575
576 def __validate_end_time(self, start_time, end_time):
577 starttime_obj = datetime.strptime(start_time, TIME_FORMAT_WITHOUT_OFFSET)
578 endtime_obj = datetime.strptime(end_time, TIME_FORMAT_WITHOUT_OFFSET)
579 if starttime_obj > endtime_obj:
580 self.module.exit_json(failed=True, msg=END_START_TIME.format(end_time, start_time))
581 return True
582
583 def check_diagnostics_jobs(self):
584 res_uri = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
585 job_uri = f"{res_uri[0]}/{OEM}/{MANUFACTURER}/{JOBS}{JOBS_EXPAND}"
586 job_resp = self.idrac.invoke_request(job_uri, "GET")
587 job_list = job_resp.json_data.get('Members', [])
588 job_id = ""
589 for jb in job_list:
590 if jb.get("JobType") == "RemoteDiagnostics" and jb.get("JobState") in ["Scheduled", "Running", "Starting", "New"]:
591 job_id = jb['Id']
592 job_dict = remove_key(jb, regex_pattern=ODATA_REGEX)
593 break
594 if self.module.check_mode and job_id:
595 self.module.exit_json(msg=ALREADY_RUN_MSG, job_details=job_dict, skipped=True)
596 if self.module.check_mode and not job_id:
597 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
598 if job_id:
599 self.module.exit_json(msg=ALREADY_RUN_MSG, job_details=job_dict, skipped=True)
600
601
602 class ExportDiagnostics(Diagnostics):
603
604 def execute(self):
605 self.test_network_share()
606 self.__get_export_diagnostics_url()
607 if self.module.check_mode:
608 self.perform_check_mode()
609 job_status = {}
610 share_type = self.module.params.get('share_parameters').get('share_type')
611 share_type_methods = {
612 "local": self.__export_diagnostics_local,
613 "http": self.__export_diagnostics_http,
614 "https": self.__export_diagnostics_http,
615 "cifs": self.__export_diagnostics_cifs,
616 "nfs": self.__export_diagnostics_nfs
617 }
618 export_diagnostics_status = share_type_methods[share_type]()
619 if share_type != "local":
620 job_status = self.get_job_status(export_diagnostics_status)
621 status = export_diagnostics_status.status_code
622 diagnostics_file_path = f"{self.share_name}/{self.file_name}"
623 if status in STATUS_SUCCESS:
624 msg = SUCCESS_EXPORT_MSG
625 job_details = job_status
626 return msg, job_details, diagnostics_file_path
627
628 def __export_diagnostics_local(self):
629 payload = {}
630 payload["ShareType"] = "Local"
631 file_path = self.module.params.get('share_parameters').get('share_name')
632 self.share_name = file_path.rstrip("/")
633 diagnostics_status = self.__export_diagnostics(payload)
634 diagnostics_file_name = payload.get("FileName")
635 diagnostics_data = self.idrac.invoke_request(diagnostics_status.headers.get("Location"), "GET")
636 file_name = os.path.join(file_path, diagnostics_file_name)
637 with open(file_name, "w") as fp:
638 fp.write(diagnostics_data.body.decode().replace("\r", ""))
639 return diagnostics_status
640
641 def __export_diagnostics_http(self):
642 payload = self.get_payload_details()
643 export_status = self.__export_diagnostics(payload)
644 share = self.module.params.get('share_parameters')
645 ip = config_ipv6(share.get('ip_address'))
646 self.share_name = f"{share.get('share_type')}://{ip}/{share.get('share_name').strip('/')}"
647 return export_status
648
649 def __export_diagnostics_cifs(self):
650 payload = self.get_payload_details()
651 if self.module.params.get('share_parameters').get('workgroup'):
652 payload["Workgroup"] = self.module.params.get('share_parameters').get('workgroup')
653 export_status = self.__export_diagnostics(payload)
654 share_name = self.module.params.get('share_parameters').get('share_name').replace("\\", "/")
655 self.share_name = f"//{self.module.params.get('share_parameters').get('ip_address')}/{share_name.strip('/')}"
656 return export_status
657
658 def __export_diagnostics_nfs(self):
659 payload = self.get_payload_details()
660 del payload["UserName"], payload["Password"]
661 export_status = self.__export_diagnostics(payload)
662 share = self.module.params.get('share_parameters')
663 self.share_name = f"{share.get('ip_address')}:/{share.get('share_name').strip('/')}"
664 return export_status
665
666 def __get_export_diagnostics_url(self):
667 uri, error_msg = validate_and_get_first_resource_id_uri(
668 self.module, self.idrac, MANAGERS_URI)
669 if error_msg:
670 self.module.exit_json(msg=error_msg, failed=True)
671 resp = get_dynamic_uri(self.idrac, uri)
672 url = resp.get('Links', {}).get(OEM, {}).get(MANUFACTURER, {}).get(LC_SERVICE, {}).get(ODATA, {})
673 if url:
674 action_resp = get_dynamic_uri(self.idrac, url)
675 export_url = action_resp.get(ACTIONS, {}).get(EXPORT, {}).get('target', {})
676 self.export_url = export_url
677 else:
678 self.module.exit_json(msg=UNSUPPORTED_FIRMWARE_MSG, failed=True)
679
680 def __export_diagnostics(self, payload):
681 diagnostics_file_name = self.module.params.get('share_parameters').get('file_name')
682 if not diagnostics_file_name:
683 now = datetime.now()
684 hostname = self.module.params.get('idrac_ip')
685 hostname = self.expand_ipv6(hostname)
686 hostname = hostname.replace(":", ".")
687 diagnostics_file_name = f"{hostname}_{now.strftime(TIME_FORMAT_FILE)}.txt"
688 payload["FileName"] = diagnostics_file_name
689 self.file_name = diagnostics_file_name
690 diagnostics_status = self.idrac.invoke_request(self.export_url, "POST", data=payload)
691 return diagnostics_status
692
693 def get_job_status(self, export_diagnostics_status):
694 res_uri = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
695 job_tracking_uri = export_diagnostics_status.headers.get("Location")
696 job_id = job_tracking_uri.split("/")[-1]
697 job_uri = f"{res_uri[0]}/{OEM}/{MANUFACTURER}/{JOBS}/{job_id}"
698 job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(self.idrac, job_uri)
699 job_dict = remove_key(job_dict, regex_pattern=ODATA_REGEX)
700 if job_failed:
701 self.module.exit_json(msg=job_dict.get('Message'), failed=True, job_details=job_dict)
702 return job_dict
703
704 def perform_check_mode(self):
705 try:
706 payload = {}
707 payload['ShareType'] = 'Local'
708 export_status = self.idrac.invoke_request(self.export_url, "POST", data=payload)
709 if export_status.status_code in STATUS_SUCCESS:
710 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
711 except HTTPError as err:
712 filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX)
713 message_details = filter_err.get('error').get(MESSAGE_EXTENDED_INFO)[0]
714 message_id = message_details.get('MessageId')
715 if 'SYS099' in message_id:
716 self.module.exit_json(msg=NO_FILE, skipped=True)
717
718 def expand_ipv6(self, ip):
719 sections = ip.split(':')
720 num_sections = len(sections)
721 double_colon_index = sections.index('') if '' in sections else -1
722 if double_colon_index != -1:
723 missing_sections = 8 - num_sections + 1
724 sections[double_colon_index:double_colon_index + 1] = ['0000'] * missing_sections
725 sections = [section.zfill(4) for section in sections]
726 expanded_ip = ':'.join(sections)
727 return expanded_ip
728
729
730 class RunAndExportDiagnostics:
731
732 def __init__(self, idrac, module):
733 self.run = RunDiagnostics(idrac, module)
734 self.export = ExportDiagnostics(idrac, module)
735 self.module = module
736
737 def execute(self):
738 msg, job_status, file_path = self.run.execute()
739 if self.module.params.get("job_wait"):
740 msg, job_status, file_path = self.export.execute()
741 msg = SUCCESS_RUN_AND_EXPORT_MSG
742 return msg, job_status, file_path
743
744
745 class DiagnosticsType:
746 _diagnostics_classes = {
747 "run": RunDiagnostics,
748 "export": ExportDiagnostics,
749 "run_and_export": RunAndExportDiagnostics
750 }
751
752 @staticmethod
753 def diagnostics_operation(idrac, module):
754 class_type = None
755 if module.params.get("run") and module.params.get("export"):
756 class_type = "run_and_export"
757 elif module.params.get("run"):
758 class_type = "run"
759 elif module.params.get("export"):
760 class_type = "export"
761 if class_type:
762 diagnostics_class = DiagnosticsType._diagnostics_classes.get(class_type)
763 return diagnostics_class(idrac, module)
764 else:
765 module.exit_json(msg=NO_OPERATION_SKIP_MSG, skipped=True)
766
767
768 def main():
769 specs = get_argument_spec()
770
771 module = IdracAnsibleModule(
772 argument_spec=specs,
773 required_one_of=[["run", "export"]],
774 required_if=[
775 ["run", True, ("reboot_type", "run_mode",)],
776 ["export", True, ("share_parameters",)]
777 ],
778 supports_check_mode=True
779 )
780
781 try:
782 with iDRACRedfishAPI(module.params) as idrac:
783 diagnostics_obj = DiagnosticsType.diagnostics_operation(idrac, module)
784 msg, job_status, file_path = diagnostics_obj.execute()
785 if file_path is None:
786 module.exit_json(msg=msg, changed=True, job_details=job_status)
787 module.exit_json(msg=msg, changed=True, job_details=job_status, diagnostics_file_path=file_path)
788 except HTTPError as err:
789 filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX)
790 message_details = filter_err.get('error').get(MESSAGE_EXTENDED_INFO)[0]
791 message_id = message_details.get('MessageId')
792 if 'SYS099' in message_id:
793 module.exit_json(msg=NO_FILE, skipped=True)
794 if 'SYS098' in message_id:
795 module.exit_json(msg=message_details.get('Message'), skipped=True)
796 module.exit_json(msg=str(err), error_info=filter_err, failed=True)
797 except URLError as err:
798 module.exit_json(msg=str(err), unreachable=True)
799 except (OSError, ValueError, SSLValidationError, ConnectionError, TypeError) as e:
800 module.exit_json(msg=str(e), failed=True)
801
802
803 def get_argument_spec():
804 return {
805 "run": {"type": 'bool'},
806 "export": {"type": 'bool'},
807 "run_mode": {
808 "type": 'str',
809 "default": 'express',
810 "choices": ['express', 'extended', 'long_run']
811 },
812 "reboot_type": {
813 "type": 'str',
814 "default": 'graceful',
815 "choices": ['force', 'graceful', 'power_cycle']
816 },
817 "scheduled_start_time": {"type": 'str'},
818 "scheduled_end_time": {"type": 'str'},
819 "job_wait": {"type": 'bool', "default": True},
820 "job_wait_timeout": {"type": 'int', "default": 1200},
821 "share_parameters": {
822 "type": 'dict',
823 "options": {
824 "share_type": {
825 "type": 'str',
826 "default": 'local',
827 "choices": ['local', 'nfs', 'cifs', 'http', 'https']
828 },
829 "proxy_type": {
830 "type": 'str',
831 "default": 'http',
832 "choices": ['http', 'socks']
833 },
834 "username": {"type": 'str'},
835 "password": {"type": 'str', "no_log": True},
836 "proxy_port": {"type": 'int', "default": 80},
837 "file_name": {"type": 'str'},
838 "ignore_certificate_warning": {
839 "type": 'str',
840 "default": "off",
841 "choices": ["off", "on"]
842 },
843 "ip_address": {"type": 'str'},
844 "proxy_server": {"type": 'str'},
845 "workgroup": {"type": 'str'},
846 "proxy_support": {
847 "type": 'str',
848 "default": "off",
849 "choices": ["off", "default_proxy", "parameters_proxy"]
850 },
851 "share_name": {"type": 'str'},
852 "proxy_username": {"type": 'str'},
853 "proxy_password": {"type": 'str', "no_log": True}
854 },
855 "required_together": [
856 ("username", "password"),
857 ("proxy_username", "proxy_password")
858 ],
859 "required_if": [
860 ["share_type", "local", ["share_name"]],
861 ["share_type", "nfs", ["ip_address", "share_name"]],
862 ["share_type", "cifs", ["ip_address", "share_name", "username", "password"]],
863 ["share_type", "http", ["ip_address", "share_name"]],
864 ["share_type", "https", ["ip_address", "share_name"]],
865 ["proxy_support", "parameters_proxy", ["proxy_server"]]
866 ],
867 },
868 "resource_id": {"type": 'str'}
869 }
870
871
872 if __name__ == '__main__':
873 main()