
    VhZ                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlmZ d dlmZmZ d dlmZmZ d d	lmZmZ d
dddZdZdZdZdZdZdZdZd Zd ZddZ d Z!d Z"d Z#e$dk(  r e#        yy)    )absolute_importdivisionprint_functiona  
---
module: ome_diagnostics
short_description: Export technical support logs(TSR) to network share location
version_added: "3.6.0"
description: This module allows to export SupportAssist collection logs from OpenManage Enterprise and
  OpenManage Enterprise Modular and application logs from OpenManage Enterprise Modular to a CIFS or NFS share.
extends_documentation_fragment:
  - dellemc.openmanage.ome_auth_options
options:
  device_ids:
    type: list
    description:
      - List of target device IDs.
      - This is applicable for C(support_assist_collection) and C(supportassist_collection) logs.
      - This option is mutually exclusive with I(device_service_tags) and I(device_group_name).
    elements: int
  device_service_tags:
    type: list
    description:
      - List of target identifier.
      - This is applicable for C(support_assist_collection) and C(supportassist_collection) logs.
      - This option is mutually exclusive with I(device_ids) and I(device_group_name).
    elements: str
  device_group_name:
    type: str
    description:
      - Name of the device group to export C(support_assist_collection) or C(supportassist_collection) logs of all devices within the group.
      - This is applicable for C(support_assist_collection) and C(supportassist_collection) logs.
      - This option is not applicable for OpenManage Enterprise Modular.
      - This option is mutually exclusive with I(device_ids) and I(device_service_tags).
  log_type:
    type: str
    description:
      - C(application) is applicable for OpenManage Enterprise Modular to export the application log bundle.
      - C(support_assist_collection) and C(supportassist_collection) is applicable for one or more devices to export SupportAssist logs.
      - C(support_assist_collection) and C(supportassist_collection) supports both OpenManage Enterprise and OpenManage Enterprise Modular.
      - C(support_assist_collection) and C(supportassist_collection) does not support export of C(OS_LOGS) from OpenManage Enterprise.
        If tried to export, the tasks will complete with errors, and the module fails.
    choices: [application, support_assist_collection, supportassist_collection]
    default: support_assist_collection
  mask_sensitive_info:
    type: bool
    description:
      - Select this option to mask the personal identification information such as IPAddress,
        DNS, alert destination, email, gateway, inet6, MacAddress, netmask etc.
      - This option is applicable for C(application) of I(log_type).
    default: false
  log_selectors:
    type: list
    description:
      - By default, the SupportAssist logs contain only hardware logs. To collect additional logs
        such as OS logs, RAID logs or Debug logs, specify the log types to be collected in the choices list.
      - If the log types are not specified, only the hardware logs are exported.
      - C(OS_LOGS) to collect OS Logs.
      - C(RAID_LOGS) to collect RAID controller logs.
      - C(DEBUG_LOGS) to collect Debug logs.
      - This option is applicable only for C(support_assist_collection) and C(supportassist_collection) of I(log_type).
    choices: [OS_LOGS, RAID_LOGS, DEBUG_LOGS]
    elements: str
  share_address:
    type: str
    required: true
    description: Network share IP address.
  share_name:
    type: str
    required: true
    description:
      - Network share path.
      - Filename is auto generated and should not be provided as part of I(share_name).
  share_type:
    type: str
    required: true
    description: Network share type
    choices: [NFS, CIFS]
  share_user:
    type: str
    description:
      - Network share username.
      - This option is applicable for C(CIFS) of I(share_type).
  share_password:
    type: str
    description:
      - Network share password
      - This option is applicable for C(CIFS) of I(share_type).
  share_domain:
    type: str
    description:
      - Network share domain name.
      - This option is applicable for C(CIFS) if I(share_type).
  job_wait:
    type: bool
    description:
      - Whether to wait for the Job completion or not.
      - The maximum wait time is I(job_wait_timeout).
    default: true
  job_wait_timeout:
    type: int
    description:
      - The maximum wait time of I(job_wait) in minutes.
      - This option is applicable I(job_wait) is true.
    default: 60
  test_connection:
    type: bool
    description:
      - Test the availability of the network share location.
      - I(job_wait) and I(job_wait_timeout) options are not applicable for I(test_connection).
    default: false
  lead_chassis_only:
    type: bool
    description:
      - Extract the logs from Lead chassis only.
      - I(lead_chassis_only) is only applicable when I(log_type) is C(application) on OpenManage Enterprise Modular.
    default: false
requirements:
  - "python >= 3.9.6"
author:
  - "Felix Stephen (@felixs88)"
  - "Sachin Apagundi(@sachin-apa)"
notes:
    - Run this module from a system that has direct access to OpenManage Enterprise.
    - This module performs the test connection and device validations. It does not create a job for copying the
      logs in check mode and always reports as changes found.
    - This module supports C(check_mode).
a  
---
- name: Export application log using CIFS share location
  dellemc.openmanage.ome_diagnostics:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    share_type: CIFS
    share_address: "192.168.0.2"
    share_user: share_username
    share_password: share_password
    share_name: cifs_share
    log_type: application
    mask_sensitive_info: false
    test_connection: true

- name: Export application log using NFS share location
  dellemc.openmanage.ome_diagnostics:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    share_address: "192.168.0.3"
    share_type: NFS
    share_name: nfs_share
    log_type: application
    mask_sensitive_info: true
    test_connection: true

- name: Export SupportAssist log using CIFS share location
  dellemc.openmanage.ome_diagnostics:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    share_address: "192.168.0.3"
    share_user: share_username
    share_password: share_password
    share_name: cifs_share
    share_type: CIFS
    log_type: support_assist_collection
    device_ids: [10011, 10022]
    log_selectors: [OS_LOGS]
    test_connection: true

- name: Export SupportAssist log using NFS share location
  dellemc.openmanage.ome_diagnostics:
    hostname: "192.168.0.1"
    username: "username"
    password: "password"
    ca_path: "/path/to/ca_cert.pem"
    share_address: "192.168.0.3"
    share_type: NFS
    share_name: nfs_share
    log_type: support_assist_collection
    device_group_name: group_name
    test_connection: true
a  
---
msg:
  type: str
  description: "Overall status of the export log."
  returned: always
  sample: "Export log job completed successfully."
jog_status:
  type: dict
  description: Details of the export log operation status.
  returned: success
  sample: {
    "Builtin": false,
    "CreatedBy": "root",
    "Editable": true,
    "EndTime": None,
    "Id": 12778,
    "JobDescription": "Export device log",
    "JobName": "Export Log",
    "JobStatus": {"Id": 2080, "Name": "New"},
    "JobType": {"Id": 18, "Internal": false, "Name": "DebugLogs_Task"},
    "LastRun": "2021-07-06 10:52:50.519",
    "LastRunStatus": {"Id": 2060, "Name": "Completed"},
    "NextRun": None,
    "Schedule": "startnow",
    "StartTime": None,
    "State": "Enabled",
    "UpdatedBy": None,
    "UserGenerated": true,
    "Visible": true,
    "Params": [
      {"JobId": 12778, "Key": "maskSensitiveInfo", "Value": "FALSE"},
      {"JobId": 12778, "Key": "password", "Value": "tY86w7q92u0QzvykuF0gQQ"},
      {"JobId": 12778, "Key": "userName", "Value": "administrator"},
      {"JobId": 12778, "Key": "shareName", "Value": "iso"},
      {"JobId": 12778, "Key": "OPERATION_NAME", "Value": "EXTRACT_LOGS"},
      {"JobId": 12778, "Key": "shareType", "Value": "CIFS"},
      {"JobId": 12778, "Key": "shareAddress", "Value": "100.96.32.142"}
    ],
    "Targets": [{"Data": "", "Id": 10053, "JobId": 12778, "TargetType": {"Id": 1000, "Name": "DEVICE"}}]
  }
error_info:
  description: Details of the HTTP Error.
  returned: on HTTP error
  type: dict
  sample: {
    "error": {
      "code": "Base.1.0.GeneralError",
      "message": "A general error has occurred. See ExtendedInfo for more information.",
      "@Message.ExtendedInfo": [
        {
          "MessageId": "GEN1234",
          "RelatedProperties": [],
          "Message": "Unable to process the request because an error occurred.",
          "MessageArgs": [],
          "Severity": "Critical",
          "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
        }
      ]
    }
  }
N)SSLError)RestOMEOmeAnsibleModule)URLError	HTTPError)ConnectionErrorSSLValidationError         )OS_LOGS	RAID_LOGS
DEBUG_LOGSzJobService/JobszGroupService/Groupsz GroupService/Groups({0})/DeviceszDeviceService/DeviceszManagementDomainService/Domainsz'JobService/Jobs({0})/ExecutionHistorieszChanges found to be applied.c                 ,   | j                   j                  d      g }}ddj                  |      i}|j                  dt        |      }|j
                  d   }|rv|d   d   }|j                  dt        j                  |            }|j
                  d   }	|	r%|	D ]  }
|
d	   d
k(  s|j                  |
d          ! n4| j                  d       n!| j                  dj                  |             |s!| j                  dj                  |             |S )Ndevice_group_name$filterzName eq '{0}'GETquery_paramvaluer   IdType  z-There are no device(s) present in this group.msgz_Unable to complete the operation because the entered target device group name '{0}' is invalid.zKThe requested group '{0}' does not contain devices that support export log.)	paramsgetformatinvoke_request	GROUP_URI	json_dataGROUP_DEVICE_URIappend	fail_json)modulerest_obj
group_namegroup_devicer   
group_respgroupgroup_idrespdevice_group_respdevices              v/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/dellemc/openmanage/plugins/modules/ome_diagnostics.pygroup_validationr3     s(   %}}001DErJo44Z@AK((	{(SJ  )E8D>&&u.>.E.Eh.OP NN73+ 6&>T) ''t56 !PQ CCI6*CU 	 	W 3396*3E 	 	G    c           
         g g g }}}| j                   j                  d      | j                   j                  d      }}|j                  t              }|dnddk(  rdnd}||n|}	|	D ]  t	        t        fd|d               }
|
r#|
d	   d
   dk(  r|j                  |
d	   d          D|
r&|
d	   d
   dk(  s|j                  t                     l|j                  t                      |r:| j                  dj                  |dj                  t        |                         |s<|r:| j                  dj                  |dj                  t        |                         |S )N
device_idsdevice_service_tagsr   DeviceServiceTagidzservice tagc                     |    fv S N )deachkeys    r2   <lambda>z#device_validation.<locals>.<lambda>;  s    qv$'7 r4   report_listr   r   r   z\Unable to complete the operation because the entered target device {0}(s) '{1}' are invalid.,r   zDThe requested device {0}(s) '{1}' are not applicable for export log.)r   r    get_all_report_details
DEVICE_URIlistfilterr&   strr'   r!   joinset)r(   r)   
device_lstinvalid_lstother_typesdevicestags
all_devicer   
req_devicer1   r>   r?   s              @@r2   device_validationrQ   3  sr   +-r2[JMM%%l3V]]5F5FG\5]TG00<J%$+=C4KD]E#/TJ *f7M9RSTfQi'4/fQio.F1If-5s4y)s4y)*  GGMveUXU]U]^abm^nUoGp 	 	r+ >>DfUCHHUXYdUeLf>g 	 	ir4   c           	         g g }}| j                   d   }|dk(  r| j                   d   }d }|rl|j                  t              }d}	d }
|d   D ]  }|d   dv s|d   }
 |
rc|j                  d	t        d
dj                  |	|
      i      }|j                  d   }n)|j                  d	t        d
di      }|j                  d   }|r&|D ]   }|j                  |d   d|d   ddd       " n2| j                  d       n|D ]  }|j                  |ddddd        |j                  d| j                   d   d       |j                  d| j                   d   d       |j                  ddd       | j                   j                  d      !|j                  d| j                   d   d       | j                   j                  d       !|j                  d!| j                   d    d       | j                   j                  d"      !|j                  d#| j                   d"   d       | j                   j                  d$      !|j                  d%| j                   d$   d       | j                   j                  d&      =|dk(  r8|j                  d't        | j                   d&         j                         d       | j                   j                  d(      |d)k(  s|d*k(  ru| j                   d(   D cg c]  }t        |    }}|j                          d+j                  t        t        |            }|j                  d,d-j                  |      d       |j!                  d.d/||d0d1d      }|S c c}w )2Nlog_typeapplicationlead_chassis_onlyr   r   DomainRoleTypeValue)LEAD
STANDALONEDeviceIdr   r   z
{0} eq {1}r   zType eq 2000 r   CHASSIS)r   Name)r   Data
TargetTypez:There is no device(s) available to export application log.r   r   DEVICEshareAddressshare_address)KeyValue	shareType
share_typeOPERATION_NAMEEXTRACT_LOGS
share_name	shareName
share_useruserNameshare_passwordpasswordshare_domain
domainNamemask_sensitive_infomaskSensitiveInfolog_selectorssupport_assist_collectionsupportassist_collectionrB   logSelectorz0,{0}z
Export LogzExport device log   DebugLogs_Task)r   get_all_items_with_pagination
DOMAIN_URIr"   rD   r!   r$   r&   r'   r    rG   upperLOG_SELECTORsortrH   mapjob_submission)r(   r)   rJ   payload_paramstarget_paramsrS   	lead_only	resp_datadomain_detailsr?   ch_device_ideach_domainr/   devr1   ilog_lstlog_selectorresponses                      r2   extract_log_operationr   K  s   $&MN}}Z(H= MM"56		%CCJONCL-g6 ;459OO#.z#:L; ..uj<E|GZGZ[^`lGm;n / p NN73	**5*9VdJe*fDw/I  ]$$CIr;>v;PY4Z&\ ]] !]^  	QF  7;X0N"P Q	Q .6==;YZ[+l8STU"2^LM}}&2kFMM,<WXY}}&2j6==;VWX}})*6j6==IY;Z[\}}(4lV]]>=Z[\}}./;M@Y&9CVkHlDmDsDsDuvw}})58Gb;bfn  sM  gM,2MM/,JKq<?KKxxC 12mgnn\>Z[\&&|5H-'5bJZ7[]HO Ls   /M-c                     	 |j                  dt        d       y # t        $ rB}t        j                  |      }|d   d   d   d   dk(  r| j                  d	
       Y d }~y d }~ww xY w)Nr      )api_timeouterrorz@Message.ExtendedInfor   	MessageIdCGEN1006z>Export log operation is not supported on the specified system.r   )r"   ry   r
   jsonloadr'   )r(   r)   errerr_messages       r2   check_domain_servicer     sv    czqA
 	  ciinw 78;KHJV!ab
	cs    	A&8A!!A&c           	         d\  }}|j                  dt        j                  | d               }|j                  d   r|j                  d   d   }|j                  ddj                  t        j                  | d         |d               }|j                  d   D ]"  }t	        j
                  d|d         rd	} ||fS  d
}||fS )N)z%Export log job completed with errors.Fr   r   r   r   z {0}({1})/ExecutionHistoryDetailsz0Job status for JID_\d+ is Completed with Errors.rc   TF)r"   EXE_HISTORY_URIr!   r$   refindall)r/   r)   r   failhistoryhisthistory_detailshds           r2   find_failed_jobsr     s    >IC%%e_-C-CDJ-OPG!  )!,"11.55o6L6LTRVZ6XZ^_cZde
 "++G4 	B::QSUV]S^_ 9	
 D9r4   c            
         i dddddddddddddd	d
dddg ddddddddddg ddddddd	dddd	dddddgddddd	ddddddddd	dddddd ddd!dd"ddddd#dddd} t        | d
d$dggd
dg d%dgd
d&g d%dgddddgggd%gd'      }	 t        |j                  d(      5 }|j                  d
   d$k(  rt        ||       |j	                  d)      \  }}|s|j                  d*+       |j                  d"   r|j                  |j                  d   |j                  d   |j                  d   |j                  d   |j                  d   |j                  d         }|j                  |j                  d,   d-d-.      \  }}|r|j                  d/+       g }|j                  d
   dk(  s|j                  d
   d&k(  r(|j                  j                  d      t        ||      }nK|j                  d
   dk(  s|j                  d
   d&k(  r'|j                  j                  d      t        ||      }|j                  r|j                  t        d0       t        |||1      }	d2}
|j                  d   r|j                  d    d!z  }|j                  |	j                  d,   |d-.      \  }}d3}
|d4j!                  |      k(  r|j                  d5|	j                  6       |r8t#        |	j                  |      \  }
}|r|j                  |
|	j                  6       |j%                  d7d8j!                  t&        |	j                  d,               }	|	j                  }|r|j)                  |      }|j                  |
|d9       d d d        y # 1 sw Y   y xY w# t*        $ r9}|j                  t-        |      t/        j0                  |      :       Y d }~y d }~wt2        $ r&}|j                  t-        |      d;       Y d }~y d }~wt4        t6        t8        t:        t<        t>        t@        f$ r%}|j                  t-        |      +       Y d }~y d }~ww xY w)<Nr6   FrE   int)requiredtypeelementsr7   rG   r   )r   r   rS   rs   )rs   rT   rt   )r   r   defaultchoicesrp   bool)r   r   r   rr   )r   r   r   )r   r   r   r   ra   Trh   re   NFSCIFS)r   r   r   rj   rl   )r   r   no_logrn   job_waitjob_wait_timeout<   test_connectionrU   rT   )r6   r7   r   rt   )argument_specrequired_ifmutually_exclusivesupports_check_mode)req_sessionrw   zAAn export log job is already running. Wait for the job to finish.r   r   r   )job_wait_sec
sleep_timezUnable to access the share. Ensure that the share address, share name, share domain, and share credentials provided are correct.)r   changed)rJ   z&Export log job submitted successfully.z&Export log job completed successfully.z*The job is not complete after {0} seconds.zUThe export job is not complete because it has exceeded the configured timeout period.)r   
job_statusr   z{0}({1}))r   r   r   )r   
error_info)r   unreachable)!r   r   r   r   check_existing_job_stater'   test_network_connectionjob_trackingr$   r    r3   rQ   
check_mode	exit_jsonCHANGES_FOUNDr   r!   r   r"   JOB_URIstrip_substr_dictr
   rG   r   r   r	   IOError
ValueError	TypeErrorr   r   r   OSError)specsr(   r)   job_allowedjob_lst	conn_resp
job_failedjob_messagevalid_devicer   messageseconds
failed_jobr/   r   s                  r2   mainr     sM   5&eLE6uU 	%? 	B] hj	 	E6eT 	eV%KY^` 	dE: 	47 	4E6?S 	5%8 	uetL 	UE: 	4H  	"M!" 	v%P#$ 	%ER%E* )>(?@4GO3GO6L2B#CD
 WW FB'V]]5 ;	I}}Z(M9$VX6 $,#D#DEU#V K  %h i }}./$<<V]]?=[=C]]<=X=C]]<=X=C]]<=X=C]]K[=\=C]]>=Z\	 +3*?*?	@S@STX@YhiKL +@ +N'
K$$ *e$ f Lj)-HHFMMZdLe  jD  MDMM%%&9:F/A--
+/JJfmm\fNg  lF  OFMM%%&9:B0B     ]D A -VX,WH>G}}Z( --(:;b@*2*?*?@R@RSW@XMTKL +@ +N'
K C"N"U"UV]"^^$$s#+#5#5 %  *:8;M;Mx*X'GZ!((WASAS(T#225*:K:KGU]UgUghlUm:no%%D11$7T4Hw;	I ;	I ;	Ix  BSX$))C.AA 9SX488ZHoGY[bc 'SX&&'sO    N" 7KNN" NN" N" "	Q+/OQ+P+Q7QQ__main__r;   )%
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNr   r   sslr   ?ansible_collections.dellemc.openmanage.plugins.module_utils.omer   r   +ansible.module_utils.six.moves.urllib.errorr	   r
   ansible.module_utils.urlsr   r   r{   r   r#   r%   rD   ry   r   r   r3   rQ   r   r   r   r   __name__r<   r4   r2   <module>r      s    C B|~:x=
@  	  e K I1A>
!	5 $
.
;.002j$e'P zF r4   