Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (C) 2020, Viktor Tsymbalyuk
5 # Copyright: (C) 2020, Ansible Project
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_host_sriov
16 short_description: Manage SR-IOV settings on host
17 description:
18 - This module can be used to configure, enable or disable SR-IOV functions on ESXi host.
19 - Module does not reboot the host after changes, but puts it in output "rebootRequired" state.
20 - User can specify an ESXi hostname or Cluster name. In case of cluster name, all ESXi hosts are updated.
21 author:
22 - Viktor Tsymbalyuk (@victron)
23 options:
24 esxi_hostname:
25 description:
26 - Name of the host system to work with.
27 - This parameter is required if O(cluster_name) is not specified.
28 - User can specify specific host from the cluster.
29 type: str
30 cluster_name:
31 description:
32 - Name of the cluster from which all host systems will be used.
33 - This parameter is required if O(esxi_hostname) is not specified.
34 type: str
35 vmnic:
36 description:
37 - Interface name, like vmnic0.
38 type: str
39 required: true
40 num_virt_func:
41 description:
42 - number of functions to activate on interface.
43 - 0 means SR-IOV disabled.
44 - number greater than 0 means SR-IOV enabled.
45 type: int
46 required: true
47 sriov_on:
48 description:
49 - optional parameter, related to O(num_virt_func).
50 - SR-IOV can be enabled only if O(num_virt_func) > 0.
51 type: bool
52 required: false
53 extends_documentation_fragment:
54 - vmware.vmware.base_options
55 '''
56
57 EXAMPLES = r'''
58 - name: enable SR-IOV on vmnic0 with 8 functions
59 community.vmware.vmware_host_sriov:
60 hostname: "{{ vcenter_hostname }}"
61 username: "{{ vcenter_username }}"
62 password: "{{ vcenter_password }}"
63 esxi_hostname: "{{ esxi1 }}"
64 vmnic: vmnic0
65 sriov_on: true
66 num_virt_func: 8
67
68 - name: enable SR-IOV on already enabled interface vmnic0
69 community.vmware.vmware_host_sriov:
70 hostname: "{{ vcenter_hostname }}"
71 username: "{{ vcenter_username }}"
72 password: "{{ vcenter_password }}"
73 esxi_hostname: "{{ esxi1 }}"
74 vmnic: vmnic0
75 sriov_on: true
76 num_virt_func: 8
77
78 - name: enable SR-IOV on vmnic0 with big number of functions
79 community.vmware.vmware_host_sriov:
80 hostname: "{{ vcenter_hostname }}"
81 username: "{{ vcenter_username }}"
82 password: "{{ vcenter_password }}"
83 esxi_hostname: "{{ esxi1 }}"
84 vmnic: vmnic0
85 sriov_on: true
86 num_virt_func: 100
87 ignore_errors: true
88
89 - name: disable SR-IOV on vmnic0
90 community.vmware.vmware_host_sriov:
91 hostname: "{{ vcenter_hostname }}"
92 username: "{{ vcenter_username }}"
93 password: "{{ vcenter_password }}"
94 esxi_hostname: "{{ esxi1 }}"
95 vmnic: vmnic0
96 sriov_on: false
97 num_virt_func: 0
98 '''
99
100 RETURN = r'''
101 host_sriov_diff:
102 description:
103 - contains info about SR-IOV status on vmnic before, after and requested changes
104 - sometimes vCenter slowly update info, as result "after" contains same info as "before"
105 need to run again in check_mode or reboot host, as ESXi requested
106 returned: always
107 type: dict
108 "sample": {
109 "changed": true,
110 "diff": {
111 "after": {
112 "host_test": {
113 "sriovActive": false,
114 "sriovEnabled": true,
115 "maxVirtualFunctionSupported": 63,
116 "numVirtualFunction": 0,
117 "numVirtualFunctionRequested": 8,
118 "rebootRequired": true,
119 "sriovCapable": true
120 }
121 },
122 "before": {
123 "host_test": {
124 "sriovActive": false,
125 "sriovEnabled": false,
126 "maxVirtualFunctionSupported": 63,
127 "numVirtualFunction": 0,
128 "numVirtualFunctionRequested": 0,
129 "rebootRequired": false,
130 "sriovCapable": true
131 }
132 },
133 "changes": {
134 "host_test": {
135 "numVirtualFunction": 8,
136 "rebootRequired": true,
137 "sriovEnabled": true
138 }
139 }
140 }
141 }
142 '''
143
144
145 try:
146 from pyVmomi import vim
147 except ImportError:
148 pass
149
150 from ansible.module_utils.basic import AnsibleModule
151 from ansible.module_utils.common.text.converters import to_native
152 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
153 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
154 from time import sleep
155
156
157 class VmwareAdapterConfigManager(PyVmomi):
158 """Class to configure SR-IOV settings"""
159
160 def __init__(self, module):
161 super(VmwareAdapterConfigManager, self).__init__(module)
162 cluster_name = self.params.get("cluster_name", None)
163 esxi_host_name = self.params.get("esxi_hostname", None)
164
165 self.vmnic = self.params.get("vmnic", None)
166 self.num_virt_func = self.params.get("num_virt_func", None)
167 self.sriov_on = self.params.get("sriov_on", None)
168
169 # prepare list of hosts to work with them
170 self.hosts = self.get_all_host_objs(
171 cluster_name=cluster_name, esxi_host_name=esxi_host_name
172 )
173 if not self.hosts:
174 self.module.fail_json(msg="Failed to find host system.")
175 self.results = {"before": {}, "after": {}, "changes": {}}
176
177 def sanitize_params(self):
178 """checks user input, raise error if input incompatible
179 :return : None
180 """
181
182 if self.num_virt_func < 0:
183 self.module.fail_json(msg="allowed value for num_virt_func >= 0")
184 if self.num_virt_func == 0:
185 if self.sriov_on is True:
186 self.module.fail_json(
187 msg="with sriov_on == true, allowed value for num_virt_func > 0"
188 )
189 self.sriov_on = False # fill value, if user not provided
190
191 if self.num_virt_func > 0:
192 if self.sriov_on is False:
193 self.module.fail_json(
194 msg="with sriov_on == false, allowed value for num_virt_func is 0"
195 )
196 self.sriov_on = True # fill value, if user not provided
197
198 def check_compatibility(self, before, hostname):
199 """
200 checks hardware compatibility with user input, raise error if input incompatible
201 :before : dict, of params on target interface before changing
202 :hostname : str, hosthame
203 :return : None
204 """
205 if self.num_virt_func > 0:
206 if not before["sriovCapable"]:
207 self.module.fail_json(
208 msg="sriov not supported on host= %s, nic= %s" % (hostname, self.vmnic)
209 )
210
211 if before["maxVirtualFunctionSupported"] < self.num_virt_func:
212 self.module.fail_json(
213 msg="maxVirtualFunctionSupported= %d on %s" % (before["maxVirtualFunctionSupported"], self.vmnic)
214 )
215
216 def make_diff(self, before, hostname):
217 """
218 preparing diff - changes which will be applied
219 :before : dict, of params on target interface before changing
220 :hostname : str, hosthame
221 :return : dict, of changes which is going to apply
222 """
223 diff = {}
224 change = False
225 change_msg = ""
226
227 if before["sriovEnabled"] != self.sriov_on:
228 diff["sriovEnabled"] = self.sriov_on
229 change = True
230
231 if before["numVirtualFunction"] != self.num_virt_func:
232 if before["numVirtualFunctionRequested"] != self.num_virt_func:
233 diff["numVirtualFunction"] = self.num_virt_func
234 change = True
235 else:
236 change_msg = "Not active (looks like not rebooted) "
237
238 if not change:
239 change_msg += "No any changes, already configured "
240 diff["msg"] = change_msg
241 diff["change"] = change
242
243 return diff
244
245 def set_host_state(self):
246 """Checking and applying ESXi host configuration one by one,
247 from prepared list of hosts in `self.hosts`.
248 For every host applied:
249 - user input checking done via calling `sanitize_params` method
250 - checks hardware compatibility with user input `check_compatibility`
251 - conf changes created via `make_diff`
252 - changes applied via calling `_update_sriov` method
253 - host state before and after via calling `_check_sriov`
254 """
255 self.sanitize_params()
256 change_list = []
257 changed = False
258 for host in self.hosts:
259 self.results["before"][host.name] = {}
260 self.results["after"][host.name] = {}
261 self.results["changes"][host.name] = {}
262 self.results["before"][host.name] = self._check_sriov(host)
263
264 self.check_compatibility(self.results["before"][host.name], host.name)
265 diff = self.make_diff(self.results["before"][host.name], host.name)
266 self.results["changes"][host.name] = diff
267
268 if not diff["change"]:
269 change_list.append(False)
270 self.results["after"][host.name] = self._check_sriov(host)
271 if (self.results["before"][host.name]["rebootRequired"] != self.results["after"][host.name]["rebootRequired"]):
272 self.results["changes"][host.name]["rebootRequired"] = self.results["after"][host.name]["rebootRequired"]
273 continue
274
275 success = self._update_sriov(host, self.sriov_on, self.num_virt_func)
276 if success:
277 change_list.append(True)
278 else:
279 change_list.append(False)
280
281 self.results["after"][host.name] = self._check_sriov(host)
282 self.results["changes"][host.name].update(
283 {
284 "rebootRequired": self.results["after"][host.name]["rebootRequired"]
285 }
286 )
287
288 if any(change_list):
289 changed = True
290 self.module.exit_json(changed=changed, diff=self.results)
291
292 def _check_sriov(self, host):
293 pnic_info = {}
294 pnic_info["rebootRequired"] = host.summary.rebootRequired
295 for pci_device in host.configManager.pciPassthruSystem.pciPassthruInfo:
296 if pci_device.id == self._getPciId(host):
297 try:
298 if pci_device.sriovCapable:
299 pnic_info["sriovCapable"] = True
300 pnic_info["sriovEnabled"] = pci_device.sriovEnabled
301 pnic_info["sriovActive"] = pci_device.sriovActive
302 pnic_info["numVirtualFunction"] = pci_device.numVirtualFunction
303 pnic_info[
304 "numVirtualFunctionRequested"
305 ] = pci_device.numVirtualFunctionRequested
306 pnic_info[
307 "maxVirtualFunctionSupported"
308 ] = pci_device.maxVirtualFunctionSupported
309 else:
310 pnic_info["sriovCapable"] = False
311 except AttributeError:
312 pnic_info["sriovCapable"] = False
313 break
314 return pnic_info
315
316 def _getPciId(self, host):
317 for pnic in host.config.network.pnic:
318 if pnic.device == self.vmnic:
319 return pnic.pci
320 self.module.fail_json(msg="No nic= %s on host= %s" % (self.vmnic, host.name))
321
322 def _update_sriov(self, host, sriovEnabled, numVirtualFunction):
323 nic_sriov = vim.host.SriovConfig()
324 nic_sriov.id = self._getPciId(host)
325 nic_sriov.sriovEnabled = sriovEnabled
326 nic_sriov.numVirtualFunction = numVirtualFunction
327
328 try:
329 if not self.module.check_mode:
330 host.configManager.pciPassthruSystem.UpdatePassthruConfig([nic_sriov])
331 # looks only for refresh info
332 host.configManager.pciPassthruSystem.Refresh()
333 sleep(2) # TODO: needed method to know that host updated info
334 return True
335 return False
336 except vim.fault.HostConfigFault as config_fault:
337 self.module.fail_json(
338 msg="Failed to configure SR-IOV for host= %s due to : %s"
339 % (host.name, to_native(config_fault.msg))
340 )
341 return False
342
343
344 def main():
345 """Main"""
346 argument_spec = base_argument_spec()
347 argument_spec.update(
348 cluster_name=dict(type="str", required=False),
349 esxi_hostname=dict(type="str", required=False),
350 vmnic=dict(type="str", required=True),
351 num_virt_func=dict(type="int", required=True),
352 sriov_on=dict(type="bool", required=False),
353 )
354
355 module = AnsibleModule(
356 argument_spec=argument_spec,
357 required_one_of=[
358 ["cluster_name", "esxi_hostname"],
359 ],
360 supports_check_mode=True,
361 )
362
363 vmware_host_adapter_config = VmwareAdapterConfigManager(module)
364 vmware_host_adapter_config.set_host_state()
365
366
367 if __name__ == "__main__":
368 main()