Debian Codegraph @

lib/ansible/plugins/action/reboot.py

raw
1 # Copyright: (c) 2016-2018, Matt Davis <[email protected]>
2 # Copyright: (c) 2018, Sam Doran <[email protected]>
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 import secrets
8 import time
9
10 from datetime import datetime, timedelta, timezone
11
12 from ansible.errors import AnsibleError, AnsibleConnectionFailure
13 from ansible.module_utils.common.text.converters import to_native, to_text
14 from ansible.module_utils.common.validation import check_type_list, check_type_str
15 from ansible.plugins.action import ActionBase
16 from ansible.utils.display import Display
17
18 display = Display()
19
20
21 class TimedOutException(Exception):
22 pass
23
24
25 class ActionModule(ActionBase):
26 TRANSFERS_FILES = False
27 _VALID_ARGS = frozenset((
28 'boot_time_command',
29 'connect_timeout',
30 'msg',
31 'post_reboot_delay',
32 'pre_reboot_delay',
33 'reboot_command',
34 'reboot_timeout',
35 'search_paths',
36 'test_command',
37 ))
38
39 DEFAULT_REBOOT_TIMEOUT = 600
40 DEFAULT_CONNECT_TIMEOUT = None
41 DEFAULT_PRE_REBOOT_DELAY = 0
42 DEFAULT_POST_REBOOT_DELAY = 0
43 DEFAULT_TEST_COMMAND = 'whoami'
44 DEFAULT_BOOT_TIME_COMMAND = 'cat /proc/sys/kernel/random/boot_id'
45 DEFAULT_REBOOT_MESSAGE = 'Reboot initiated by Ansible'
46 DEFAULT_SHUTDOWN_COMMAND = 'shutdown'
47 DEFAULT_SHUTDOWN_COMMAND_ARGS = '-r {delay_min} "{message}"'
48 DEFAULT_SUDOABLE = True
49
50 DEPRECATED_ARGS = {} # type: dict[str, str]
51
52 BOOT_TIME_COMMANDS = {
53 'freebsd': '/sbin/sysctl kern.boottime',
54 'openbsd': '/sbin/sysctl kern.boottime',
55 'macosx': 'who -b',
56 'solaris': 'who -b',
57 'sunos': 'who -b',
58 'vmkernel': 'grep booted /var/log/vmksummary.log | tail -n 1',
59 'aix': 'who -b',
60 }
61
62 SHUTDOWN_COMMANDS = {
63 'alpine': 'reboot',
64 'vmkernel': 'reboot',
65 }
66
67 SHUTDOWN_COMMAND_ARGS = {
68 'alpine': '',
69 'void': '-r +{delay_min} "{message}"',
70 'freebsd': '-r +{delay_sec}s "{message}"',
71 'linux': DEFAULT_SHUTDOWN_COMMAND_ARGS,
72 'macosx': '-r +{delay_min} "{message}"',
73 'openbsd': '-r +{delay_min} "{message}"',
74 'solaris': '-y -g {delay_sec} -i 6 "{message}"',
75 'sunos': '-y -g {delay_sec} -i 6 "{message}"',
76 'vmkernel': '-d {delay_sec}',
77 'aix': '-Fr',
78 }
79
80 TEST_COMMANDS = {
81 'solaris': 'who',
82 'vmkernel': 'who',
83 }
84
85 def __init__(self, *args, **kwargs):
86 super(ActionModule, self).__init__(*args, **kwargs)
87
88 @property
89 def pre_reboot_delay(self):
90 return self._check_delay('pre_reboot_delay', self.DEFAULT_PRE_REBOOT_DELAY)
91
92 @property
93 def post_reboot_delay(self):
94 return self._check_delay('post_reboot_delay', self.DEFAULT_POST_REBOOT_DELAY)
95
96 def _check_delay(self, key, default):
97 """Ensure that the value is positive or zero"""
98 value = int(self._task.args.get(key, self._task.args.get(key + '_sec', default)))
99 if value < 0:
100 value = 0
101 return value
102
103 def _get_value_from_facts(self, variable_name, distribution, default_value):
104 """Get dist+version specific args first, then distribution, then family, lastly use default"""
105 attr = getattr(self, variable_name)
106 value = attr.get(
107 distribution['name'] + distribution['version'],
108 attr.get(
109 distribution['name'],
110 attr.get(
111 distribution['family'],
112 getattr(self, default_value))))
113 return value
114
115 def get_shutdown_command_args(self, distribution):
116 reboot_command = self._task.args.get('reboot_command')
117 if reboot_command is not None:
118 try:
119 reboot_command = check_type_str(reboot_command, allow_conversion=False)
120 except TypeError as e:
121 raise AnsibleError("Invalid value given for 'reboot_command': %s." % to_native(e))
122
123 # No args were provided
124 try:
125 return reboot_command.split(' ', 1)[1]
126 except IndexError:
127 return ''
128 else:
129 args = self._get_value_from_facts('SHUTDOWN_COMMAND_ARGS', distribution, 'DEFAULT_SHUTDOWN_COMMAND_ARGS')
130
131 # Convert seconds to minutes. If less than 60, set it to 0.
132 delay_min = self.pre_reboot_delay // 60
133 reboot_message = self._task.args.get('msg', self.DEFAULT_REBOOT_MESSAGE)
134 return args.format(delay_sec=self.pre_reboot_delay, delay_min=delay_min, message=reboot_message)
135
136 def get_distribution(self, task_vars):
137 # FIXME: only execute the module if we don't already have the facts we need
138 distribution = {}
139 display.debug('{action}: running setup module to get distribution'.format(action=self._task.action))
140 module_output = self._execute_module(
141 task_vars=task_vars,
142 module_name='ansible.legacy.setup',
143 module_args={'gather_subset': 'min'})
144 try:
145 if module_output.get('failed', False):
146 raise AnsibleError('Failed to determine system distribution. {0}, {1}'.format(
147 to_native(module_output['module_stdout']).strip(),
148 to_native(module_output['module_stderr']).strip()))
149 distribution['name'] = module_output['ansible_facts']['ansible_distribution'].lower()
150 distribution['version'] = to_text(module_output['ansible_facts']['ansible_distribution_version'].split('.')[0])
151 distribution['family'] = to_text(module_output['ansible_facts']['ansible_os_family'].lower())
152 display.debug("{action}: distribution: {dist}".format(action=self._task.action, dist=distribution))
153 return distribution
154 except KeyError as ke:
155 raise AnsibleError('Failed to get distribution information. Missing "{0}" in output.'.format(ke.args[0]))
156
157 def get_shutdown_command(self, task_vars, distribution):
158 reboot_command = self._task.args.get('reboot_command')
159 if reboot_command is not None:
160 try:
161 reboot_command = check_type_str(reboot_command, allow_conversion=False)
162 except TypeError as e:
163 raise AnsibleError("Invalid value given for 'reboot_command': %s." % to_native(e))
164 shutdown_bin = reboot_command.split(' ', 1)[0]
165 else:
166 shutdown_bin = self._get_value_from_facts('SHUTDOWN_COMMANDS', distribution, 'DEFAULT_SHUTDOWN_COMMAND')
167
168 if shutdown_bin[0] == '/':
169 return shutdown_bin
170 else:
171 default_search_paths = ['/sbin', '/bin', '/usr/sbin', '/usr/bin', '/usr/local/sbin']
172 search_paths = self._task.args.get('search_paths', default_search_paths)
173
174 try:
175 # Convert bare strings to a list
176 search_paths = check_type_list(search_paths)
177 except TypeError:
178 err_msg = "'search_paths' must be a string or flat list of strings, got {0}"
179 raise AnsibleError(err_msg.format(search_paths))
180
181 display.debug('{action}: running find module looking in {paths} to get path for "{command}"'.format(
182 action=self._task.action,
183 command=shutdown_bin,
184 paths=search_paths))
185
186 find_result = self._execute_module(
187 task_vars=task_vars,
188 # prevent collection search by calling with ansible.legacy (still allows library/ override of find)
189 module_name='ansible.legacy.find',
190 module_args={
191 'paths': search_paths,
192 'patterns': [shutdown_bin],
193 'file_type': 'any'
194 }
195 )
196
197 full_path = [x['path'] for x in find_result['files']]
198 if not full_path:
199 raise AnsibleError('Unable to find command "{0}" in search paths: {1}'.format(shutdown_bin, search_paths))
200 return full_path[0]
201
202 def deprecated_args(self):
203 for arg, version in self.DEPRECATED_ARGS.items():
204 if self._task.args.get(arg) is not None:
205 display.warning("Since Ansible {version}, {arg} is no longer a valid option for {action}".format(
206 version=version,
207 arg=arg,
208 action=self._task.action))
209
210 def get_system_boot_time(self, distribution):
211 boot_time_command = self._get_value_from_facts('BOOT_TIME_COMMANDS', distribution, 'DEFAULT_BOOT_TIME_COMMAND')
212 if self._task.args.get('boot_time_command'):
213 boot_time_command = self._task.args.get('boot_time_command')
214
215 try:
216 check_type_str(boot_time_command, allow_conversion=False)
217 except TypeError as e:
218 raise AnsibleError("Invalid value given for 'boot_time_command': %s." % to_native(e))
219
220 display.debug("{action}: getting boot time with command: '{command}'".format(action=self._task.action, command=boot_time_command))
221 command_result = self._low_level_execute_command(boot_time_command, sudoable=self.DEFAULT_SUDOABLE)
222
223 if command_result['rc'] != 0:
224 stdout = command_result['stdout']
225 stderr = command_result['stderr']
226 raise AnsibleError("{action}: failed to get host boot time info, rc: {rc}, stdout: {out}, stderr: {err}".format(
227 action=self._task.action,
228 rc=command_result['rc'],
229 out=to_native(stdout),
230 err=to_native(stderr)))
231 display.debug("{action}: last boot time: {boot}".format(action=self._task.action, boot=command_result['stdout'].strip()))
232 return command_result['stdout'].strip()
233
234 def check_boot_time(self, distribution, previous_boot_time):
235 display.vvv("{action}: attempting to get system boot time".format(action=self._task.action))
236 connect_timeout = self._task.args.get('connect_timeout', self._task.args.get('connect_timeout_sec', self.DEFAULT_CONNECT_TIMEOUT))
237
238 # override connection timeout from defaults to the custom value
239 if connect_timeout:
240 try:
241 display.debug("{action}: setting connect_timeout to {value}".format(action=self._task.action, value=connect_timeout))
242 self._connection.set_option("connection_timeout", connect_timeout)
243 except AnsibleError:
244 try:
245 self._connection.set_option("timeout", connect_timeout)
246 except (AnsibleError, AttributeError):
247 display.warning("Connection plugin does not allow the connection timeout to be overridden")
248
249 self._connection.reset()
250
251 # try and get boot time
252 try:
253 current_boot_time = self.get_system_boot_time(distribution)
254 except Exception as e:
255 raise e
256
257 # FreeBSD returns an empty string immediately before reboot so adding a length
258 # check to prevent prematurely assuming system has rebooted
259 if len(current_boot_time) == 0 or current_boot_time == previous_boot_time:
260 raise ValueError("boot time has not changed")
261
262 def run_test_command(self, distribution, **kwargs):
263 test_command = self._task.args.get('test_command', self._get_value_from_facts('TEST_COMMANDS', distribution, 'DEFAULT_TEST_COMMAND'))
264 display.vvv("{action}: attempting post-reboot test command".format(action=self._task.action))
265 display.debug("{action}: attempting post-reboot test command '{command}'".format(action=self._task.action, command=test_command))
266 try:
267 command_result = self._low_level_execute_command(test_command, sudoable=self.DEFAULT_SUDOABLE)
268 except Exception:
269 # may need to reset the connection in case another reboot occurred
270 # which has invalidated our connection
271 try:
272 self._connection.reset()
273 except AttributeError:
274 pass
275 raise
276
277 if command_result['rc'] != 0:
278 msg = 'Test command failed: {err} {out}'.format(
279 err=to_native(command_result['stderr']),
280 out=to_native(command_result['stdout']))
281 raise RuntimeError(msg)
282
283 display.vvv("{action}: system successfully rebooted".format(action=self._task.action))
284
285 def do_until_success_or_timeout(self, action, reboot_timeout, action_desc, distribution, action_kwargs=None):
286 max_end_time = datetime.now(timezone.utc) + timedelta(seconds=reboot_timeout)
287 if action_kwargs is None:
288 action_kwargs = {}
289
290 fail_count = 0
291 max_fail_sleep = 12
292 last_error_msg = ''
293
294 while datetime.now(timezone.utc) < max_end_time:
295 try:
296 action(distribution=distribution, **action_kwargs)
297 if action_desc:
298 display.debug('{action}: {desc} success'.format(action=self._task.action, desc=action_desc))
299 return
300 except Exception as e:
301 if isinstance(e, AnsibleConnectionFailure):
302 try:
303 self._connection.reset()
304 except AnsibleConnectionFailure:
305 pass
306 # Use exponential backoff with a max timeout, plus a little bit of randomness
307 random_int = secrets.randbelow(1000) / 1000
308 fail_sleep = 2 ** fail_count + random_int
309 if fail_sleep > max_fail_sleep:
310
311 fail_sleep = max_fail_sleep + random_int
312 if action_desc:
313 try:
314 error = to_text(e).splitlines()[-1]
315 except IndexError as e:
316 error = to_text(e)
317 last_error_msg = f"{self._task.action}: {action_desc} fail '{error}'"
318 msg = f"{last_error_msg}, retrying in {fail_sleep:.4f} seconds..."
319
320 display.debug(msg)
321 display.vvv(msg)
322 fail_count += 1
323 time.sleep(fail_sleep)
324
325 if last_error_msg:
326 msg = f"Last error message before the timeout exception - {last_error_msg}"
327 display.debug(msg)
328 display.vvv(msg)
329 raise TimedOutException('Timed out waiting for {desc} (timeout={timeout})'.format(desc=action_desc, timeout=reboot_timeout))
330
331 def perform_reboot(self, task_vars, distribution):
332 result = {}
333 reboot_result = {}
334 shutdown_command = self.get_shutdown_command(task_vars, distribution)
335 shutdown_command_args = self.get_shutdown_command_args(distribution)
336 reboot_command = '{0} {1}'.format(shutdown_command, shutdown_command_args)
337
338 try:
339 display.vvv("{action}: rebooting server...".format(action=self._task.action))
340 display.debug("{action}: rebooting server with command '{command}'".format(action=self._task.action, command=reboot_command))
341 reboot_result = self._low_level_execute_command(reboot_command, sudoable=self.DEFAULT_SUDOABLE)
342 except AnsibleConnectionFailure as e:
343 # If the connection is closed too quickly due to the system being shutdown, carry on
344 display.debug('{action}: AnsibleConnectionFailure caught and handled: {error}'.format(action=self._task.action, error=to_text(e)))
345 reboot_result['rc'] = 0
346
347 result['start'] = datetime.now(timezone.utc)
348
349 if reboot_result['rc'] != 0:
350 result['failed'] = True
351 result['rebooted'] = False
352 result['msg'] = "Reboot command failed. Error was: '{stdout}, {stderr}'".format(
353 stdout=to_native(reboot_result['stdout'].strip()),
354 stderr=to_native(reboot_result['stderr'].strip()))
355 return result
356
357 result['failed'] = False
358 return result
359
360 def validate_reboot(self, distribution, original_connection_timeout=None, action_kwargs=None):
361 display.vvv('{action}: validating reboot'.format(action=self._task.action))
362 result = {}
363
364 try:
365 # keep on checking system boot_time with short connection responses
366 reboot_timeout = int(self._task.args.get('reboot_timeout', self._task.args.get('reboot_timeout_sec', self.DEFAULT_REBOOT_TIMEOUT)))
367
368 self.do_until_success_or_timeout(
369 action=self.check_boot_time,
370 action_desc="last boot time check",
371 reboot_timeout=reboot_timeout,
372 distribution=distribution,
373 action_kwargs=action_kwargs)
374
375 # Get the connect_timeout set on the connection to compare to the original
376 try:
377 connect_timeout = self._connection.get_option('connection_timeout')
378 except KeyError:
379 try:
380 connect_timeout = self._connection.get_option('timeout')
381 except KeyError:
382 pass
383 else:
384 if original_connection_timeout != connect_timeout:
385 try:
386 display.debug("{action}: setting connect_timeout/timeout back to original value of {value}".format(action=self._task.action,
387 value=original_connection_timeout))
388 try:
389 self._connection.set_option("connection_timeout", original_connection_timeout)
390 except AnsibleError:
391 try:
392 self._connection.set_option("timeout", original_connection_timeout)
393 except AnsibleError:
394 raise
395 # reset the connection to clear the custom connection timeout
396 self._connection.reset()
397 except (AnsibleError, AttributeError) as e:
398 display.debug("{action}: failed to reset connection_timeout back to default: {error}".format(action=self._task.action,
399 error=to_text(e)))
400
401 # finally run test command to ensure everything is working
402 # FUTURE: add a stability check (system must remain up for N seconds) to deal with self-multi-reboot updates
403 self.do_until_success_or_timeout(
404 action=self.run_test_command,
405 action_desc="post-reboot test command",
406 reboot_timeout=reboot_timeout,
407 distribution=distribution,
408 action_kwargs=action_kwargs)
409
410 result['rebooted'] = True
411 result['changed'] = True
412
413 except TimedOutException as toex:
414 result['failed'] = True
415 result['rebooted'] = True
416 result['msg'] = to_text(toex)
417 return result
418
419 return result
420
421 def run(self, tmp=None, task_vars=None):
422 self._supports_check_mode = True
423
424 # If running with local connection, fail so we don't reboot ourselves
425 if self._connection.transport == 'local':
426 msg = 'Running {0} with local connection would reboot the control node.'.format(self._task.action)
427 return {'changed': False, 'elapsed': 0, 'rebooted': False, 'failed': True, 'msg': msg}
428
429 if self._task.check_mode:
430 return {'changed': True, 'elapsed': 0, 'rebooted': True}
431
432 if task_vars is None:
433 task_vars = {}
434
435 self.deprecated_args()
436
437 result = super(ActionModule, self).run(tmp, task_vars)
438
439 if result.get('skipped', False) or result.get('failed', False):
440 return result
441
442 distribution = self.get_distribution(task_vars)
443
444 # Get current boot time
445 try:
446 previous_boot_time = self.get_system_boot_time(distribution)
447 except Exception as e:
448 result['failed'] = True
449 result['reboot'] = False
450 result['msg'] = to_text(e)
451 return result
452
453 # Get the original connection_timeout option var so it can be reset after
454 original_connection_timeout = None
455
456 display.debug("{action}: saving original connect_timeout of {timeout}".format(action=self._task.action, timeout=original_connection_timeout))
457 try:
458 original_connection_timeout = self._connection.get_option('connection_timeout')
459 except KeyError:
460 try:
461 original_connection_timeout = self._connection.get_option('timeout')
462 except KeyError:
463 display.debug("{action}: connect_timeout connection option has not been set".format(action=self._task.action))
464
465 # Initiate reboot
466 reboot_result = self.perform_reboot(task_vars, distribution)
467
468 if reboot_result['failed']:
469 result = reboot_result
470 elapsed = datetime.now(timezone.utc) - reboot_result['start']
471 result['elapsed'] = elapsed.seconds
472 return result
473
474 if self.post_reboot_delay != 0:
475 display.debug("{action}: waiting an additional {delay} seconds".format(action=self._task.action, delay=self.post_reboot_delay))
476 display.vvv("{action}: waiting an additional {delay} seconds".format(action=self._task.action, delay=self.post_reboot_delay))
477 time.sleep(self.post_reboot_delay)
478
479 # Make sure reboot was successful
480 result = self.validate_reboot(distribution, original_connection_timeout, action_kwargs={'previous_boot_time': previous_boot_time})
481
482 elapsed = datetime.now(timezone.utc) - reboot_result['start']
483 result['elapsed'] = elapsed.seconds
484
485 return result