Debian Codegraph @

ansible_collections/microsoft/ad/plugins/plugin_utils/_module_with_reboot.py

raw
1 # Copyright (c) 2022 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 """Run module with reboot handler
5
6 This code contains the skeleton needed for action plugins to run a module with
7 an automatic reboot handler. Right now it should only be used in this
8 collection as the interface is not final and count be subject to change.
9 """
10
11 # FOR INTERNAL COLLECTION USE ONLY
12 # The interfaces in this file are meant for use within this collection
13 # and may not remain stable to outside uses. Changes may be made in ANY release, even a bugfix release.
14 # See also: https://github.com/ansible/community/issues/539#issuecomment-780839686
15 # Please open an issue if you have questions about this.
16
17 import typing as t
18
19 from ansible.plugins.action import ActionBase
20 from ansible.utils.display import Display
21 from ansible.utils.vars import merge_hash
22
23 from ._reboot import reboot_host
24
25 display = Display()
26
27
28 class ActionModuleWithReboot(ActionBase):
29 """Action Plugin with Auto Reboot.
30
31 An action plugin that can be used to automatically reboot the host after
32 running a module. By default it checks for the return value reboot_required
33 and reboots the host if it is present.
34
35 There are method that can be overloaded in the sub class to control the
36 behaviour like retries, whether to reboot, etc.
37 """
38
39 def _ad_should_reboot(self, result: t.Dict[str, t.Any]) -> bool:
40 """Check whether a reboot is to be done
41
42 Called after the module is run and is used to check if the reboot
43 should be performed. The default check is to see if reboot_required
44 was returned by the module.
45
46 Args:
47 result: The module result.
48
49 Returns:
50 bool: Whether to do a reboot or not.
51 """
52 return result.get("reboot_required", False)
53
54 def _ad_should_rerun(self, result: t.Dict[str, t.Any]) -> bool:
55 """Check whether to rerun the module.
56
57 Called after the reboot is completed and used to check whether the
58 module should be rerun. The default is to not rerun the module.
59
60 Args:
61 result: The module result.
62
63 Returns:
64 bool: Whether to rerun the module again.
65 """
66 return False
67
68 def _ad_process_result(self, result: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
69 """Called at the end of the run.
70
71 Called at the end of the plugin run for the sub class to edit the
72 result as needed. The default is for the result to be returned as is.
73
74 Args:
75 result: The module result.
76
77 Returns:
78 Dict[str, Any]: The final result to return.
79 """
80 return result
81
82 def _ad_set_rebooted(
83 self,
84 result: t.Dict[str, t.Any],
85 reboot_result: t.Dict[str, t.Any],
86 ) -> None:
87 """Called when a reboot is done.
88
89 Called when the reboot has been performed. The sub class can use this
90 to edit the result or do additional checks as needed. The default is to
91 set the reboot_required return value to False if it is in the module
92 result.
93
94 Args:
95 result: The module result.
96 reboot_result: The result from the reboot
97 """
98 if "reboot_required" in result:
99 result["reboot_required"] = False
100
101 def run(
102 self,
103 tmp: t.Optional[str] = None,
104 task_vars: t.Optional[t.Dict[str, t.Any]] = None,
105 ) -> t.Dict[str, t.Any]:
106 self._supports_check_mode = True
107 self._supports_async = True
108
109 result = super().run(tmp=tmp, task_vars=task_vars)
110 del tmp
111
112 wrap_async = self._task.async_val and not self._connection.has_native_async
113 reboot = self._task.args.get("reboot", False)
114 reboot_timeout = self._task.args.get("reboot_timeout", 600)
115
116 if self._task.async_val > 0 and reboot:
117 return {
118 "failed": True,
119 "msg": "async is not supported for this task when reboot=true",
120 "changed": False,
121 }
122
123 invocation = None
124 while True:
125 module_res = self._execute_module(
126 task_vars=task_vars,
127 wrap_async=wrap_async,
128 )
129 invocation = module_res.pop("invocation", None)
130
131 if reboot and self._ad_should_reboot(module_res):
132 previous_boot_time = module_res.pop("_previous_boot_time", None)
133
134 if self._task.check_mode:
135 reboot_res = {}
136 else:
137 reboot_res = reboot_host(
138 self._task.action,
139 self._connection,
140 reboot_timeout=reboot_timeout,
141 previous_boot_time=previous_boot_time,
142 )
143
144 if reboot_res.get("failed", False):
145 module_res = {
146 "changed": module_res.get("changed", False),
147 "failed": True,
148 "msg": "Failed to reboot after module returned reboot_required, see reboot_result and module_result for more details",
149 "reboot_result": reboot_res,
150 "module_result": module_res,
151 }
152 break
153
154 # Regardless of the module result this needs to be True as a
155 # reboot happened.
156 module_res["changed"] = True
157 self._ad_set_rebooted(module_res, reboot_res)
158
159 if self._ad_should_rerun(module_res) and not self._task.check_mode:
160 display.vv(
161 "Module result has indicated it should rerun after a reboot has occurred, rerunning"
162 )
163 continue
164
165 break
166
167 # Make sure the invocation details from the module are still present.
168 if invocation is not None:
169 module_res["invocation"] = invocation
170
171 result = merge_hash(result, module_res)
172
173 return self._ad_process_result(result)
174
175
176 class DomainPromotionWithReboot(ActionModuleWithReboot):
177 """Domain Promotion Action Plugin with Auto Reboot.
178
179 An action plugin that runs a task that can promote the target Windows host
180 to a domain controller. It implements the common reboot handling for that
181 particular task.
182 """
183
184 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
185 super().__init__(*args, **kwargs)
186 self._ran_once = False
187
188 def _ad_should_rerun(self, result: t.Dict[str, t.Any]) -> bool:
189 ran_once = self._ran_once
190 self._ran_once = True
191
192 if ran_once or not result.get("_do_action_reboot", False):
193 return False
194
195 if self._task.check_mode:
196 # Assume that on a rerun it will not have failed and that it
197 # ran successful.
198 result["failed"] = False
199 result.pop("msg", None)
200 return False
201
202 else:
203 return True
204
205 def _ad_process_result(self, result: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
206 result.pop("_do_action_reboot", None)
207
208 return result