Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2019, Anusha Hegde <[email protected]>
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_guest_serial_port
15 short_description: Manage serial ports on an existing VM
16 description:
17 - "This module can be used to manage serial ports on an existing VM"
18 options:
19 name:
20 description:
21 - Name of the virtual machine.
22 - This is a required parameter, if parameter O(uuid) or O(moid) is not supplied.
23 type: str
24 uuid:
25 description:
26 - UUID of the instance to manage the serial ports, this is VMware's unique identifier.
27 - This is a required parameter, if parameter O(name) or O(moid) is not supplied.
28 type: str
29 moid:
30 description:
31 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
32 - This is required if O(name) or O(uuid) is not supplied.
33 type: str
34 use_instance_uuid:
35 description:
36 - Whether to use the VMware instance UUID rather than the BIOS UUID.
37 default: false
38 type: bool
39 backings:
40 type: list
41 elements: dict
42 description:
43 - A list of backings for serial ports.
44 - 'O(backings[].backing_type) is required to add or reconfigure or remove an existing serial port.'
45 required: true
46 suboptions:
47 backing_type:
48 description:
49 - Backing type is required for the serial ports to be added or reconfigured or removed.
50 type: str
51 required: true
52 aliases:
53 - type
54 state:
55 description:
56 - O(backings[].state) is required to identify whether we are adding, modifying or removing the serial port.
57 - If V(present), a serial port will be added or modified.
58 - If V(absent), an existing serial port will be removed.
59 - If an existing serial port to modify or remove, O(backings[].backing_type) and either of O(backings[].service_uri) or O(backings[].pipe_name)
60 or O(backings[].device_name) or O(backings[].file_path) are required.
61 choices:
62 - present
63 - absent
64 type: str
65 default: present
66 yield_on_poll:
67 description:
68 - Enables CPU yield behavior.
69 type: bool
70 default: true
71 pipe_name:
72 description:
73 - Pipe name for the host pipe.
74 - Required when O(backings[].backing_type=pipe).
75 type: str
76 endpoint:
77 description:
78 - When you use serial port pipe backing to connect a virtual machine to another process, you must define the endpoints.
79 - Required when O(backings[].backing_type=pipe).
80 type: str
81 choices:
82 - client
83 - server
84 default: client
85 no_rx_loss:
86 description:
87 - Enables optimized data transfer over the pipe.
88 - Required when O(backings[].backing_type=pipe).
89 type: bool
90 default: false
91 service_uri:
92 description:
93 - Identifies the local host or a system on the network, depending on the value of O(backings[].direction).
94 - If you use the virtual machine as a server, the URI identifies the host on which the virtual machine runs.
95 - In this case, the host name part of the URI should be empty, or it should specify the address of the local host.
96 - If you use the virtual machine as a client, the URI identifies the remote system on the network.
97 - Required when O(backings[].backing_type=pipe).
98 type: str
99 proxy_uri:
100 description:
101 - Identifies a vSPC proxy service that provides network access to the O(backings[].service_uri).
102 - If you specify a proxy URI, the virtual machine initiates a connection with the proxy service
103 and forwards the serviceURI and direction to the proxy.
104 - The C(Use Virtual Serial Port Concentrator) option is automatically enabled when O(backings[].proxy_uri) is set.
105 type: str
106 version_added: '3.7.0'
107 direction:
108 description:
109 - The direction of the connection.
110 - Required when O(backings[].backing_type=network).
111 type: str
112 choices:
113 - client
114 - server
115 default: client
116 device_name:
117 description:
118 - Serial device absolutely path.
119 - Required when O(backings[].backing_type=device).
120 type: str
121 file_path:
122 description:
123 - File path for the host file used in this backing. Fully qualified path is required, like <datastore_name>/<file_name>.
124 - Required when O(backings[].backing_type=file).
125 type: str
126 extends_documentation_fragment:
127 - vmware.vmware.base_options
128 author:
129 - Anusha Hegde (@anusha94)
130 '''
131
132 EXAMPLES = r'''
133 # Create serial ports
134 - name: Create multiple serial ports with Backing type - network, pipe, device and file
135 community.vmware.vmware_guest_serial_port:
136 hostname: "{{ vcenter_hostname }}"
137 username: "{{ vcenter_username }}"
138 password: "{{ vcenter_password }}"
139 name: "test_vm1"
140 backings:
141 - type: 'network'
142 direction: 'client'
143 service_uri: 'tcp://6000'
144 yield_on_poll: true
145 - type: 'pipe'
146 pipe_name: 'serial_pipe'
147 endpoint: 'client'
148 - type: 'device'
149 device_name: '/dev/char/serial/uart0'
150 - type: 'file'
151 file_path: '[datastore1]/file1'
152 yield_on_poll: true
153 register: create_multiple_ports
154
155 # Create vSPC port
156 - name: Create network serial port with vSPC
157 community.vmware.vmware_guest_serial_port:
158 hostname: "{{ vcenter_hostname }}"
159 username: "{{ vcenter_username }}"
160 password: "{{ vcenter_password }}"
161 name: "test_vm1"
162 backings:
163 - type: 'network'
164 direction: 'server'
165 service_uri: 'vSPC.py'
166 proxy_uri: 'telnets://<host>:<port>'
167 yield_on_poll: true
168
169 # Modify existing serial port
170 - name: Modify Network backing type
171 community.vmware.vmware_guest_serial_port:
172 hostname: '{{ vcenter_hostname }}'
173 username: '{{ vcenter_username }}'
174 password: '{{ vcenter_password }}'
175 name: '{{ name }}'
176 backings:
177 - type: 'network'
178 state: 'present'
179 direction: 'server'
180 service_uri: 'tcp://6000'
181 delegate_to: localhost
182
183 # Remove serial port
184 - name: Remove pipe backing type
185 community.vmware.vmware_guest_serial_port:
186 hostname: '{{ vcenter_hostname }}'
187 username: '{{ vcenter_username }}'
188 password: '{{ vcenter_password }}'
189 name: '{{ name }}'
190 backings:
191 - type: 'pipe'
192 state: 'absent'
193 delegate_to: localhost
194 '''
195
196 RETURN = r'''
197 serial_port_data:
198 description: metadata about the virtual machine's serial ports after managing them
199 returned: always
200 type: dict
201 sample: [
202 {
203 "backing_type": "network",
204 "direction": "client",
205 "service_uri": "tcp://6000"
206 },
207 {
208 "backing_type": "pipe",
209 "direction": "server",
210 "pipe_name": "serial pipe"
211 },
212 ]
213 '''
214
215 from ansible.module_utils.basic import AnsibleModule
216 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, wait_for_task
217 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
218 from ansible.module_utils.common.text.converters import to_native
219 try:
220 from pyVmomi import vim
221 except ImportError:
222 pass
223
224
225 class PyVmomiHelper(PyVmomi):
226 """ This class is a helper to create easily VMware Spec for PyVmomiHelper """
227
228 def __init__(self, module):
229 super(PyVmomiHelper, self).__init__(module)
230 self.change_applied = False # a change was applied meaning at least one task succeeded
231 self.config_spec = vim.vm.ConfigSpec()
232 self.config_spec.deviceChange = []
233 self.serial_ports = []
234
235 def check_vm_state(self, vm_obj):
236 """
237 To add serial port, the VM must be in powered off state
238
239 Input:
240 - vm: Virtual Machine
241
242 Output:
243 - True if vm is in poweredOff state
244 - module fails otherwise
245 """
246 if vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOff:
247 return True
248 self.module.fail_json(msg="A serial device cannot be added to a VM in the current state(" + vm_obj.runtime.powerState + "). "
249 "Please use the vmware_guest_powerstate module to power off the VM")
250
251 def get_serial_port_config_spec(self, vm_obj):
252 """
253 Variables changed:
254 - self.config_spec
255 - self.change_applied
256 """
257 # create serial config spec for adding, editing, removing
258 for backing in self.params.get('backings'):
259 serial_port = get_serial_port(vm_obj, backing)
260 if serial_port:
261 serial_spec = vim.vm.device.VirtualDeviceSpec()
262 serial_spec.device = serial_port
263 if diff_serial_port_config(serial_port, backing):
264 if backing['state'] == 'present':
265 # modify existing serial port
266 serial_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
267 backing_type = backing.get('type', backing.get('backing_type'))
268 serial_spec.device.backing = self.get_backing_info(serial_port, backing, backing_type)
269 serial_spec.device.yieldOnPoll = backing['yield_on_poll']
270 self.change_applied = True
271 self.config_spec.deviceChange.append(serial_spec)
272 elif backing['state'] == 'absent':
273 # remove serial port
274 serial_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove
275 self.change_applied = True
276 self.config_spec.deviceChange.append(serial_spec)
277 else:
278 if backing['state'] == 'present':
279 # if serial port is None
280 # create a new serial port
281 serial_port_spec = self.create_serial_port(backing)
282 serial_port_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
283 self.serial_ports.append(serial_port_spec)
284 self.change_applied = True
285
286 def reconfigure_vm_serial_port(self, vm_obj):
287 """
288 Reconfigure vm with new or modified serial port config spec
289 """
290 self.get_serial_port_config_spec(vm_obj)
291 try:
292 # configure create tasks first
293 if self.serial_ports:
294 for serial_port in self.serial_ports:
295 # each type of serial port is of config_spec.device = vim.vm.device.VirtualSerialPort() object type
296 # because serial ports differ in the backing types and config_spec.device has to be unique,
297 # we are creating a new spec for every create port configuration
298 spec = vim.vm.ConfigSpec()
299 spec.deviceChange.append(serial_port)
300 task = vm_obj.ReconfigVM_Task(spec=spec)
301 wait_for_task(task)
302 task = vm_obj.ReconfigVM_Task(spec=self.config_spec)
303 wait_for_task(task)
304 except vim.fault.InvalidDatastorePath as e:
305 self.module.fail_json(msg="Failed to configure serial port on given virtual machine due to invalid path: %s" % to_native(e.msg))
306 except vim.fault.RestrictedVersion as e:
307 self.module.fail_json(msg="Failed to reconfigure virtual machine due to product versioning restrictions: %s" % to_native(e.msg))
308 if task.info.state == 'error':
309 results = {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg}
310 else:
311 serial_port_info = get_serial_port_info(vm_obj)
312 results = {'changed': self.change_applied, 'failed': False, 'serial_port_info': serial_port_info}
313
314 return results
315
316 def set_network_backing(self, serial_port, backing_info):
317 """
318 Set the networking backing params
319 """
320 required_params = ['service_uri', 'direction']
321 if set(required_params).issubset(backing_info.keys()):
322 backing = serial_port.URIBackingInfo()
323 backing.serviceURI = backing_info['service_uri']
324 backing.proxyURI = backing_info['proxy_uri']
325 backing.direction = backing_info['direction']
326 else:
327 self.module.fail_json(msg="Failed to create a new serial port of network backing type due to insufficient parameters."
328 + "The required parameters are service_uri and direction")
329 return backing
330
331 def set_pipe_backing(self, serial_port, backing_info):
332 """
333 Set the pipe backing params
334 """
335 required_params = ['pipe_name', 'endpoint']
336 if set(required_params).issubset(backing_info.keys()):
337 backing = serial_port.PipeBackingInfo()
338 backing.pipeName = backing_info['pipe_name']
339 backing.endpoint = backing_info['endpoint']
340 else:
341 self.module.fail_json(msg="Failed to create a new serial port of pipe backing type due to insufficient parameters."
342 + "The required parameters are pipe_name and endpoint")
343
344 # since no_rx_loss is an optional argument, so check if the key is present
345 if 'no_rx_loss' in backing_info.keys() and backing_info['no_rx_loss']:
346 backing.noRxLoss = backing_info['no_rx_loss']
347 return backing
348
349 def set_device_backing(self, serial_port, backing_info):
350 """
351 Set the device backing params
352 """
353 required_params = ['device_name']
354 if set(required_params).issubset(backing_info.keys()):
355 backing = serial_port.DeviceBackingInfo()
356 backing.deviceName = backing_info['device_name']
357 else:
358 self.module.fail_json(msg="Failed to create a new serial port of device backing type due to insufficient parameters."
359 + "The required parameters are device_name")
360 return backing
361
362 def set_file_backing(self, serial_port, backing_info):
363 """
364 Set the file backing params
365 """
366 required_params = ['file_path']
367 if set(required_params).issubset(backing_info.keys()):
368 backing = serial_port.FileBackingInfo()
369 backing.fileName = backing_info['file_path']
370 else:
371 self.module.fail_json(msg="Failed to create a new serial port of file backing type due to insufficient parameters."
372 + "The required parameters are file_path")
373 return backing
374
375 def get_backing_info(self, serial_port, backing, backing_type):
376 """
377 Returns the call to the appropriate backing function based on the backing type
378 """
379 switcher = {
380 "network": self.set_network_backing,
381 "pipe": self.set_pipe_backing,
382 "device": self.set_device_backing,
383 "file": self.set_file_backing
384 }
385 backing_func = switcher.get(backing_type, None)
386 if backing_func is None:
387 self.module.fail_json(msg="Failed to find a valid backing type. "
388 "Provided '%s', should be one of [%s]" % (backing_type, ', '.join(switcher.keys())))
389 return backing_func(serial_port, backing)
390
391 def create_serial_port(self, backing):
392 """
393 Create a new serial port
394 """
395 serial_spec = vim.vm.device.VirtualDeviceSpec()
396 serial_port = vim.vm.device.VirtualSerialPort()
397 serial_port.yieldOnPoll = backing['yield_on_poll']
398 backing_type = backing.get('type', backing.get('backing_type', None))
399 serial_port.backing = self.get_backing_info(serial_port, backing, backing_type)
400 serial_spec.device = serial_port
401 return serial_spec
402
403
404 def get_serial_port(vm_obj, backing):
405 """
406 Return the serial port of specified backing type
407 """
408 serial_port = None
409 backing_type_mapping = {
410 'network': vim.vm.device.VirtualSerialPort.URIBackingInfo,
411 'pipe': vim.vm.device.VirtualSerialPort.PipeBackingInfo,
412 'device': vim.vm.device.VirtualSerialPort.DeviceBackingInfo,
413 'file': vim.vm.device.VirtualSerialPort.FileBackingInfo
414 }
415 valid_params = backing.keys()
416 for device in vm_obj.config.hardware.device:
417 if isinstance(device, vim.vm.device.VirtualSerialPort):
418 backing_type = backing.get('type', backing.get('backing_type', None))
419 if isinstance(device.backing, backing_type_mapping[backing_type]):
420 if 'service_uri' in valid_params:
421 # network backing type
422 serial_port = device
423 break
424 if 'pipe_name' in valid_params:
425 # named pipe backing type
426 serial_port = device
427 break
428 if 'device_name' in valid_params:
429 # physical serial device backing type
430 serial_port = device
431 break
432 if 'file_path' in valid_params:
433 # file backing type
434 serial_port = device
435 break
436 # if there is a backing of only one type, user need not provide secondary details like service_uri, pipe_name, device_name or file_path
437 # we will match the serial port with backing type only
438 # in this case, the last matching serial port will be returned
439 serial_port = device
440 return serial_port
441
442
443 def get_serial_port_info(vm_obj):
444 """
445 Get the serial port info
446 """
447 serial_port_info = []
448 if vm_obj is None:
449 return serial_port_info
450 for port in vm_obj.config.hardware.device:
451 backing = dict()
452 if isinstance(port, vim.vm.device.VirtualSerialPort):
453 if isinstance(port.backing, vim.vm.device.VirtualSerialPort.URIBackingInfo):
454 backing['backing_type'] = 'network'
455 backing['direction'] = port.backing.direction
456 backing['service_uri'] = port.backing.serviceURI
457 backing['proxy_uri'] = port.backing.proxyURI
458 elif isinstance(port.backing, vim.vm.device.VirtualSerialPort.PipeBackingInfo):
459 backing['backing_type'] = 'pipe'
460 backing['pipe_name'] = port.backing.pipeName
461 backing['endpoint'] = port.backing.endpoint
462 backing['no_rx_loss'] = port.backing.noRxLoss
463 elif isinstance(port.backing, vim.vm.device.VirtualSerialPort.DeviceBackingInfo):
464 backing['backing_type'] = 'device'
465 backing['device_name'] = port.backing.deviceName
466 elif isinstance(port.backing, vim.vm.device.VirtualSerialPort.FileBackingInfo):
467 backing['backing_type'] = 'file'
468 backing['file_path'] = port.backing.fileName
469 else:
470 continue
471 serial_port_info.append(backing)
472 return serial_port_info
473
474
475 def diff_serial_port_config(serial_port, backing):
476 if backing['state'] == 'present':
477 if 'yield_on_poll' in backing:
478 if serial_port.yieldOnPoll != backing['yield_on_poll']:
479 return True
480 if backing['service_uri'] is not None:
481 if serial_port.backing.serviceURI != backing['service_uri'] or \
482 serial_port.backing.direction != backing['direction'] or \
483 serial_port.backing.proxyURI != backing['proxy_uri']:
484 return True
485 if backing['pipe_name'] is not None:
486 if serial_port.backing.pipeName != backing['pipe_name'] or \
487 serial_port.backing.endpoint != backing['endpoint'] or \
488 serial_port.backing.noRxLoss != backing['no_rx_loss']:
489 return True
490 if backing['device_name'] is not None:
491 if serial_port.backing.deviceName != backing['device_name']:
492 return True
493 if backing['file_path'] is not None:
494 if serial_port.backing.fileName != backing['file_path']:
495 return True
496
497 if backing['state'] == 'absent':
498 if backing['service_uri'] is not None:
499 if serial_port.backing.serviceURI == backing['service_uri'] and \
500 serial_port.backing.proxyURI == backing['proxy_uri']:
501 return True
502 if backing['pipe_name'] is not None:
503 if serial_port.backing.pipeName == backing['pipe_name']:
504 return True
505 if backing['device_name'] is not None:
506 if serial_port.backing.deviceName == backing['device_name']:
507 return True
508 if backing['file_path'] is not None:
509 if serial_port.backing.fileName == backing['file_path']:
510 return True
511
512 return False
513
514
515 def main():
516 """
517 Main method
518 """
519 argument_spec = base_argument_spec()
520 argument_spec.update(
521 name=dict(type='str'),
522 uuid=dict(type='str'),
523 moid=dict(type='str'),
524 use_instance_uuid=dict(type='bool', default=False),
525 backings=dict(type='list', elements='dict', required=True,
526 options=dict(
527 backing_type=dict(type='str', required=True, aliases=['type']),
528 pipe_name=dict(type='str', default=None),
529 endpoint=dict(type='str', choices=['client', 'server'], default='client'),
530 no_rx_loss=dict(type='bool', default=False),
531 service_uri=dict(type='str', default=None),
532 proxy_uri=dict(type='str', default=None),
533 direction=dict(type='str', choices=['client', 'server'], default='client'),
534 device_name=dict(type='str', default=None),
535 file_path=dict(type='str', default=None),
536 yield_on_poll=dict(type='bool', default=True),
537 state=dict(type='str', choices=['present', 'absent'], default='present')
538 ),
539 required_if=[
540 ['backing_type', 'pipe', ['pipe_name', 'endpoint', 'no_rx_loss']],
541 ['backing_type', 'network', ['service_uri', 'direction']],
542 ['backing_type', 'device', ['device_name']],
543 ['backing_type', 'file', ['file_path']]
544 ]),
545 )
546
547 module = AnsibleModule(
548 argument_spec=argument_spec,
549 required_one_of=[
550 ['name', 'uuid', 'moid']
551 ],
552 mutually_exclusive=[
553 ['name', 'uuid', 'moid']
554 ],
555 )
556 result = {'failed': False, 'changed': False}
557
558 pyv = PyVmomiHelper(module)
559 # Check if the VM exists before continuing
560 vm_obj = pyv.get_vm()
561
562 if vm_obj:
563 proceed = pyv.check_vm_state(vm_obj)
564 if proceed:
565 result = pyv.reconfigure_vm_serial_port(vm_obj)
566
567 else:
568 # We are unable to find the virtual machine user specified
569 # Bail out
570 vm_id = (module.params.get('name') or module.params.get('uuid') or module.params.get('vm_id'))
571 module.fail_json(msg="Unable to manage serial ports for non-existing"
572 " virtual machine '%s'." % vm_id)
573
574 if result['failed']:
575 module.fail_json(**result)
576 else:
577 module.exit_json(**result)
578
579
580 if __name__ == '__main__':
581 main()