Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_host_logbundle.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2020, sky-joker
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: vmware_host_logbundle
15 short_description: Fetch logbundle file from ESXi
16 description:
17 - This module can be used to fetch logbundle file from ESXi.
18 author:
19 - sky-joker (@sky-joker)
20 options:
21 esxi_hostname:
22 description:
23 - Name of the host system to fetch the logbundle.
24 type: str
25 required: true
26 dest:
27 description:
28 - file destination on localhost, path must be exist.
29 type: str
30 required: true
31 download_timeout:
32 version_added: 4.5.0
33 description:
34 - The user defined timeout in seconds of exporting the log file.
35 - The default of the function this module uses is so low that you have to set this this to a higher value in all probabilty.
36 type: int
37 manifests:
38 description:
39 - Logs to include in the logbundle file.
40 - Refer to the id key of the M(community.vmware.vmware_host_logbundle_info) module for values that can be specified in the manifest.
41 default:
42 - System:Base
43 - System:CoreDumps
44 - System:EsxImage
45 - System:IOFilter
46 - System:LoadESX
47 - System:Modules
48 - System:RDMA
49 - System:ResourceGroups
50 - System:TPM
51 - System:VFlash
52 - System:VMTools
53 - System:VmiofPlugins
54 - System:ntp
55 - System:uwstats
56 - Fcd:Catalog
57 - VirtualMachines:CoreDumps
58 - VirtualMachines:VirtualMachineStats
59 - VirtualMachines:base
60 - VirtualMachines:base
61 - VirtualMachines:diskinfo
62 - VirtualMachines:logs
63 - Storage:FCoE
64 - Storage:Multipathing
65 - Storage:NAS
66 - Storage:VSAN
67 - Storage:VSANHealth
68 - Storage:VSANIscsiTarget
69 - Storage:VSANPerfStats
70 - Storage:VSANPerfSvc
71 - Storage:VSANTraces
72 - Storage:VVOL
73 - Storage:base
74 - Storage:iodm
75 - Storage:iscsi
76 - FeatureStateSwitch:FeatureStateSwitch
77 - Userworld:HostAgent
78 - Userworld:ProcessInformation
79 - Configuration:System
80 - Logs:System
81 - hostProfiles:SystemImageCacheHostProfile
82 - hostProfiles:hostProfiles
83 - FileSystem:VMFSDiskDump
84 - FileSystem:base
85 - ActiveDirectory:base
86 - CIM:base
87 - Hardware:base
88 - Hardware:usb
89 - Installer:base
90 - Network:base
91 - Network:dvs
92 - Network:lacp
93 - Network:nscd
94 - Network:tcpip
95 - IntegrityChecks:md5sums
96 type: list
97 elements: str
98 required: false
99 performance_data:
100 description:
101 - Gather performance data for ESXi.
102 type: dict
103 required: false
104 suboptions:
105 duration:
106 description:
107 - Duration for which performance data is gathered.
108 type: int
109 default: 300
110 interval:
111 description:
112 - Interval for which performance data is gathered.
113 type: int
114 default: 5
115 extends_documentation_fragment:
116 - vmware.vmware.base_options
117 '''
118
119 EXAMPLES = r'''
120 - name: fetch logbundle file from ESXi
121 community.vmware.vmware_host_logbundle:
122 hostname: "{{ vcenter_hostname }}"
123 username: "{{ vcenter_username }}"
124 password: "{{ vcenter_password }}"
125 esxi_hostname: "{{ esxi_hostname }}"
126 dest: ./esxi-log.tgz
127
128 - name: fetch logbundle file from ESXi with manifests
129 community.vmware.vmware_host_logbundle:
130 hostname: "{{ vcenter_hostname }}"
131 username: "{{ vcenter_username }}"
132 password: "{{ vcenter_password }}"
133 esxi_hostname: "{{ esxi_hostname }}"
134 dest: ./esxi-log.tgz
135 manifests:
136 - System:Base
137 - VirtualMachines:VirtualMachineStats
138 '''
139
140 RETURN = r'''
141 dest:
142 description: saved path of a logbundle file for ESXi
143 returned: on success
144 type: str
145 sample:
146 {
147 "changed": true,
148 "dest": "./esxi-log.tgz",
149 "failed": false,
150 "gid": 0,
151 "group": "root",
152 "mode": "0644",
153 "owner": "root",
154 "size": 25783140,
155 "state": "file",
156 "uid": 0
157 }
158 '''
159
160 try:
161 from pyVmomi import vim
162 except ImportError:
163 pass
164
165 import xml.etree.ElementTree as ET
166
167 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
168 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
169 from ansible.module_utils.basic import AnsibleModule
170 from ansible.module_utils.urls import fetch_url
171
172
173 class VMwareHostLogbundle(PyVmomi):
174 def __init__(self, module):
175 super(VMwareHostLogbundle, self).__init__(module)
176 self.esxi_hostname = self.params['esxi_hostname']
177 self.dest = self.params['dest']
178 self.manifests = self.params['manifests']
179 self.performance_data = self.params['performance_data']
180 self.download_timeout = self.params['download_timeout']
181
182 if not self.dest.endswith('.tgz'):
183 self.dest = self.dest + '.tgz'
184
185 def generate_req_headers(self, url):
186 # get ticket
187 req = vim.SessionManager.HttpServiceRequestSpec(method='httpGet', url=url)
188 ticket = self.content.sessionManager.AcquireGenericServiceTicket(req)
189
190 headers = {
191 'Content-Type': 'application/octet-stream',
192 'Cookie': 'vmware_cgi_ticket=%s' % ticket.id
193 }
194
195 return headers
196
197 def validate_manifests(self):
198 url = 'https://' + self.esxi_hostname + '/cgi-bin/vm-support.cgi?listmanifests=1'
199 headers = self.generate_req_headers(url)
200
201 manifests = []
202 try:
203 resp, info = fetch_url(self.module, method='GET', headers=headers, url=url)
204 if info['status'] != 200:
205 self.module.fail_json(msg="failed to fetch manifests from %s: %s" % (url, info['msg']))
206 manifest_list = ET.fromstring(resp.read())
207 for manifest in manifest_list[0]:
208 manifests.append(manifest.attrib['id'])
209
210 except Exception as e:
211 self.module.fail_json(msg="Failed to fetch manifests from %s: %s" % (url, e))
212
213 for manifest in self.manifests:
214 validate_manifest_result = [m for m in manifests if m == manifest]
215 if not validate_manifest_result:
216 self.module.fail_json(msg="%s is a manifest that cannot be specified." % manifest)
217
218 def get_logbundle(self):
219 self.validate_manifests()
220 url = 'https://' + self.esxi_hostname + '/cgi-bin/vm-support.cgi?manifests=' + '%20'.join(self.manifests)
221
222 if self.performance_data:
223 duration = self.performance_data.get('duration')
224 interval = self.performance_data.get('interval')
225 url = url + '&performance=true&duration=%s&interval=%s' % (duration, interval)
226
227 headers = self.generate_req_headers(url)
228
229 try:
230 if self.download_timeout is not None:
231 resp, info = fetch_url(self.module, method='GET', headers=headers, url=url, timeout=self.download_timeout)
232 else:
233 resp, info = fetch_url(self.module, method='GET', headers=headers, url=url)
234 if info['status'] != 200:
235 self.module.fail_json(msg="failed to fetch logbundle from %s: %s" % (url, info['msg']))
236 with open(self.dest, 'wb') as local_file:
237 local_file.write(resp.read())
238
239 except Exception as e:
240 self.module.fail_json(msg="Failed to fetch logbundle from %s: %s" % (url, e))
241
242 self.module.exit_json(changed=True, dest=self.dest)
243
244
245 def main():
246 argument_spec = base_argument_spec()
247 argument_spec.update(
248 esxi_hostname=dict(type='str', required=True),
249 dest=dict(type='str', required=True),
250 download_timeout=dict(type='int'),
251 manifests=dict(type='list', elements='str',
252 default=['System:Base', 'System:CoreDumps', 'System:EsxImage', 'System:IOFilter',
253 'System:LoadESX', 'System:Modules', 'System:RDMA', 'System:ResourceGroups',
254 'System:TPM', 'System:VFlash', 'System:VMTools', 'System:VmiofPlugins', 'System:ntp',
255 'System:uwstats', 'Fcd:Catalog', 'VirtualMachines:CoreDumps',
256 'VirtualMachines:VirtualMachineStats', 'VirtualMachines:base', 'VirtualMachines:base',
257 'VirtualMachines:diskinfo', 'VirtualMachines:logs', 'Storage:FCoE',
258 'Storage:Multipathing', 'Storage:NAS', 'Storage:VSAN', 'Storage:VSANHealth',
259 'Storage:VSANIscsiTarget', 'Storage:VSANPerfStats', 'Storage:VSANPerfSvc',
260 'Storage:VSANTraces', 'Storage:VVOL', 'Storage:base', 'Storage:iodm', 'Storage:iscsi',
261 'FeatureStateSwitch:FeatureStateSwitch', 'Userworld:HostAgent',
262 'Userworld:ProcessInformation', 'Configuration:System', 'Logs:System',
263 'hostProfiles:SystemImageCacheHostProfile', 'hostProfiles:hostProfiles',
264 'FileSystem:VMFSDiskDump', 'FileSystem:base', 'ActiveDirectory:base', 'CIM:base',
265 'Hardware:base', 'Hardware:usb', 'Installer:base', 'Network:base', 'Network:dvs',
266 'Network:lacp', 'Network:nscd', 'Network:tcpip', 'IntegrityChecks:md5sums']),
267 performance_data=dict(type='dict', required=False,
268 options=dict(
269 duration=dict(type='int', default=300),
270 interval=dict(type='int', default=5)
271 ))
272 )
273
274 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
275
276 vmware_host_logbundle_mgr = VMwareHostLogbundle(module)
277 vmware_host_logbundle_mgr.get_logbundle()
278
279
280 if __name__ == "__main__":
281 main()