Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Ansible Project
5 # Copyright: (c) 2018, 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_video
16 short_description: Modify video card configurations of specified virtual machine in given vCenter infrastructure
17 description:
18 - This module is used to reconfigure video card settings of given virtual machine.
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 datacenter:
54 default: ha-datacenter
55 description:
56 - The datacenter name to which virtual machine belongs to.
57 type: str
58 gather_video_facts:
59 description:
60 - If set to V(true), return settings of the video card, other attributes are ignored.
61 - If set to V(false), will do reconfiguration and return video card settings.
62 type: bool
63 default: false
64 use_auto_detect:
65 description:
66 - 'If set to V(true), applies common video settings to the guest operating system, attributes O(display_number) and O(video_memory_mb) are ignored.'
67 - 'If set to V(false), the number of display and the total video memory will be reconfigured using O(display_number) and O(video_memory_mb).'
68 type: bool
69 display_number:
70 description:
71 - The number of display. Valid value from 1 to 10. The maximum display number is 4 on vCenter 6.0, 6.5 web UI.
72 type: int
73 video_memory_mb:
74 description:
75 - 'Valid total MB of video memory range of virtual machine is from 1.172 MB to 256 MB on ESXi 6.7U1,
76 from 1.172 MB to 128 MB on ESXi 6.7 and previous versions.'
77 - For specific guest OS, supported minimum and maximum video memory are different, please be careful on setting this.
78 type: float
79 enable_3D:
80 description:
81 - Enable 3D for guest operating systems on which VMware supports 3D.
82 type: bool
83 renderer_3D:
84 description:
85 - 'If set to V(automatic), selects the appropriate option (software or hardware) for this virtual machine automatically.'
86 - 'If set to V(software), uses normal CPU processing for 3D calculations.'
87 - 'If set to V(hardware), requires graphics hardware (GPU) for faster 3D calculations.'
88 choices: [ automatic, software, hardware ]
89 type: str
90 memory_3D_mb:
91 description:
92 - The value of 3D Memory must be power of 2 and valid value is from 32 MB to 2048 MB.
93 type: int
94 extends_documentation_fragment:
95 - vmware.vmware.base_options
96
97 '''
98
99 EXAMPLES = r'''
100 - name: Change video card settings of virtual machine
101 community.vmware.vmware_guest_video:
102 hostname: "{{ vcenter_hostname }}"
103 username: "{{ vcenter_username }}"
104 password: "{{ vcenter_password }}"
105 datacenter: "{{ datacenter_name }}"
106 name: test-vm
107 gather_video_facts: false
108 use_auto_detect: false
109 display_number: 2
110 video_memory_mb: 8.0
111 enable_3D: true
112 renderer_3D: automatic
113 memory_3D_mb: 512
114 delegate_to: localhost
115 register: video_facts
116
117 - name: Change video card settings of virtual machine using MoID
118 community.vmware.vmware_guest_video:
119 hostname: "{{ vcenter_hostname }}"
120 username: "{{ vcenter_username }}"
121 password: "{{ vcenter_password }}"
122 datacenter: "{{ datacenter_name }}"
123 moid: vm-42
124 gather_video_facts: false
125 use_auto_detect: false
126 display_number: 2
127 video_memory_mb: 8.0
128 enable_3D: true
129 renderer_3D: automatic
130 memory_3D_mb: 512
131 delegate_to: localhost
132 register: video_facts
133
134 - name: Gather video card settings of virtual machine
135 community.vmware.vmware_guest_video:
136 hostname: "{{ vcenter_hostname }}"
137 username: "{{ vcenter_username }}"
138 password: "{{ vcenter_password }}"
139 datacenter: "{{ datacenter_name }}"
140 name: test-vm
141 gather_video_facts: false
142 delegate_to: localhost
143 register: video_facts
144 '''
145
146 RETURN = r'''
147 video_status:
148 description: metadata about the virtual machine's video card after managing them
149 returned: always
150 type: dict
151 sample: {
152 "auto_detect": false,
153 "display_number": 2,
154 "enable_3D_support": true,
155 "memory_3D": 524288,
156 "renderer_3D": "automatic",
157 "video_memory": 8192
158 }
159 '''
160
161 try:
162 from pyVmomi import vim
163 except ImportError:
164 pass
165
166 from ansible.module_utils.basic import AnsibleModule
167 from ansible.module_utils.common.text.converters import to_native
168 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, wait_for_task
169 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
170
171
172 class PyVmomiHelper(PyVmomi):
173 def __init__(self, module):
174 super(PyVmomiHelper, self).__init__(module)
175 self.change_detected = False
176 self.config_spec = vim.vm.ConfigSpec()
177 self.config_spec.deviceChange = []
178 self.video_card_facts = None
179
180 @staticmethod
181 def is_power_of_2(num):
182 return num != 0 and ((num & (num - 1)) == 0)
183
184 def gather_video_card_facts(self, vm_obj):
185 """
186 Gather facts about VM's video card settings
187 Args:
188 vm_obj: Managed object of virtual machine
189 Returns: Video Card device and a list of dict video card configuration
190 """
191 video_facts = dict()
192 video_card = None
193 for device in vm_obj.config.hardware.device:
194 if isinstance(device, vim.vm.device.VirtualVideoCard):
195 video_card = device
196 video_facts = dict(
197 auto_detect=device.useAutoDetect,
198 display_number=device.numDisplays,
199 video_memory=device.videoRamSizeInKB,
200 enable_3D_support=device.enable3DSupport,
201 renderer_3D=device.use3dRenderer,
202 memory_3D=device.graphicsMemorySizeInKB,
203 )
204 break
205 return video_card, video_facts
206
207 def get_video_card_spec(self, vm_obj):
208 """
209 Get device changes of virtual machine
210 Args:
211 vm_obj: Managed object of virtual machine
212 Returns: virtual device spec
213 """
214 video_card, video_card_facts = self.gather_video_card_facts(vm_obj)
215 self.video_card_facts = video_card_facts
216 if video_card is None:
217 self.module.fail_json(msg='Unable to get video card device for the specified virtual machine.')
218 video_spec = vim.vm.device.VirtualDeviceSpec()
219 video_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
220 video_spec.device = video_card
221 auto_detect = False
222 enabled_3d = False
223
224 if self.params['gather_video_facts']:
225 return None
226 if self.params['use_auto_detect'] is not None:
227 if video_card_facts['auto_detect'] and self.params['use_auto_detect']:
228 auto_detect = True
229 elif not video_card_facts['auto_detect'] and self.params['use_auto_detect']:
230 video_spec.device.useAutoDetect = True
231 self.change_detected = True
232 auto_detect = True
233 elif video_card_facts['auto_detect'] and not self.params['use_auto_detect']:
234 video_spec.device.useAutoDetect = False
235 self.change_detected = True
236 else:
237 if video_card_facts['auto_detect']:
238 auto_detect = True
239 # useAutoDetect set to False then display number and video memory config can be changed
240 if not auto_detect:
241 if self.params['display_number'] is not None:
242 if self.params['display_number'] < 1:
243 self.module.fail_json(msg="display_number attribute valid value: 1-10.")
244 if self.params['display_number'] != video_card_facts['display_number']:
245 video_spec.device.numDisplays = self.params['display_number']
246 self.change_detected = True
247
248 if self.params['video_memory_mb'] is not None:
249 if self.params['video_memory_mb'] < 1.172:
250 self.module.fail_json(msg="video_memory_mb attribute valid value: ESXi 6.7U1(1.172-256 MB),"
251 "ESXi 6.7/6.5/6.0(1.172-128 MB).")
252 if int(self.params['video_memory_mb'] * 1024) != video_card_facts['video_memory']:
253 video_spec.device.videoRamSizeInKB = int(self.params['video_memory_mb'] * 1024)
254 self.change_detected = True
255 else:
256 if self.params['display_number'] is not None or self.params['video_memory_mb'] is not None:
257 self.module.fail_json(msg="display_number and video_memory_mb can not be changed if use_auto_detect is true.")
258 # useAutoDetect value not control 3D config
259 if self.params['enable_3D'] is not None:
260 if self.params['enable_3D'] != video_card_facts['enable_3D_support']:
261 video_spec.device.enable3DSupport = self.params['enable_3D']
262 self.change_detected = True
263 if self.params['enable_3D']:
264 enabled_3d = True
265 else:
266 if video_card_facts['enable_3D_support']:
267 enabled_3d = True
268 else:
269 if video_card_facts['enable_3D_support']:
270 enabled_3d = True
271 # 3D is enabled then 3D memory and renderer method can be set
272 if enabled_3d:
273 if self.params['renderer_3D'] is not None:
274 renderer = self.params['renderer_3D'].lower()
275 if renderer not in ['automatic', 'software', 'hardware']:
276 self.module.fail_json(msg="renderer_3D attribute valid value: automatic, software, hardware.")
277 if renderer != video_card_facts['renderer_3D']:
278 video_spec.device.use3dRenderer = renderer
279 self.change_detected = True
280 if self.params['memory_3D_mb'] is not None:
281 memory_3d = self.params['memory_3D_mb']
282 if not self.is_power_of_2(memory_3d):
283 self.module.fail_json(msg="memory_3D_mb attribute should be an integer value and power of 2(32-2048).")
284 else:
285 if memory_3d < 32 or memory_3d > 2048:
286 self.module.fail_json(msg="memory_3D_mb attribute should be an integer value and power of 2(32-2048).")
287 if memory_3d * 1024 != video_card_facts['memory_3D']:
288 video_spec.device.graphicsMemorySizeInKB = memory_3d * 1024
289 self.change_detected = True
290 else:
291 if self.params['renderer_3D'] is not None or self.params['memory_3D_mb'] is not None:
292 self.module.fail_json(msg='3D renderer or 3D memory can not be configured if 3D is not enabled.')
293 if not self.change_detected:
294 return None
295 return video_spec
296
297 def reconfigure_vm_video(self, vm_obj):
298 """
299 Reconfigure video card settings of virtual machine
300 Args:
301 vm_obj: Managed object of virtual machine
302 Returns: Reconfigure results
303 """
304 video_card_spec = self.get_video_card_spec(vm_obj)
305 if video_card_spec is None:
306 return {'changed': False, 'failed': False, 'instance': self.video_card_facts}
307 self.config_spec.deviceChange.append(video_card_spec)
308 try:
309 task = vm_obj.ReconfigVM_Task(spec=self.config_spec)
310 wait_for_task(task)
311 except vim.fault.InvalidDeviceSpec as invalid_device_spec:
312 self.module.fail_json(msg="Failed to configure video card on given virtual machine due to invalid"
313 " device spec : %s" % (to_native(invalid_device_spec.msg)),
314 details="Please check ESXi server logs for more details.")
315 except vim.fault.RestrictedVersion as e:
316 self.module.fail_json(msg="Failed to reconfigure virtual machine due to"
317 " product versioning restrictions: %s" % to_native(e.msg))
318 if task.info.state == 'error':
319 return {'changed': self.change_detected, 'failed': True, 'msg': task.info.error.msg}
320 video_card_facts = self.gather_video_card_facts(vm_obj)[1]
321 return {'changed': self.change_detected, 'failed': False, 'instance': video_card_facts}
322
323
324 def main():
325 argument_spec = base_argument_spec()
326 argument_spec.update(
327 name=dict(type='str'),
328 uuid=dict(type='str'),
329 moid=dict(type='str'),
330 folder=dict(type='str'),
331 datacenter=dict(type='str', default='ha-datacenter'),
332 gather_video_facts=dict(type='bool', default=False),
333 use_auto_detect=dict(type='bool'),
334 display_number=dict(type='int'),
335 video_memory_mb=dict(type='float'),
336 enable_3D=dict(type='bool'),
337 renderer_3D=dict(type='str', choices=['automatic', 'software', 'hardware']),
338 memory_3D_mb=dict(type='int'),
339 )
340
341 module = AnsibleModule(
342 argument_spec=argument_spec,
343 required_one_of=[
344 ['name', 'uuid', 'moid']
345 ]
346 )
347
348 pyv = PyVmomiHelper(module)
349 vm = pyv.get_vm()
350 if not vm:
351 vm_id = module.params.get('uuid') or module.params.get('name') or module.params.get('moid')
352 module.fail_json(msg='Unable to find the specified virtual machine : %s' % vm_id)
353
354 vm_facts = pyv.gather_facts(vm)
355 vm_power_state = vm_facts['hw_power_status'].lower()
356 gather_video_facts = module.params.get('gather_video_facts') or False
357 if vm_power_state != 'poweredoff':
358 if not gather_video_facts:
359 module.fail_json(msg='VM state should be poweredoff to reconfigure video card settings.')
360 result = pyv.reconfigure_vm_video(vm_obj=vm)
361 if result['failed']:
362 module.fail_json(**result)
363 module.exit_json(**result)
364
365
366 if __name__ == '__main__':
367 main()