Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2019, Ansible Project
5 # Copyright: (c) 2019, Diane Wang <[email protected]>
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = r'''
14 ---
15 module: vmware_guest_screenshot
16 short_description: Create a screenshot of the Virtual Machine console.
17 description:
18 - This module is used to take screenshot of the given virtual machine when virtual machine is powered on.
19 author:
20 - Diane Wang (@Tomorrow9) <[email protected]>
21 options:
22 name:
23 description:
24 - Name of the virtual machine.
25 - This is a required parameter, if parameter O(uuid) or O(moid) is not supplied.
26 type: str
27 uuid:
28 description:
29 - UUID of the instance to gather facts if known, this is VMware's unique identifier.
30 - This is a required parameter, if parameter O(name) or O(moid) is not supplied.
31 type: str
32 moid:
33 description:
34 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
35 - This is required if O(name) or O(uuid) is not supplied.
36 type: str
37 folder:
38 description:
39 - Destination folder, absolute or relative path to find an existing guest.
40 - This is a required parameter, only if multiple VMs are found with same name.
41 - The folder should include the datacenter. ESXi server's datacenter is ha-datacenter.
42 - 'Examples:'
43 - ' folder: /ha-datacenter/vm'
44 - ' folder: ha-datacenter/vm'
45 - ' folder: /datacenter1/vm'
46 - ' folder: datacenter1/vm'
47 - ' folder: /datacenter1/vm/folder1'
48 - ' folder: datacenter1/vm/folder1'
49 - ' folder: /folder1/datacenter1/vm'
50 - ' folder: folder1/datacenter1/vm'
51 - ' folder: /folder1/datacenter1/vm/folder2'
52 type: str
53 cluster:
54 description:
55 - The name of cluster where the virtual machine is running.
56 - This is a required parameter, if O(esxi_hostname) is not set.
57 - O(esxi_hostname) and O(cluster) are mutually exclusive.
58 type: str
59 esxi_hostname:
60 description:
61 - The ESXi hostname where the virtual machine is running.
62 - This is a required parameter, if O(cluster) is not set.
63 - O(esxi_hostname) and O(cluster) are mutually exclusive.
64 type: str
65 datacenter:
66 description:
67 - The datacenter name to which virtual machine belongs to.
68 type: str
69 local_path:
70 description:
71 - 'If not set, the created screenshot file will be kept in the directory of the virtual machine
72 on ESXi host. If set to a valid path on local machine, then the screenshot file will be
73 downloaded from ESXi host to the local directory.'
74 - 'If not download screenshot file to local machine, you can open it through the returned file URL in screenshot
75 facts manually.'
76 type: path
77 extends_documentation_fragment:
78 - vmware.vmware.base_options
79
80 '''
81
82 EXAMPLES = r'''
83 - name: take a screenshot of the virtual machine console
84 community.vmware.vmware_guest_screenshot:
85 hostname: "{{ vcenter_hostname }}"
86 username: "{{ vcenter_username }}"
87 password: "{{ vcenter_password }}"
88 datacenter: "{{ datacenter_name }}"
89 folder: "{{ folder_name }}"
90 name: "{{ vm_name }}"
91 local_path: "/tmp/"
92 delegate_to: localhost
93 register: take_screenshot
94
95 - name: Take a screenshot of the virtual machine console using MoID
96 community.vmware.vmware_guest_screenshot:
97 hostname: "{{ vcenter_hostname }}"
98 username: "{{ vcenter_username }}"
99 password: "{{ vcenter_password }}"
100 datacenter: "{{ datacenter_name }}"
101 folder: "{{ folder_name }}"
102 moid: vm-42
103 local_path: "/tmp/"
104 delegate_to: localhost
105 register: take_screenshot
106 '''
107
108 RETURN = r'''
109 screenshot_info:
110 description: display the facts of captured virtual machine screenshot file
111 returned: always
112 type: dict
113 sample: {
114 "virtual_machine": "test_vm",
115 "screenshot_file": "[datastore0] test_vm/test_vm-1.png",
116 "task_start_time": "2019-05-25T10:35:04.215016Z",
117 "task_complete_time": "2019-05-25T10:35:04.412622Z",
118 "result": "success",
119 "screenshot_file_url": "https://test_vcenter/folder/test_vm/test_vm-1.png?dcPath=test-dc&dsName=datastore0",
120 "download_local_path": "/tmp/",
121 "download_file_size": 2367,
122 }
123 '''
124
125 try:
126 from pyVmomi import vim, vmodl
127 except ImportError:
128 pass
129
130 from ansible.module_utils.basic import AnsibleModule
131 from urllib.parse import urlencode, quote
132 from ansible.module_utils.common.text.converters import to_native
133 from ansible.module_utils.urls import open_url
134 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, wait_for_task, get_parent_datacenter
135 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
136 import os
137
138
139 class PyVmomiHelper(PyVmomi):
140 def __init__(self, module):
141 super(PyVmomiHelper, self).__init__(module)
142 self.change_detected = False
143
144 def generate_http_access_url(self, file_path):
145 # e.g., file_path is like this format: [datastore0] test_vm/test_vm-1.png
146 # from file_path generate URL
147 url_path = None
148 if not file_path:
149 return url_path
150
151 path = "/folder/%s" % quote(file_path.split()[1])
152 params = dict(dsName=file_path.split()[0].strip('[]'))
153 if not self.is_vcenter():
154 datacenter = 'ha-datacenter'
155 else:
156 datacenter = get_parent_datacenter(self.current_vm_obj).name.replace('&', '%26')
157 params['dcPath'] = datacenter
158 url_path = "https://%s%s?%s" % (self.params['hostname'], path, urlencode(params))
159
160 return url_path
161
162 def download_screenshot_file(self, file_url, local_file_path, file_name):
163 response = None
164 download_size = 0
165 # file is downloaded as local_file_name when specified, or use original file name
166 if local_file_path.endswith('.png'):
167 local_file_name = local_file_path.split('/')[-1]
168 local_file_path = local_file_path.rsplit('/', 1)[0]
169 else:
170 local_file_name = file_name
171 if not os.path.exists(local_file_path):
172 try:
173 os.makedirs(local_file_path)
174 except OSError as err:
175 self.module.fail_json(msg="Exception caught when create folder %s on local machine, with error %s"
176 % (local_file_path, to_native(err)))
177 local_file = os.path.join(local_file_path, local_file_name)
178 with open(local_file, 'wb') as handle:
179 try:
180 response = open_url(file_url, url_username=self.params.get('username'),
181 url_password=self.params.get('password'), validate_certs=False)
182 except Exception as err:
183 self.module.fail_json(msg="Download screenshot file from URL %s, failed due to %s" % (file_url, to_native(err)))
184 if not response or response.getcode() >= 400:
185 self.module.fail_json(msg="Download screenshot file from URL %s, failed with response %s, response code %s"
186 % (file_url, response, response.getcode()))
187 bytes_read = response.read(2 ** 20)
188 while bytes_read:
189 handle.write(bytes_read)
190 handle.flush()
191 os.fsync(handle.fileno())
192 download_size += len(bytes_read)
193 bytes_read = response.read(2 ** 20)
194
195 return download_size
196
197 def get_screenshot_facts(self, task_info, file_url, file_size):
198 screenshot_facts = dict()
199 if task_info is not None:
200 screenshot_facts = dict(
201 virtual_machine=task_info.entityName,
202 screenshot_file=task_info.result,
203 task_start_time=task_info.startTime,
204 task_complete_time=task_info.completeTime,
205 result=task_info.state,
206 screenshot_file_url=file_url,
207 download_local_path=self.params.get('local_path'),
208 download_file_size=file_size,
209 )
210
211 return screenshot_facts
212
213 def take_vm_screenshot(self):
214 if self.current_vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn:
215 self.module.fail_json(msg="VM is %s, valid power state is poweredOn." % self.current_vm_obj.runtime.powerState)
216 try:
217 task = self.current_vm_obj.CreateScreenshot_Task()
218 wait_for_task(task)
219 except vim.fault.FileFault as e:
220 self.module.fail_json(msg="Failed to create screenshot due to errors when creating or accessing one or more"
221 " files needed for this operation, %s" % to_native(e.msg))
222 except vim.fault.InvalidState as e:
223 self.module.fail_json(msg="Failed to create screenshot due to VM is not ready to respond to such requests,"
224 " %s" % to_native(e.msg))
225 except vmodl.RuntimeFault as e:
226 self.module.fail_json(msg="Failed to create screenshot due to runtime fault, %s," % to_native(e.msg))
227 except vim.fault.TaskInProgress as e:
228 self.module.fail_json(msg="Failed to create screenshot due to VM is busy, %s" % to_native(e.msg))
229
230 if task.info.state == 'error':
231 return {'changed': self.change_detected, 'failed': True, 'msg': task.info.error.msg}
232 else:
233 download_file_size = None
234 self.change_detected = True
235 file_url = self.generate_http_access_url(task.info.result)
236 if self.params.get('local_path'):
237 if file_url:
238 download_file_size = self.download_screenshot_file(file_url=file_url,
239 local_file_path=self.params['local_path'],
240 file_name=task.info.result.split('/')[-1])
241 screenshot_facts = self.get_screenshot_facts(task.info, file_url, download_file_size)
242 return {'changed': self.change_detected, 'failed': False, 'screenshot_info': screenshot_facts}
243
244
245 def main():
246 argument_spec = base_argument_spec()
247 argument_spec.update(
248 name=dict(type='str'),
249 uuid=dict(type='str'),
250 moid=dict(type='str'),
251 folder=dict(type='str'),
252 datacenter=dict(type='str'),
253 esxi_hostname=dict(type='str'),
254 cluster=dict(type='str'),
255 local_path=dict(type='path'),
256 )
257 module = AnsibleModule(
258 argument_spec=argument_spec,
259 required_one_of=[
260 ['name', 'uuid', 'moid']
261 ]
262 )
263 pyv = PyVmomiHelper(module)
264 vm = pyv.get_vm()
265 if not vm:
266 vm_id = (module.params.get('uuid') or module.params.get('name') or module.params.get('moid'))
267 module.fail_json(msg='Unable to find the specified virtual machine : %s' % vm_id)
268
269 result = pyv.take_vm_screenshot()
270 if result['failed']:
271 module.fail_json(**result)
272 else:
273 module.exit_json(**result)
274
275
276 if __name__ == '__main__':
277 main()