Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2021, 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 DOCUMENTATION = r"""
12 ---
13 module: vmware_host_passthrough
14 short_description: Manage PCI device passthrough settings on host
15 author:
16 - sky-joker (@sky-joker)
17 description:
18 - This module can be managed PCI device passthrough settings on host.
19 options:
20 cluster:
21 description:
22 - Name of the cluster from which all host systems will be used.
23 - This parameter is required if O(esxi_hostname) is not specified.
24 aliases:
25 - cluster_name
26 type: str
27 esxi_hostname:
28 description:
29 - Name of the host system to work with.
30 - This parameter is required if O(cluster_name) is not specified.
31 - User can specify specific host from the cluster.
32 type: str
33 devices:
34 description:
35 - List of PCI device name or id.
36 suboptions:
37 device:
38 description:
39 - Name of PCI device to enable passthrough.
40 aliases:
41 - name
42 - device_name
43 type: str
44 elements: dict
45 required: true
46 type: list
47 state:
48 description:
49 - If V(state=present), passthrough of PCI device will be enabled.
50 - If V(state=absent), passthrough of PCI device will be disabled.
51 choices:
52 - present
53 - absent
54 default: present
55 type: str
56 extends_documentation_fragment:
57 - vmware.vmware.base_options
58 """
59
60 EXAMPLES = r"""
61 - name: Enable PCI device passthrough against the whole ESXi in a cluster
62 community.vmware.vmware_host_passthrough:
63 hostname: "{{ vcenter_hostname }}"
64 username: "{{ vcenter_username }}"
65 password: "{{ vcenter_password }}"
66 validate_certs: false
67 cluster: "{{ ccr1 }}"
68 devices:
69 - device_name: "Dual Band Wireless AC 3165"
70 state: present
71
72 - name: Enable PCI device passthrough against one ESXi
73 community.vmware.vmware_host_passthrough:
74 hostname: "{{ vcenter_hostname }}"
75 username: "{{ vcenter_username }}"
76 password: "{{ vcenter_password }}"
77 validate_certs: false
78 esxi_hostname: "{{ esxi1 }}"
79 devices:
80 - device_name: "Dual Band Wireless AC 3165"
81 state: present
82
83 - name: Enable PCI device passthrough with PCI ids
84 community.vmware.vmware_host_passthrough:
85 hostname: "{{ vcenter_hostname }}"
86 username: "{{ vcenter_username }}"
87 password: "{{ vcenter_password }}"
88 validate_certs: false
89 esxi_hostname: "{{ esxi1 }}"
90 devices:
91 - device: '0000:03:00.0'
92 - device: '0000:00:02.0'
93 state: present
94
95 - name: Disable PCI device passthrough against the whole ESXi in a cluster
96 community.vmware.vmware_host_passthrough:
97 hostname: "{{ vcenter_hostname }}"
98 username: "{{ vcenter_username }}"
99 password: "{{ vcenter_password }}"
100 validate_certs: false
101 cluster: "{{ ccr1 }}"
102 devices:
103 - device_name: "Dual Band Wireless AC 3165"
104 state: absent
105 """
106
107 RETURN = r"""
108 passthrough_configs:
109 description:
110 - list of that PCI devices have been enabled passthrough for each host system.
111 returned: changed
112 type: list
113 elements: dict
114 sample: >-
115 [
116 {
117 "esxi-01.example.com": [
118 {
119 "device_id": "0000:03:00.0",
120 "device_name": "Dual Band Wireless AC 3165",
121 "passthruEnabled": true
122 }
123 ]
124 },
125 {
126 "esxi-02.example.com": [
127 {
128 "device_id": "0000:03:00.0",
129 "device_name": "Dual Band Wireless AC 3165",
130 "passthruEnabled": true
131 }
132 ]
133 }
134 ]
135 """
136
137 try:
138 from pyVmomi import vim
139 except ImportError:
140 pass
141
142 import copy
143 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
144 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
145 from ansible.module_utils.basic import AnsibleModule
146
147
148 class VMwareHostPassthrough(PyVmomi):
149 def __init__(self, module):
150 super(VMwareHostPassthrough, self).__init__(module)
151 self.cluster = self.params['cluster']
152 self.esxi_hostname = self.params['esxi_hostname']
153 self.devices = self.params['devices']
154 self.state = self.params['state']
155
156 self.hosts = self.get_all_host_objs(cluster_name=self.cluster, esxi_host_name=self.esxi_hostname)
157 # Looks for a specified ESXi host from a cluster if specified cluster and ESXi host.
158 if self.cluster and self.esxi_hostname:
159 self.hosts = [host_obj for host_obj in self.hosts if host_obj.name == self.esxi_hostname]
160 if not self.hosts:
161 self.module.fail_json(msg="Failed to find host system: %s" % self.esxi_hostname)
162
163 self.result = dict(changed=False, passthrough_configs=[], diff={})
164
165 def collect_pci_device_ids_for_supported_passthrough(self):
166 """
167 Collect device ids for supported passthrough from pciPassthruInfo.
168 The condition for whether support passthrough is that passthruCapable property has True.
169 """
170 self.hosts_passthrough_pci_device_id = {}
171 for host_obj in self.hosts:
172 esxi_hostname = host_obj.name
173 self.hosts_passthrough_pci_device_id[esxi_hostname] = {
174 'host_obj': host_obj,
175 'pci_device_ids': []
176 }
177 for pci_device in host_obj.config.pciPassthruInfo:
178 if pci_device.passthruCapable:
179 self.hosts_passthrough_pci_device_id[esxi_hostname]['pci_device_ids'].append(pci_device)
180
181 def collect_pci_devices_able_to_enable_passthrough(self):
182 """
183 Collect devices able to enable passthrough based on device id.
184 """
185 self.hosts_passthrough_pci_devices = []
186 for esxi_hostname, value in self.hosts_passthrough_pci_device_id.items():
187 pci_devices = []
188 for device_id in value['pci_device_ids']:
189 for device in value['host_obj'].hardware.pciDevice:
190 if device.id == device_id.id:
191 pci_devices.append({
192 'device_name': device.deviceName,
193 'device_id': device.id,
194 'passthruEnabled': device_id.passthruEnabled,
195 })
196 self.hosts_passthrough_pci_devices.append({
197 esxi_hostname: {
198 'host_obj': value['host_obj'],
199 'pci_devices': pci_devices
200 }
201 })
202
203 def check_whether_devices_exist(self):
204 """
205 Check specified pci devices are exists.
206 """
207 self.existent_devices = []
208 self.non_existent_devices = []
209
210 # The keys use in checking pci devices existing.
211 keys = ['device_name', 'device_id']
212
213 for host_pci_device in self.hosts_passthrough_pci_devices:
214 pci_devices = []
215 for esxi_hostname, value in host_pci_device.items():
216 for target_device in self.devices:
217 device = target_device['device']
218 if device in [pci_device.get(key) for key in keys for pci_device in value['pci_devices']]:
219 pci_devices.append(
220 [
221 pci_device for pci_device in value['pci_devices']
222 if device == pci_device['device_name'] or device == pci_device['device_id']
223 ]
224 )
225 else:
226 self.non_existent_devices.append(device)
227 self.existent_devices.append({
228 esxi_hostname: {
229 'host_obj': value['host_obj'],
230 'checked_pci_devices': self.de_duplication(sum(pci_devices, []))
231 }
232 })
233
234 def diff_passthrough_config(self):
235 """
236 Check there are differences between a new and existing config each ESXi host.
237 """
238 # Make the diff_config variable to check the difference between a new and existing config.
239 self.diff_config = dict(before={}, after={})
240
241 self.change_flag = False
242 self.host_target_device_to_change_configuration = {}
243 state = True if self.state == "present" else False
244 for host_has_checked_pci_devices in self.existent_devices:
245 for esxi_hostname, value in host_has_checked_pci_devices.items():
246 for key in 'before', 'after':
247 self.diff_config[key][esxi_hostname] = []
248 self.host_target_device_to_change_configuration[esxi_hostname] = {
249 'host_obj': None,
250 'new_configs': []
251 }
252 for target_device in self.devices:
253 device = target_device['device']
254 for checked_pci_device in value['checked_pci_devices']:
255 if device == checked_pci_device['device_name'] or device == checked_pci_device['device_id']:
256 before = dict(checked_pci_device)
257 after = dict(copy.deepcopy(checked_pci_device))
258
259 if state != checked_pci_device['passthruEnabled']:
260 self.change_flag = True
261 after['passthruEnabled'] = state
262
263 self.host_target_device_to_change_configuration[esxi_hostname]['new_configs'].append(after)
264 self.host_target_device_to_change_configuration[esxi_hostname]['host_obj'] = value['host_obj']
265 self.diff_config['before'][esxi_hostname].append(before)
266 self.diff_config['after'][esxi_hostname].append(after)
267
268 # De-duplicate pci device data and sort.
269 self.diff_config['before'][esxi_hostname] = sorted(
270 self.de_duplication(self.diff_config['before'][esxi_hostname]),
271 key=lambda d: d['device_name']
272 )
273 self.diff_config['after'][esxi_hostname] = sorted(
274 self.de_duplication(self.diff_config['after'][esxi_hostname]),
275 key=lambda d: d['device_name']
276 )
277
278 def generate_passthrough_configurations_to_be_applied(self):
279 """
280 Generate configs to enable or disable PCI device passthrough.
281 The configs are generated against only ESXi host has PCI device to be changed.
282 """
283 self.host_passthrough_configs = {}
284 for esxi_hostname, value in self.host_target_device_to_change_configuration.items():
285 self.host_passthrough_configs[esxi_hostname] = {
286 'host_obj': value['host_obj'],
287 'generated_new_configs': []
288 }
289 if value['new_configs']:
290 state = True if self.state == "present" else False
291 for new_config in value['new_configs']:
292 config = vim.host.PciPassthruConfig()
293 config.passthruEnabled = state
294 config.id = new_config['device_id']
295 self.host_passthrough_configs[esxi_hostname]['generated_new_configs'].append(config)
296
297 def de_duplication(self, data):
298 """
299 De-duplicate dictionaries in a list.
300 """
301 return [
302 dict(s) for s in set(frozenset(d.items()) for d in data)
303 ]
304
305 def execute(self):
306 self.collect_pci_device_ids_for_supported_passthrough()
307 self.collect_pci_devices_able_to_enable_passthrough()
308
309 self.check_whether_devices_exist()
310 if self.non_existent_devices:
311 self.module.fail_json(msg="Failed to fined device: %s" % list(set(self.non_existent_devices)))
312
313 self.diff_passthrough_config()
314 if self.change_flag and self.module.check_mode is False:
315 self.generate_passthrough_configurations_to_be_applied()
316 for value in self.host_passthrough_configs.values():
317 try:
318 host_obj = value['host_obj']
319 config = value['generated_new_configs']
320 host_obj.configManager.pciPassthruSystem.UpdatePassthruConfig(config)
321 except Exception as e:
322 self.module.fail_json(msg="Failed to operate PCI device passthrough: %s" % e)
323
324 # ESXi host configuration will be included in the result if it will be changed.
325 self.result['passthrough_configs'] = [
326 {
327 esxi_hostname: value['new_configs']
328 } for esxi_hostname, value in self.host_target_device_to_change_configuration.items() if value['new_configs']
329 ]
330 self.result['changed'] = self.change_flag
331 self.result['diff'] = self.diff_config
332 self.module.exit_json(**self.result)
333
334
335 def main():
336 argument_spec = base_argument_spec()
337 argument_spec.update(
338 cluster=dict(type='str', aliases=['cluster_name']),
339 esxi_hostname=dict(type='str'),
340 devices=dict(type='list', elements='dict', required=True,
341 options=dict(
342 device=dict(type='str', aliases=['name', 'device_name'])
343 )),
344 state=dict(type='str', default='present', choices=['present', 'absent'])
345 )
346
347 module = AnsibleModule(argument_spec=argument_spec,
348 required_one_of=[
349 ['cluster', 'esxi_hostname']
350 ],
351 supports_check_mode=True)
352
353 vmware_host_passthrough = VMwareHostPassthrough(module)
354 vmware_host_passthrough.execute()
355
356
357 if __name__ == "__main__":
358 main()