Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Christian Kotte <[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_host_hyperthreading
15 short_description: Enables/Disables Hyperthreading optimization for an ESXi host system
16 description:
17 - This module can be used to enable or disable Hyperthreading optimization for ESXi host systems in given vCenter infrastructure.
18 - It also checks if Hyperthreading is activated/deactivated and if the host needs to be restarted.
19 - The module informs the user if Hyperthreading is enabled but inactive because the processor is vulnerable to L1 Terminal Fault (L1TF).
20 author:
21 - Christian Kotte (@ckotte)
22 options:
23 state:
24 description:
25 - Enable or disable Hyperthreading.
26 - You need to reboot the ESXi host if you change the configuration.
27 - Make sure that Hyperthreading is enabled in the BIOS. Otherwise, it will be enabled, but never activated.
28 type: str
29 choices: [ enabled, disabled ]
30 default: 'enabled'
31 esxi_hostname:
32 description:
33 - Name of the host system to work with.
34 - This parameter is required if O(cluster_name) is not specified.
35 type: str
36 cluster_name:
37 description:
38 - Name of the cluster from which all host systems will be used.
39 - This parameter is required if O(esxi_hostname) is not specified.
40 type: str
41 extends_documentation_fragment:
42 - vmware.vmware.base_options
43
44 '''
45
46 EXAMPLES = r'''
47 - name: Enable Hyperthreading for an host system
48 community.vmware.vmware_host_hyperthreading:
49 hostname: '{{ vcenter_hostname }}'
50 username: '{{ vcenter_username }}'
51 password: '{{ vcenter_password }}'
52 esxi_hostname: '{{ esxi_hostname }}'
53 state: enabled
54 delegate_to: localhost
55
56 - name: Disable Hyperthreading for an host system
57 community.vmware.vmware_host_hyperthreading:
58 hostname: '{{ vcenter_hostname }}'
59 username: '{{ vcenter_username }}'
60 password: '{{ vcenter_password }}'
61 esxi_hostname: '{{ esxi_hostname }}'
62 state: disabled
63 delegate_to: localhost
64
65 - name: Disable Hyperthreading for all host systems from cluster
66 community.vmware.vmware_host_hyperthreading:
67 hostname: '{{ vcenter_hostname }}'
68 username: '{{ vcenter_username }}'
69 password: '{{ vcenter_password }}'
70 cluster_name: '{{ cluster_name }}'
71 state: disabled
72 delegate_to: localhost
73 '''
74
75 RETURN = r'''
76 results:
77 description: metadata about host system's Hyperthreading configuration
78 returned: always
79 type: dict
80 sample: {
81 "esxi01": {
82 "msg": "Hyperthreading is already enabled and active for host 'esxi01'",
83 "state_current": "active",
84 "state": "enabled",
85 },
86 }
87 '''
88
89 try:
90 from pyVmomi import vim, vmodl
91 except ImportError:
92 pass
93
94 from ansible.module_utils.basic import AnsibleModule
95 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
96 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
97 from ansible.module_utils.common.text.converters import to_native
98
99
100 class VmwareHostHyperthreading(PyVmomi):
101 """Manage Hyperthreading for an ESXi host system"""
102
103 def __init__(self, module):
104 super(VmwareHostHyperthreading, self).__init__(module)
105 cluster_name = self.params.get('cluster_name')
106 esxi_host_name = self.params.get('esxi_hostname')
107 self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
108 if not self.hosts:
109 self.module.fail_json(msg="Failed to find host system.")
110
111 def ensure(self):
112 """Manage Hyperthreading for an ESXi host system"""
113 results = dict(changed=False, result=dict())
114 desired_state = self.params.get('state')
115 host_change_list = []
116 for host in self.hosts:
117 changed = False
118 results['result'][host.name] = dict(msg='')
119
120 hyperthreading_info = host.config.hyperThread
121
122 results['result'][host.name]['state'] = desired_state
123 if desired_state == 'enabled':
124 # Don't do anything if Hyperthreading is already enabled
125 if hyperthreading_info.config:
126 if hyperthreading_info.active:
127 results['result'][host.name]['changed'] = False
128 results['result'][host.name]['state_current'] = "active"
129 results['result'][host.name]['msg'] = "Hyperthreading is enabled and active"
130 if not hyperthreading_info.active:
131 # L1 Terminal Fault (L1TF)/Foreshadow mitigation workaround (https://kb.vmware.com/s/article/55806)
132 option_manager = host.configManager.advancedOption
133 try:
134 mitigation = option_manager.QueryOptions('VMkernel.Boot.hyperthreadingMitigation')
135 except vim.fault.InvalidName:
136 mitigation = None
137 if mitigation and mitigation[0].value:
138 results['result'][host.name]['changed'] = False
139 results['result'][host.name]['state_current'] = "enabled"
140 results['result'][host.name]['msg'] = ("Hyperthreading is enabled, but not active because the"
141 " processor is vulnerable to L1 Terminal Fault (L1TF).")
142 else:
143 changed = results['result'][host.name]['changed'] = True
144 results['result'][host.name]['state_current'] = "enabled"
145 results['result'][host.name]['msg'] = ("Hyperthreading is enabled, but not active."
146 " A reboot is required!")
147 # Enable Hyperthreading
148 else:
149 # Check if Hyperthreading is available
150 if hyperthreading_info.available:
151 if not self.module.check_mode:
152 try:
153 host.configManager.cpuScheduler.EnableHyperThreading()
154 changed = results['result'][host.name]['changed'] = True
155 results['result'][host.name]['state_previous'] = "disabled"
156 results['result'][host.name]['state_current'] = "enabled"
157 results['result'][host.name]['msg'] = (
158 "Hyperthreading enabled for host. Reboot the host to activate it."
159 )
160 except vmodl.fault.NotSupported as not_supported:
161 # This should never happen since Hyperthreading is available
162 self.module.fail_json(
163 msg="Failed to enable Hyperthreading for host '%s' : %s" %
164 (host.name, to_native(not_supported.msg))
165 )
166 except (vmodl.RuntimeFault, vmodl.MethodFault) as runtime_fault:
167 self.module.fail_json(
168 msg="Failed to enable Hyperthreading for host '%s' due to : %s" %
169 (host.name, to_native(runtime_fault.msg))
170 )
171 else:
172 changed = results['result'][host.name]['changed'] = True
173 results['result'][host.name]['state_previous'] = "disabled"
174 results['result'][host.name]['state_current'] = "enabled"
175 results['result'][host.name]['msg'] = "Hyperthreading will be enabled"
176 else:
177 self.module.fail_json(msg="Hyperthreading optimization is not available for host '%s'" % host.name)
178 elif desired_state == 'disabled':
179 # Don't do anything if Hyperthreading is already disabled
180 if not hyperthreading_info.config:
181 if not hyperthreading_info.active:
182 results['result'][host.name]['changed'] = False
183 results['result'][host.name]['state_current'] = "inactive"
184 results['result'][host.name]['msg'] = "Hyperthreading is disabled and inactive"
185 if hyperthreading_info.active:
186 changed = results['result'][host.name]['changed'] = True
187 results['result'][host.name]['state_current'] = "disabled"
188 results['result'][host.name]['msg'] = ("Hyperthreading is already disabled"
189 " but still active. A reboot is required!")
190 # Disable Hyperthreading
191 else:
192 # Check if Hyperthreading is available
193 if hyperthreading_info.available:
194 if not self.module.check_mode:
195 try:
196 host.configManager.cpuScheduler.DisableHyperThreading()
197 changed = results['result'][host.name]['changed'] = True
198 results['result'][host.name]['state_previous'] = "enabled"
199 results['result'][host.name]['state_current'] = "disabled"
200 results['result'][host.name]['msg'] = (
201 "Hyperthreading disabled. Reboot the host to deactivate it."
202 )
203 except vmodl.fault.NotSupported as not_supported:
204 # This should never happen since Hyperthreading is available
205 self.module.fail_json(
206 msg="Failed to disable Hyperthreading for host '%s' : %s" %
207 (host.name, to_native(not_supported.msg))
208 )
209 except (vmodl.RuntimeFault, vmodl.MethodFault) as runtime_fault:
210 self.module.fail_json(
211 msg="Failed to disable Hyperthreading for host '%s' due to : %s" %
212 (host.name, to_native(runtime_fault.msg))
213 )
214 else:
215 changed = results['result'][host.name]['changed'] = True
216 results['result'][host.name]['state_previous'] = "enabled"
217 results['result'][host.name]['state_current'] = "disabled"
218 results['result'][host.name]['msg'] = "Hyperthreading will be disabled"
219 else:
220 self.module.fail_json(msg="Hyperthreading optimization is not available for host '%s'" % host.name)
221
222 host_change_list.append(changed)
223
224 if any(host_change_list):
225 results['changed'] = True
226 self.module.exit_json(**results)
227
228
229 def main():
230 """Main"""
231 argument_spec = base_argument_spec()
232 argument_spec.update(
233 state=dict(default='enabled', choices=['enabled', 'disabled']),
234 esxi_hostname=dict(type='str', required=False),
235 cluster_name=dict(type='str', required=False),
236 )
237
238 module = AnsibleModule(argument_spec=argument_spec,
239 required_one_of=[
240 ['cluster_name', 'esxi_hostname'],
241 ],
242 supports_check_mode=True
243 )
244
245 hyperthreading = VmwareHostHyperthreading(module)
246 hyperthreading.ensure()
247
248
249 if __name__ == '__main__':
250 main()