Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 10.0.1
7 # Copyright (C) 2021-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 __metaclass__ = type
15
16 DOCUMENTATION = r"""
17 ---
18 module: ome_diagnostics
19 short_description: Export technical support logs(TSR) to network share location
20 version_added: "3.6.0"
21 description: This module allows to export SupportAssist collection logs from OpenManage Enterprise and
22 OpenManage Enterprise Modular and application logs from OpenManage Enterprise Modular to a CIFS or NFS share.
23 extends_documentation_fragment:
24 - dellemc.openmanage.ome_auth_options
25 options:
26 device_ids:
27 type: list
28 description:
29 - List of target device IDs.
30 - This is applicable for C(support_assist_collection) and C(supportassist_collection) logs.
31 - This option is mutually exclusive with I(device_service_tags) and I(device_group_name).
32 elements: int
33 device_service_tags:
34 type: list
35 description:
36 - List of target identifier.
37 - This is applicable for C(support_assist_collection) and C(supportassist_collection) logs.
38 - This option is mutually exclusive with I(device_ids) and I(device_group_name).
39 elements: str
40 device_group_name:
41 type: str
42 description:
43 - Name of the device group to export C(support_assist_collection) or C(supportassist_collection) logs of all devices within the group.
44 - This is applicable for C(support_assist_collection) and C(supportassist_collection) logs.
45 - This option is not applicable for OpenManage Enterprise Modular.
46 - This option is mutually exclusive with I(device_ids) and I(device_service_tags).
47 log_type:
48 type: str
49 description:
50 - C(application) is applicable for OpenManage Enterprise Modular to export the application log bundle.
51 - C(support_assist_collection) and C(supportassist_collection) is applicable for one or more devices to export SupportAssist logs.
52 - C(support_assist_collection) and C(supportassist_collection) supports both OpenManage Enterprise and OpenManage Enterprise Modular.
53 - C(support_assist_collection) and C(supportassist_collection) does not support export of C(OS_LOGS) from OpenManage Enterprise.
54 If tried to export, the tasks will complete with errors, and the module fails.
55 choices: [application, support_assist_collection, supportassist_collection]
56 default: support_assist_collection
57 mask_sensitive_info:
58 type: bool
59 description:
60 - Select this option to mask the personal identification information such as IPAddress,
61 DNS, alert destination, email, gateway, inet6, MacAddress, netmask etc.
62 - This option is applicable for C(application) of I(log_type).
63 default: false
64 log_selectors:
65 type: list
66 description:
67 - By default, the SupportAssist logs contain only hardware logs. To collect additional logs
68 such as OS logs, RAID logs or Debug logs, specify the log types to be collected in the choices list.
69 - If the log types are not specified, only the hardware logs are exported.
70 - C(OS_LOGS) to collect OS Logs.
71 - C(RAID_LOGS) to collect RAID controller logs.
72 - C(DEBUG_LOGS) to collect Debug logs.
73 - This option is applicable only for C(support_assist_collection) and C(supportassist_collection) of I(log_type).
74 choices: [OS_LOGS, RAID_LOGS, DEBUG_LOGS]
75 elements: str
76 share_address:
77 type: str
78 required: true
79 description: Network share IP address.
80 share_name:
81 type: str
82 required: true
83 description:
84 - Network share path.
85 - Filename is auto generated and should not be provided as part of I(share_name).
86 share_type:
87 type: str
88 required: true
89 description: Network share type
90 choices: [NFS, CIFS]
91 share_user:
92 type: str
93 description:
94 - Network share username.
95 - This option is applicable for C(CIFS) of I(share_type).
96 share_password:
97 type: str
98 description:
99 - Network share password
100 - This option is applicable for C(CIFS) of I(share_type).
101 share_domain:
102 type: str
103 description:
104 - Network share domain name.
105 - This option is applicable for C(CIFS) if I(share_type).
106 job_wait:
107 type: bool
108 description:
109 - Whether to wait for the Job completion or not.
110 - The maximum wait time is I(job_wait_timeout).
111 default: true
112 job_wait_timeout:
113 type: int
114 description:
115 - The maximum wait time of I(job_wait) in minutes.
116 - This option is applicable I(job_wait) is true.
117 default: 60
118 test_connection:
119 type: bool
120 description:
121 - Test the availability of the network share location.
122 - I(job_wait) and I(job_wait_timeout) options are not applicable for I(test_connection).
123 default: false
124 lead_chassis_only:
125 type: bool
126 description:
127 - Extract the logs from Lead chassis only.
128 - I(lead_chassis_only) is only applicable when I(log_type) is C(application) on OpenManage Enterprise Modular.
129 default: false
130 requirements:
131 - "python >= 3.9.6"
132 author:
133 - "Felix Stephen (@felixs88)"
134 - "Sachin Apagundi(@sachin-apa)"
135 notes:
136 - Run this module from a system that has direct access to OpenManage Enterprise.
137 - This module performs the test connection and device validations. It does not create a job for copying the
138 logs in check mode and always reports as changes found.
139 - This module supports C(check_mode).
140 """
141
142
143 EXAMPLES = r"""
144 ---
145 - name: Export application log using CIFS share location
146 dellemc.openmanage.ome_diagnostics:
147 hostname: "192.168.0.1"
148 username: "username"
149 password: "password"
150 ca_path: "/path/to/ca_cert.pem"
151 share_type: CIFS
152 share_address: "192.168.0.2"
153 share_user: share_username
154 share_password: share_password
155 share_name: cifs_share
156 log_type: application
157 mask_sensitive_info: false
158 test_connection: true
159
160 - name: Export application log using NFS share location
161 dellemc.openmanage.ome_diagnostics:
162 hostname: "192.168.0.1"
163 username: "username"
164 password: "password"
165 ca_path: "/path/to/ca_cert.pem"
166 share_address: "192.168.0.3"
167 share_type: NFS
168 share_name: nfs_share
169 log_type: application
170 mask_sensitive_info: true
171 test_connection: true
172
173 - name: Export SupportAssist log using CIFS share location
174 dellemc.openmanage.ome_diagnostics:
175 hostname: "192.168.0.1"
176 username: "username"
177 password: "password"
178 ca_path: "/path/to/ca_cert.pem"
179 share_address: "192.168.0.3"
180 share_user: share_username
181 share_password: share_password
182 share_name: cifs_share
183 share_type: CIFS
184 log_type: support_assist_collection
185 device_ids: [10011, 10022]
186 log_selectors: [OS_LOGS]
187 test_connection: true
188
189 - name: Export SupportAssist log using NFS share location
190 dellemc.openmanage.ome_diagnostics:
191 hostname: "192.168.0.1"
192 username: "username"
193 password: "password"
194 ca_path: "/path/to/ca_cert.pem"
195 share_address: "192.168.0.3"
196 share_type: NFS
197 share_name: nfs_share
198 log_type: support_assist_collection
199 device_group_name: group_name
200 test_connection: true
201 """
202
203 RETURN = r"""
204 ---
205 msg:
206 type: str
207 description: "Overall status of the export log."
208 returned: always
209 sample: "Export log job completed successfully."
210 jog_status:
211 type: dict
212 description: Details of the export log operation status.
213 returned: success
214 sample: {
215 "Builtin": false,
216 "CreatedBy": "root",
217 "Editable": true,
218 "EndTime": None,
219 "Id": 12778,
220 "JobDescription": "Export device log",
221 "JobName": "Export Log",
222 "JobStatus": {"Id": 2080, "Name": "New"},
223 "JobType": {"Id": 18, "Internal": false, "Name": "DebugLogs_Task"},
224 "LastRun": "2021-07-06 10:52:50.519",
225 "LastRunStatus": {"Id": 2060, "Name": "Completed"},
226 "NextRun": None,
227 "Schedule": "startnow",
228 "StartTime": None,
229 "State": "Enabled",
230 "UpdatedBy": None,
231 "UserGenerated": true,
232 "Visible": true,
233 "Params": [
234 {"JobId": 12778, "Key": "maskSensitiveInfo", "Value": "FALSE"},
235 {"JobId": 12778, "Key": "password", "Value": "tY86w7q92u0QzvykuF0gQQ"},
236 {"JobId": 12778, "Key": "userName", "Value": "administrator"},
237 {"JobId": 12778, "Key": "shareName", "Value": "iso"},
238 {"JobId": 12778, "Key": "OPERATION_NAME", "Value": "EXTRACT_LOGS"},
239 {"JobId": 12778, "Key": "shareType", "Value": "CIFS"},
240 {"JobId": 12778, "Key": "shareAddress", "Value": "100.96.32.142"}
241 ],
242 "Targets": [{"Data": "", "Id": 10053, "JobId": 12778, "TargetType": {"Id": 1000, "Name": "DEVICE"}}]
243 }
244 error_info:
245 description: Details of the HTTP Error.
246 returned: on HTTP error
247 type: dict
248 sample: {
249 "error": {
250 "code": "Base.1.0.GeneralError",
251 "message": "A general error has occurred. See ExtendedInfo for more information.",
252 "@Message.ExtendedInfo": [
253 {
254 "MessageId": "GEN1234",
255 "RelatedProperties": [],
256 "Message": "Unable to process the request because an error occurred.",
257 "MessageArgs": [],
258 "Severity": "Critical",
259 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
260 }
261 ]
262 }
263 }
264 """
265
266
267 import json
268 import re
269 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
270 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
271 from ansible.module_utils.urls import ConnectionError, SSLValidationError
272
273 LOG_SELECTOR = {"OS_LOGS": 1, "RAID_LOGS": 2, "DEBUG_LOGS": 3}
274 JOB_URI = "JobService/Jobs"
275 GROUP_URI = "GroupService/Groups"
276 GROUP_DEVICE_URI = "GroupService/Groups({0})/Devices"
277 DEVICE_URI = "DeviceService/Devices"
278 DOMAIN_URI = "ManagementDomainService/Domains"
279 EXE_HISTORY_URI = "JobService/Jobs({0})/ExecutionHistories"
280 CHANGES_FOUND = "Changes found to be applied."
281 FILTER_URL = "$filter"
282
283
284 def group_validation(module, rest_obj):
285 group_name, group_device = module.params.get('device_group_name'), []
286 query_param = {FILTER_URL: "Name eq '{0}'".format(group_name)}
287 group_resp = rest_obj.invoke_request("GET", GROUP_URI, query_param=query_param)
288 group = group_resp.json_data["value"]
289 if group:
290 group_id = group[0]["Id"]
291 resp = rest_obj.invoke_request("GET", GROUP_DEVICE_URI.format(group_id))
292 device_group_resp = resp.json_data["value"]
293 if device_group_resp:
294 for device in device_group_resp:
295 if device["Type"] == 1000:
296 group_device.append(device["Id"])
297 else:
298 module.exit_json(msg="There are no device(s) present in this group.", failed=True)
299 else:
300 module.exit_json(msg="Unable to complete the operation because the entered target "
301 "device group name '{0}' is invalid.".format(group_name), failed=True)
302 if not group_device:
303 module.exit_json(msg="The requested group '{0}' does not contain devices that "
304 "support export log.".format(group_name), failed=True)
305 return group_device
306
307
308 def device_validation(module, rest_obj):
309 device_lst, invalid_lst, other_types = [], [], []
310 devices, tags = module.params.get("device_ids"), module.params.get("device_service_tags")
311 all_device = rest_obj.get_all_report_details(DEVICE_URI)
312 key = "Id" if devices is not None else "DeviceServiceTag"
313 value = "id" if key == "Id" else "service tag"
314 req_device = devices if devices is not None else tags
315 for each in req_device:
316 device = list(filter(lambda d: d[key] in [each], all_device["report_list"]))
317 if device and device[0]["Type"] == 1000:
318 device_lst.append(device[0]["Id"])
319 elif device and device[0]["Type"] != 1000:
320 other_types.append(str(each))
321 else:
322 invalid_lst.append(str(each))
323 if invalid_lst:
324 module.exit_json(msg="Unable to complete the operation because the entered "
325 "target device {0}(s) '{1}' are invalid.".format(value, ",".join(set(invalid_lst))),
326 failed=True)
327 if not device_lst and other_types:
328 module.exit_json(msg="The requested device {0}(s) '{1}' are "
329 "not applicable for export log.".format(value, ",".join(set(other_types))),
330 failed=True)
331 return device_lst
332
333
334 def extract_log_operation(module, rest_obj, device_lst=None):
335 log_type = module.params["log_type"]
336
337 if log_type == "application":
338 target_params = get_application_targets(module, rest_obj)
339 else:
340 target_params = get_device_targets(device_lst)
341
342 payload_params = build_payload(module, log_type)
343
344 response = rest_obj.job_submission(
345 "Export Log",
346 "Export device log",
347 target_params,
348 payload_params,
349 {"Id": 18, "Name": "DebugLogs_Task"}
350 )
351 return response
352
353
354 def get_application_targets(module, rest_obj):
355 lead_only = module.params["lead_chassis_only"]
356 resp_data = get_application_devices(rest_obj, lead_only)
357
358 if not resp_data:
359 module.exit_json(msg="There is no device(s) available to export application log.", failed=True)
360
361 return [
362 {
363 "Id": dev["Id"],
364 "Data": "",
365 "TargetType": {"Id": dev["Type"], "Name": "CHASSIS"}
366 }
367 for dev in resp_data
368 ]
369
370
371 def get_application_devices(rest_obj, lead_only):
372 if lead_only:
373 domain_details = rest_obj.get_all_items_with_pagination(DOMAIN_URI)
374 for domain in domain_details["value"]:
375 if domain["DomainRoleTypeValue"] in ["LEAD", "STANDALONE"]:
376 ch_device_id = domain["DeviceId"]
377 resp = rest_obj.invoke_request("GET", DEVICE_URI, query_param={FILTER_URL: f"Id eq {ch_device_id}"})
378 return resp.json_data.get("value", [])
379 else:
380 resp = rest_obj.invoke_request("GET", DEVICE_URI, query_param={FILTER_URL: "Type eq 2000"})
381 return resp.json_data.get("value", [])
382 return []
383
384
385 def get_device_targets(device_lst):
386 return [
387 {
388 "Id": device,
389 "Data": "",
390 "TargetType": {"Id": 1000, "Name": "DEVICE"}
391 }
392 for device in device_lst
393 ]
394
395
396 def build_payload(module, log_type):
397 params = module.params
398 payload = [
399 {"Key": "shareAddress", "Value": params["share_address"]},
400 {"Key": "shareType", "Value": params["share_type"]},
401 {"Key": "OPERATION_NAME", "Value": "EXTRACT_LOGS"}
402 ]
403
404 optional_keys = {
405 "share_name": "shareName",
406 "share_user": "userName",
407 "share_password": "password",
408 "share_domain": "domainName"
409 }
410
411 for param_key, payload_key in optional_keys.items():
412 if params.get(param_key) is not None:
413 payload.append({"Key": payload_key, "Value": params[param_key]})
414
415 if params.get("mask_sensitive_info") is not None and log_type == "application":
416 payload.append({
417 "Key": "maskSensitiveInfo",
418 "Value": str(params["mask_sensitive_info"]).upper()
419 })
420
421 if params.get("log_selectors") and log_type in ["support_assist_collection", "supportassist_collection"]:
422 log_lst = sorted([LOG_SELECTOR[i] for i in params["log_selectors"]])
423 log_selector = ",".join(map(str, log_lst))
424 payload.append({"Key": "logSelector", "Value": f"0,{log_selector}"})
425
426 return payload
427
428
429 def check_domain_service(module, rest_obj):
430 try:
431 rest_obj.invoke_request("GET", DOMAIN_URI, api_timeout=5)
432 except HTTPError as err:
433 err_message = json.load(err)
434 if err_message["error"]["@Message.ExtendedInfo"][0]["MessageId"] == "CGEN1006":
435 module.exit_json(msg="Export log operation is not supported on the specified system.",
436 failed=True)
437
438
439 def find_failed_jobs(resp, rest_obj):
440 msg, fail = "Export log job completed with errors.", False
441 history = rest_obj.invoke_request("GET", EXE_HISTORY_URI.format(resp["Id"]))
442 if history.json_data["value"]:
443 hist = history.json_data["value"][0]
444 history_details = rest_obj.invoke_request(
445 "GET",
446 "{0}({1})/ExecutionHistoryDetails".format(EXE_HISTORY_URI.format(resp["Id"]), hist["Id"])
447 )
448 for hd in history_details.json_data["value"]:
449 if not re.findall(r"Job status for JID_\d+ is Completed with Errors.", hd["Value"]):
450 fail = True
451 break
452 else:
453 fail = False
454 return msg, fail
455
456
457 def main():
458 specs = get_argument_spec()
459
460 module = OmeAnsibleModule(
461 argument_spec=specs,
462 required_if=get_required_if_conditions(),
463 mutually_exclusive=[('device_ids', 'device_service_tags', 'device_group_name')],
464 supports_check_mode=True
465 )
466
467 try:
468 with RestOME(module.params, req_session=True) as rest_obj:
469 if not validate_preconditions(module, rest_obj):
470 return
471
472 valid_device = get_valid_devices(module, rest_obj)
473
474 if module.check_mode:
475 module.exit_json(msg=CHANGES_FOUND, changed=True)
476
477 handle_log_job(module, rest_obj, valid_device)
478
479 except HTTPError as err:
480 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
481 except URLError as err:
482 module.exit_json(msg=str(err), unreachable=True)
483 except (IOError, ValueError, TypeError, ConnectionError, SSLValidationError, OSError) as err:
484 module.exit_json(msg=str(err), failed=True)
485
486
487 def get_argument_spec():
488 return {
489 "device_ids": {"required": False, "type": "list", "elements": "int"},
490 "device_service_tags": {"required": False, "type": "list", "elements": "str"},
491 "device_group_name": {"required": False, "type": "str"},
492 "log_type": {"required": False, "type": "str", "default": "support_assist_collection",
493 "choices": ["support_assist_collection", "application", "supportassist_collection"]},
494 "mask_sensitive_info": {"required": False, "type": "bool", "default": False},
495 "log_selectors": {"required": False, "type": "list",
496 "choices": ["RAID_LOGS", "OS_LOGS", "DEBUG_LOGS"], "elements": "str"},
497 "share_address": {"required": True, "type": "str"},
498 "share_name": {"required": True, "type": "str"},
499 "share_type": {"required": True, "type": "str", "choices": ["NFS", "CIFS"]},
500 "share_user": {"required": False, "type": "str"},
501 "share_password": {"required": False, "type": "str", "no_log": True},
502 "share_domain": {"required": False, "type": "str"},
503 "job_wait": {"required": False, "type": "bool", "default": True},
504 "job_wait_timeout": {"required": False, "type": "int", "default": 60},
505 "test_connection": {"required": False, "type": "bool", "default": False},
506 "lead_chassis_only": {"required": False, "type": "bool", "default": False},
507 }
508
509
510 def get_required_if_conditions():
511 return [
512 ['log_type', 'application', ['mask_sensitive_info']],
513 ['log_type', 'support_assist_collection',
514 ['device_ids', 'device_service_tags', 'device_group_name'], True],
515 ['log_type', 'supportassist_collection',
516 ['device_ids', 'device_service_tags', 'device_group_name'], True],
517 ['share_type', 'CIFS', ['share_user', 'share_password']]
518 ]
519
520
521 def validate_preconditions(module, rest_obj):
522 if module.params["log_type"] == "application":
523 check_domain_service(module, rest_obj)
524
525 job_state_details = rest_obj.check_existing_job_state("DebugLogs_Task")
526 if not job_state_details[0]:
527 module.exit_json(msg="An export log job is already running. Wait for the job to finish.", failed=True)
528 return False
529
530 if module.params["test_connection"]:
531 return test_network_connection(module, rest_obj)
532
533 return True
534
535
536 def test_network_connection(module, rest_obj):
537 conn_resp = rest_obj.test_network_connection(
538 module.params["share_address"],
539 module.params["share_name"],
540 module.params["share_type"],
541 module.params["share_user"],
542 module.params["share_password"],
543 module.params["share_domain"]
544 )
545 job_details = rest_obj.job_tracking(conn_resp.json_data["Id"], job_wait_sec=10, sleep_time=5)
546 if job_details[0]:
547 module.exit_json(
548 msg="Unable to access the share. Ensure that the share address, share name, "
549 "share domain, and share credentials provided are correct.",
550 failed=True
551 )
552 return False
553 return True
554
555
556 def get_valid_devices(module, rest_obj):
557 group_name = module.params.get("device_group_name")
558
559 if module.params.get("log_type") in ["support_assist_collection", "supportassist_collection"]:
560 if group_name:
561 return group_validation(module, rest_obj)
562 else:
563 return device_validation(module, rest_obj)
564 return []
565
566
567 def handle_log_job(module, rest_obj, device_lst):
568 response = extract_log_operation(module, rest_obj, device_lst=device_lst)
569 message = "Export log job submitted successfully."
570
571 if module.params["job_wait"]:
572 seconds = module.params["job_wait_timeout"] * 60
573 job_failed, job_message = rest_obj.job_tracking(response.json_data["Id"], job_wait_sec=seconds, sleep_time=5)
574 message = "Export log job completed successfully."
575
576 if job_message == f"The job is not complete after {seconds} seconds.":
577 module.exit_json(
578 msg="The export job is not complete because it has exceeded the configured timeout period.",
579 job_status=response.json_data,
580 failed=True
581 )
582
583 if job_failed:
584 message, failed_job = find_failed_jobs(response.json_data, rest_obj)
585 if failed_job:
586 module.exit_json(msg=message, job_status=response.json_data, failed=True)
587
588 response = rest_obj.invoke_request("GET", f"{JOB_URI}({response.json_data['Id']})")
589
590 resp = response.json_data
591 if resp:
592 resp = rest_obj.strip_substr_dict(resp)
593
594 module.exit_json(msg=message, job_status=resp, changed=True)
595
596
597 if __name__ == '__main__':
598 main()