Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2015, Joseph Callen <jcallen () csc.com>
5 # Copyright: (c) 2018, 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
11 __metaclass__ = type
12
13
14 DOCUMENTATION = r'''
15 ---
16 module: vmware_cluster_ha
17 deprecated:
18 removed_in: 7.0.0
19 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
20 alternative: Use M(vmware.vmware.cluster_ha) instead.
21 short_description: Manage High Availability (HA) on VMware vSphere clusters
22 description:
23 - Manages HA configuration on VMware vSphere clusters.
24 author:
25 - Joseph Callen (@jcpowermac)
26 - Abhijeet Kasurde (@Akasurde)
27 options:
28 cluster_name:
29 description:
30 - The name of the cluster to be managed.
31 type: str
32 required: true
33 datacenter:
34 description:
35 - The name of the datacenter.
36 type: str
37 required: true
38 aliases: [ datacenter_name ]
39 enable:
40 description:
41 - Whether to enable HA.
42 type: bool
43 default: true
44 ha_host_monitoring:
45 description:
46 - Whether HA restarts virtual machines after a host fails.
47 - If set to V(enabled), HA restarts virtual machines after a host fails.
48 - If set to V(disabled), HA does not restart virtual machines after a host fails.
49 - If O(enable=false), this value is ignored.
50 type: str
51 choices: [ 'enabled', 'disabled' ]
52 default: 'enabled'
53 ha_vm_monitoring:
54 description:
55 - State of virtual machine health monitoring service.
56 - If set to V(vmAndAppMonitoring), HA response to both virtual machine and application heartbeat failure.
57 - If set to V(vmMonitoringDisabled), virtual machine health monitoring is disabled.
58 - If set to V(vmMonitoringOnly), HA response to virtual machine heartbeat failure.
59 - If O(enable=false), then this value is ignored.
60 type: str
61 choices: ['vmAndAppMonitoring', 'vmMonitoringOnly', 'vmMonitoringDisabled']
62 default: 'vmMonitoringDisabled'
63 host_isolation_response:
64 description:
65 - Indicates whether or VMs should be powered off if a host determines that it is isolated from the rest of the compute resource.
66 - If set to V(none), do not power off VMs in the event of a host network isolation.
67 - If set to V(powerOff), power off VMs in the event of a host network isolation.
68 - If set to V(shutdown), shut down VMs guest operating system in the event of a host network isolation.
69 type: str
70 choices: ['none', 'powerOff', 'shutdown']
71 default: 'none'
72 slot_based_admission_control:
73 description:
74 - Configure slot based admission control policy.
75 - O(slot_based_admission_control), O(reservation_based_admission_control) and O(failover_host_admission_control) are mutually exclusive.
76 suboptions:
77 failover_level:
78 description:
79 - Number of host failures that should be tolerated.
80 type: int
81 required: true
82 type: dict
83 reservation_based_admission_control:
84 description:
85 - Configure reservation based admission control policy.
86 - O(slot_based_admission_control), O(reservation_based_admission_control) and O(failover_host_admission_control) are mutually exclusive.
87 suboptions:
88 failover_level:
89 description:
90 - Number of host failures that should be tolerated.
91 type: int
92 required: true
93 auto_compute_percentages:
94 description:
95 - By default, O(reservation_based_admission_control.failover_level) is used to calculate
96 O(reservation_based_admission_control.cpu_failover_resources_percent)
97 and O(reservation_based_admission_control.memory_failover_resources_percent).
98 If a user wants to override the percentage values, he has to set this field to false.
99 type: bool
100 default: true
101 cpu_failover_resources_percent:
102 description:
103 - Percentage of CPU resources in the cluster to reserve for failover.
104 Ignored if O(reservation_based_admission_control.auto_compute_percentages) is not set to false.
105 type: int
106 default: 50
107 memory_failover_resources_percent:
108 description:
109 - Percentage of memory resources in the cluster to reserve for failover.
110 Ignored if O(reservation_based_admission_control.auto_compute_percentages) is not set to false.
111 type: int
112 default: 50
113 type: dict
114 failover_host_admission_control:
115 description:
116 - Configure dedicated failover hosts.
117 - O(slot_based_admission_control), O(reservation_based_admission_control) and O(failover_host_admission_control) are mutually exclusive.
118 suboptions:
119 failover_hosts:
120 description:
121 - List of dedicated failover hosts.
122 type: list
123 required: true
124 elements: str
125 type: dict
126 ha_vm_failure_interval:
127 description:
128 - The number of seconds after which virtual machine is declared as failed
129 if no heartbeat has been received.
130 - This setting is only valid if O(ha_vm_monitoring=vmAndAppMonitoring) or O(ha_vm_monitoring=vmMonitoringOnly).
131 - Unit is seconds.
132 type: int
133 default: 30
134 ha_vm_min_up_time:
135 description:
136 - The number of seconds for the virtual machine's heartbeats to stabilize after
137 the virtual machine has been powered on.
138 - Valid only when O(ha_vm_monitoring=vmAndAppMonitoring) or O(ha_vm_monitoring=vmMonitoringOnly).
139 - Unit is seconds.
140 type: int
141 default: 120
142 ha_vm_max_failures:
143 description:
144 - Maximum number of failures and automated resets allowed during the time
145 that O(ha_vm_max_failure_window) specifies.
146 - Valid only when O(ha_vm_monitoring=vmAndAppMonitoring) or O(ha_vm_monitoring=vmMonitoringOnly).
147 type: int
148 default: 3
149 ha_vm_max_failure_window:
150 description:
151 - The number of seconds for the window during which up to O(ha_vm_max_failures) resets
152 can occur before automated responses stop.
153 - Valid only when O(ha_vm_monitoring=vmAndAppMonitoring) or O(ha_vm_monitoring=vmMonitoringOnly).
154 - Unit is seconds.
155 - Default specifies no failure window.
156 type: int
157 default: -1
158 ha_restart_priority:
159 description:
160 - Priority HA gives to a virtual machine if sufficient capacity is not available
161 to power on all failed virtual machines.
162 - Valid only when O(ha_vm_monitoring=vmAndAppMonitoring) or O(ha_vm_monitoring=vmMonitoringOnly).
163 - If set to V(disabled), then HA is disabled for this virtual machine.
164 - If set to V(high), then virtual machine with this priority have a higher chance of powering on after a failure,
165 when there is insufficient capacity on hosts to meet all virtual machine needs.
166 - If set to V(medium), then virtual machine with this priority have an intermediate chance of powering on after a failure,
167 when there is insufficient capacity on hosts to meet all virtual machine needs.
168 - If set to V(low), then virtual machine with this priority have a lower chance of powering on after a failure,
169 when there is insufficient capacity on hosts to meet all virtual machine needs.
170 type: str
171 default: 'medium'
172 choices: [ 'disabled', 'high', 'low', 'medium' ]
173 advanced_settings:
174 description:
175 - A dictionary of advanced HA settings.
176 default: {}
177 type: dict
178 apd_response:
179 description:
180 - VM storage protection setting for storage failures categorized as All Paths Down (APD).
181 type: str
182 default: 'warning'
183 choices: [ 'disabled', 'warning', 'restartConservative', 'restartAggressive' ]
184 apd_delay:
185 description:
186 - The response recovery delay time in sec for storage failures categorized as All Paths Down (APD).
187 - Only set if O(apd_response=restartConservative) or O(apd_response=restartAggressive).
188 type: int
189 default: 180
190 apd_reaction:
191 description:
192 - VM response recovery reaction for storage failures categorized as All Paths Down (APD).
193 - Only set if O(apd_response=restartConservative) or O(apd_response=restartAggressive).
194 type: str
195 default: 'reset'
196 choices: [ 'reset', 'none' ]
197 pdl_response:
198 description:
199 - VM storage protection setting for storage failures categorized as Permenant Device Loss (PDL).
200 type: str
201 default: 'warning'
202 choices: [ 'disabled', 'warning', 'restartAggressive' ]
203 extends_documentation_fragment:
204 - vmware.vmware.base_options
205
206 '''
207
208 EXAMPLES = r'''
209 - name: Enable HA without admission control
210 community.vmware.vmware_cluster_ha:
211 hostname: '{{ vcenter_hostname }}'
212 username: '{{ vcenter_username }}'
213 password: '{{ vcenter_password }}'
214 datacenter_name: datacenter
215 cluster_name: cluster
216 enable: true
217 delegate_to: localhost
218
219 - name: Enable HA and VM monitoring without admission control
220 community.vmware.vmware_cluster_ha:
221 hostname: "{{ vcenter_hostname }}"
222 username: "{{ vcenter_username }}"
223 password: "{{ vcenter_password }}"
224 datacenter_name: DC0
225 cluster_name: "{{ cluster_name }}"
226 enable: true
227 ha_vm_monitoring: vmMonitoringOnly
228 delegate_to: localhost
229
230 - name: Enable HA with admission control reserving 50% of resources for HA
231 community.vmware.vmware_cluster_ha:
232 hostname: '{{ vcenter_hostname }}'
233 username: '{{ vcenter_username }}'
234 password: '{{ vcenter_password }}'
235 datacenter_name: datacenter
236 cluster_name: cluster
237 enable: true
238 reservation_based_admission_control:
239 auto_compute_percentages: false
240 failover_level: 1
241 cpu_failover_resources_percent: 50
242 memory_failover_resources_percent: 50
243 delegate_to: localhost
244 '''
245
246 RETURN = r'''#
247 '''
248
249 try:
250 from pyVmomi import vim, vmodl
251 except ImportError:
252 pass
253
254 from ansible.module_utils.basic import AnsibleModule
255 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
256 PyVmomi,
257 TaskError,
258 find_datacenter_by_name,
259 wait_for_task,
260 option_diff,
261 )
262 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
263 from ansible.module_utils.common.text.converters import to_native
264
265
266 class VMwareCluster(PyVmomi):
267 def __init__(self, module):
268 super(VMwareCluster, self).__init__(module)
269 self.cluster_name = module.params['cluster_name']
270 self.datacenter_name = module.params['datacenter']
271 self.enable_ha = module.params['enable']
272 self.datacenter = None
273 self.cluster = None
274 self.host_isolation_response = getattr(vim.cluster.DasVmSettings.IsolationResponse, self.params.get('host_isolation_response'))
275
276 if self.enable_ha and (
277 self.params.get("slot_based_admission_control")
278 or self.params.get("reservation_based_admission_control")
279 or self.params.get("failover_host_admission_control")
280 ):
281 self.ha_admission_control = True
282 else:
283 self.ha_admission_control = False
284
285 self.datacenter = find_datacenter_by_name(self.content, self.datacenter_name)
286 if self.datacenter is None:
287 self.module.fail_json(msg="Datacenter %s does not exist." % self.datacenter_name)
288
289 self.cluster = self.find_cluster_by_name(cluster_name=self.cluster_name, datacenter_name=self.datacenter)
290 if self.cluster is None:
291 self.module.fail_json(msg="Cluster %s does not exist." % self.cluster_name)
292
293 self.advanced_settings = self.params.get('advanced_settings')
294 if self.advanced_settings:
295 self.changed_advanced_settings = option_diff(self.advanced_settings, self.cluster.configurationEx.dasConfig.option, False)
296 else:
297 self.changed_advanced_settings = None
298
299 def get_failover_hosts(self):
300 """
301 Get failover hosts for failover_host_admission_control policy
302 Returns: List of ESXi hosts sorted by name
303
304 """
305 policy = self.params.get('failover_host_admission_control')
306 hosts = []
307 all_hosts = dict((h.name, h) for h in self.get_all_hosts_by_cluster(self.cluster_name))
308 for host in policy.get('failover_hosts'):
309 if host in all_hosts:
310 hosts.append(all_hosts.get(host))
311 else:
312 self.module.fail_json(msg="Host %s is not a member of cluster %s." % (host, self.cluster_name))
313 hosts.sort(key=lambda h: h.name)
314 return hosts
315
316 def check_ha_config_diff(self):
317 """
318 Check HA configuration diff
319 Returns: True if there is diff, else False
320
321 """
322 das_config = self.cluster.configurationEx.dasConfig
323 if das_config.enabled != self.enable_ha:
324 return True
325
326 if self.enable_ha and (
327 das_config.vmMonitoring != self.params.get("ha_vm_monitoring")
328 or das_config.hostMonitoring != self.params.get("ha_host_monitoring")
329 or das_config.admissionControlEnabled != self.ha_admission_control
330 or das_config.defaultVmSettings.restartPriority
331 != self.params.get("ha_restart_priority")
332 or das_config.defaultVmSettings.isolationResponse
333 != self.host_isolation_response
334 or das_config.defaultVmSettings.vmToolsMonitoringSettings.vmMonitoring
335 != self.params.get("ha_vm_monitoring")
336 or das_config.defaultVmSettings.vmToolsMonitoringSettings.failureInterval
337 != self.params.get("ha_vm_failure_interval")
338 or das_config.defaultVmSettings.vmToolsMonitoringSettings.minUpTime
339 != self.params.get("ha_vm_min_up_time")
340 or das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailures
341 != self.params.get("ha_vm_max_failures")
342 or das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailureWindow
343 != self.params.get("ha_vm_max_failure_window")
344 or das_config.defaultVmSettings.vmComponentProtectionSettings.vmStorageProtectionForAPD
345 != self.params.get("apd_response")
346 or das_config.defaultVmSettings.vmComponentProtectionSettings.vmStorageProtectionForPDL
347 != self.params.get("pdl_response")
348 ):
349 return True
350
351 if self.ha_admission_control:
352 if self.params.get('slot_based_admission_control'):
353 policy = self.params.get('slot_based_admission_control')
354 if not isinstance(das_config.admissionControlPolicy, vim.cluster.FailoverLevelAdmissionControlPolicy) or \
355 das_config.admissionControlPolicy.failoverLevel != policy.get('failover_level'):
356 return True
357 elif self.params.get('reservation_based_admission_control'):
358 policy = self.params.get('reservation_based_admission_control')
359 auto_compute_percentages = policy.get('auto_compute_percentages')
360 if not isinstance(das_config.admissionControlPolicy, vim.cluster.FailoverResourcesAdmissionControlPolicy) or \
361 das_config.admissionControlPolicy.autoComputePercentages != auto_compute_percentages or \
362 das_config.admissionControlPolicy.failoverLevel != policy.get('failover_level'):
363 return True
364 if not auto_compute_percentages:
365 if das_config.admissionControlPolicy.cpuFailoverResourcesPercent != policy.get('cpu_failover_resources_percent') or \
366 das_config.admissionControlPolicy.memoryFailoverResourcesPercent != policy.get('memory_failover_resources_percent'):
367 return True
368 elif self.params.get('failover_host_admission_control'):
369 policy = self.params.get('failover_host_admission_control')
370 if not isinstance(das_config.admissionControlPolicy, vim.cluster.FailoverHostAdmissionControlPolicy):
371 return True
372 das_config.admissionControlPolicy.failoverHosts.sort(key=lambda h: h.name)
373 if das_config.admissionControlPolicy.failoverHosts != self.get_failover_hosts():
374 return True
375
376 if self.params.get('apd_response') != 'disabled' and self.params.get('apd_response') != 'warning':
377 if das_config.defaultVmSettings.vmComponentProtectionSettings.vmTerminateDelayForAPDSec != self.params.get('apd_delay'):
378 return True
379 if das_config.defaultVmSettings.vmComponentProtectionSettings.vmReactionOnAPDCleared != self.params.get('apd_reaction'):
380 return True
381
382 if self.changed_advanced_settings:
383 return True
384
385 return False
386
387 def configure_ha(self):
388 """
389 Manage HA Configuration
390
391 """
392 changed, result = False, None
393
394 if self.check_ha_config_diff():
395 if not self.module.check_mode:
396 cluster_config_spec = vim.cluster.ConfigSpecEx()
397 cluster_config_spec.dasConfig = vim.cluster.DasConfigInfo()
398 cluster_config_spec.dasConfig.enabled = self.enable_ha
399
400 if self.enable_ha:
401 vm_tool_spec = vim.cluster.VmToolsMonitoringSettings()
402 vm_tool_spec.enabled = True
403 vm_tool_spec.vmMonitoring = self.params.get('ha_vm_monitoring')
404 vm_tool_spec.failureInterval = self.params.get('ha_vm_failure_interval')
405 vm_tool_spec.minUpTime = self.params.get('ha_vm_min_up_time')
406 vm_tool_spec.maxFailures = self.params.get('ha_vm_max_failures')
407 vm_tool_spec.maxFailureWindow = self.params.get('ha_vm_max_failure_window')
408
409 das_vm_config = vim.cluster.DasVmSettings()
410 das_vm_config.restartPriority = self.params.get('ha_restart_priority')
411 das_vm_config.isolationResponse = self.host_isolation_response
412 das_vm_config.vmToolsMonitoringSettings = vm_tool_spec
413
414 das_vm_config.vmComponentProtectionSettings = vim.cluster.VmComponentProtectionSettings()
415 das_vm_config.vmComponentProtectionSettings.vmStorageProtectionForAPD = self.params.get('apd_response')
416 if self.params.get('apd_response') != 'disabled' and self.params.get('apd_response') != 'warning':
417 das_vm_config.vmComponentProtectionSettings.vmTerminateDelayForAPDSec = self.params.get('apd_delay')
418 das_vm_config.vmComponentProtectionSettings.vmReactionOnAPDCleared = self.params.get('apd_reaction')
419 das_vm_config.vmComponentProtectionSettings.vmStorageProtectionForPDL = self.params.get('pdl_response')
420 if (self.params['apd_response'] != "disabled" or self.params['pdl_response'] != "disabled"):
421 cluster_config_spec.dasConfig.vmComponentProtecting = 'enabled'
422 else:
423 cluster_config_spec.dasConfig.vmComponentProtecting = 'disabled'
424
425 cluster_config_spec.dasConfig.defaultVmSettings = das_vm_config
426
427 cluster_config_spec.dasConfig.admissionControlEnabled = self.ha_admission_control
428
429 if self.ha_admission_control:
430 if self.params.get('slot_based_admission_control'):
431 cluster_config_spec.dasConfig.admissionControlPolicy = vim.cluster.FailoverLevelAdmissionControlPolicy()
432 policy = self.params.get('slot_based_admission_control')
433 cluster_config_spec.dasConfig.admissionControlPolicy.failoverLevel = policy.get('failover_level')
434 elif self.params.get('reservation_based_admission_control'):
435 cluster_config_spec.dasConfig.admissionControlPolicy = vim.cluster.FailoverResourcesAdmissionControlPolicy()
436 policy = self.params.get('reservation_based_admission_control')
437 auto_compute_percentages = policy.get('auto_compute_percentages')
438 cluster_config_spec.dasConfig.admissionControlPolicy.autoComputePercentages = auto_compute_percentages
439 cluster_config_spec.dasConfig.admissionControlPolicy.failoverLevel = policy.get('failover_level')
440 if not auto_compute_percentages:
441 cluster_config_spec.dasConfig.admissionControlPolicy.cpuFailoverResourcesPercent = \
442 policy.get('cpu_failover_resources_percent')
443 cluster_config_spec.dasConfig.admissionControlPolicy.memoryFailoverResourcesPercent = \
444 policy.get('memory_failover_resources_percent')
445 elif self.params.get('failover_host_admission_control'):
446 cluster_config_spec.dasConfig.admissionControlPolicy = vim.cluster.FailoverHostAdmissionControlPolicy()
447 policy = self.params.get('failover_host_admission_control')
448 cluster_config_spec.dasConfig.admissionControlPolicy.failoverHosts = self.get_failover_hosts()
449
450 cluster_config_spec.dasConfig.hostMonitoring = self.params.get('ha_host_monitoring')
451 cluster_config_spec.dasConfig.vmMonitoring = self.params.get('ha_vm_monitoring')
452
453 if self.changed_advanced_settings:
454 cluster_config_spec.dasConfig.option = self.changed_advanced_settings
455
456 try:
457 task = self.cluster.ReconfigureComputeResource_Task(cluster_config_spec, True)
458 changed, result = wait_for_task(task)
459 except vmodl.RuntimeFault as runtime_fault:
460 self.module.fail_json(msg=to_native(runtime_fault.msg))
461 except vmodl.MethodFault as method_fault:
462 self.module.fail_json(msg=to_native(method_fault.msg))
463 except TaskError as task_e:
464 self.module.fail_json(msg=to_native(task_e))
465 except Exception as generic_exc:
466 self.module.fail_json(msg="Failed to update cluster"
467 " due to generic exception %s" % to_native(generic_exc))
468 else:
469 changed = True
470
471 self.module.exit_json(changed=changed, result=result)
472
473
474 def main():
475 argument_spec = base_argument_spec()
476 argument_spec.update(dict(
477 cluster_name=dict(type='str', required=True),
478 datacenter=dict(type='str', required=True, aliases=['datacenter_name']),
479 # HA
480 enable=dict(type='bool', default=True),
481 ha_host_monitoring=dict(type='str',
482 default='enabled',
483 choices=['enabled', 'disabled']),
484 host_isolation_response=dict(type='str',
485 default='none',
486 choices=['none', 'powerOff', 'shutdown']),
487 advanced_settings=dict(type='dict', default=dict(), required=False),
488 # HA VM Monitoring related parameters
489 ha_vm_monitoring=dict(type='str',
490 choices=['vmAndAppMonitoring', 'vmMonitoringOnly', 'vmMonitoringDisabled'],
491 default='vmMonitoringDisabled'),
492 ha_vm_failure_interval=dict(type='int', default=30),
493 ha_vm_min_up_time=dict(type='int', default=120),
494 ha_vm_max_failures=dict(type='int', default=3),
495 ha_vm_max_failure_window=dict(type='int', default=-1),
496
497 ha_restart_priority=dict(type='str',
498 choices=['high', 'low', 'medium', 'disabled'],
499 default='medium'),
500 # HA Admission Control related parameters
501 slot_based_admission_control=dict(type='dict', options=dict(
502 failover_level=dict(type='int', required=True),
503 )),
504 reservation_based_admission_control=dict(type='dict', options=dict(
505 auto_compute_percentages=dict(type='bool', default=True),
506 failover_level=dict(type='int', required=True),
507 cpu_failover_resources_percent=dict(type='int', default=50),
508 memory_failover_resources_percent=dict(type='int', default=50),
509 )),
510 failover_host_admission_control=dict(type='dict', options=dict(
511 failover_hosts=dict(type='list', elements='str', required=True),
512 )),
513 apd_response=dict(type='str',
514 choices=['disabled', 'warning', 'restartConservative', 'restartAggressive'],
515 default='warning'),
516 apd_delay=dict(type='int', default=180),
517 apd_reaction=dict(type='str',
518 choices=['reset', 'none'],
519 default='reset'),
520 pdl_response=dict(type='str',
521 choices=['disabled', 'warning', 'restartAggressive'],
522 default='warning'),
523 ))
524
525 module = AnsibleModule(
526 argument_spec=argument_spec,
527 supports_check_mode=True,
528 mutually_exclusive=[
529 ['slot_based_admission_control', 'reservation_based_admission_control', 'failover_host_admission_control']
530 ]
531 )
532
533 vmware_cluster_ha = VMwareCluster(module)
534 vmware_cluster_ha.configure_ha()
535
536
537 if __name__ == '__main__':
538 main()