Debian Codegraph @

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

raw
1 # Copyright: (c) 2021, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 """Reboot action for Windows hosts
5
6 This contains the code to reboot a Windows host for use by other action plugins
7 in this collection. Right now it should only be used in this collection as the
8 interface is not final and count be subject to change.
9
10 This is a straight copy from ansible.windows (with an embeded quote_pwsh)
11 """
12
13 # FOR INTERNAL COLLECTION USE ONLY
14 # The interfaces in this file are meant for use within this collection
15 # and may not remain stable to outside uses. Changes may be made in ANY release, even a bugfix release.
16 # See also: https://github.com/ansible/community/issues/539#issuecomment-780839686
17 # Please open an issue if you have questions about this.
18
19 import datetime
20 import json
21 import random
22 import re
23 import time
24 import traceback
25 import uuid
26 import typing as t
27
28 from ansible.errors import AnsibleConnectionFailure, AnsibleError
29 from ansible.module_utils.common.text.converters import to_text
30 from ansible.plugins.connection import ConnectionBase
31 from ansible.utils.display import Display
32
33
34 # This is not ideal but the psrp connection plugin doesn't catch all these exceptions as an AnsibleConnectionFailure.
35 # Until we can guarantee we are using a version of psrp that handles all this we try to handle those issues.
36 try:
37 from requests.exceptions import (
38 RequestException,
39 )
40 except ImportError:
41 RequestException = AnsibleConnectionFailure
42
43
44 _LOGON_UI_KEY = (
45 r"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoLogonChecked"
46 )
47
48 _DEFAULT_BOOT_TIME_COMMAND = (
49 "(Get-CimInstance -ClassName Win32_OperatingSystem -Property LastBootUpTime)"
50 ".LastBootUpTime.ToFileTime()"
51 )
52
53 # PowerShell has 5 characters it uses as a single quote, we need to double up on all of them.
54 # https://github.com/PowerShell/PowerShell/blob/b7cb335f03fe2992d0cbd61699de9d9aafa1d7c1/src/System.Management.Automation/engine/parser/CharTraits.cs#L265-L272
55 # https://github.com/PowerShell/PowerShell/blob/b7cb335f03fe2992d0cbd61699de9d9aafa1d7c1/src/System.Management.Automation/engine/parser/CharTraits.cs#L18-L21
56 _UNSAFE_PWSH = re.compile("(['\u2018\u2019\u201a\u201b])")
57
58 T = t.TypeVar("T")
59
60 display = Display()
61
62
63 class _ReturnResultException(Exception):
64 """Used to sneak results back to the return dict from an exception"""
65
66 def __init__(self, msg, **result):
67 super().__init__(msg)
68 self.result = result
69
70
71 class _TestCommandFailure(Exception):
72 """Differentiates between a connection failure and just a command assertion failure during the reboot loop"""
73
74
75 def reboot_host(
76 task_action: str,
77 connection: ConnectionBase,
78 boot_time_command: str = _DEFAULT_BOOT_TIME_COMMAND,
79 connect_timeout: int = 5,
80 msg: str = "Reboot initiated by Ansible",
81 post_reboot_delay: int = 0,
82 pre_reboot_delay: int = 2,
83 reboot_timeout: int = 600,
84 test_command: t.Optional[str] = None,
85 previous_boot_time: t.Optional[str] = None,
86 ) -> t.Dict[str, t.Any]:
87 """Reboot a Windows Host.
88
89 Used by action plugins in ansible.windows to reboot a Windows host. It
90 takes in the connection plugin so it can run the commands on the targeted
91 host and monitor the reboot process. The return dict will have the
92 following keys set:
93
94 changed: Whether a change occurred (reboot was done)
95 elapsed: Seconds elapsed between the reboot and it coming back online
96 failed: Whether a failure occurred
97 unreachable: Whether it failed to connect to the host on the first cmd
98 rebooted: Whether the host was rebooted
99
100 When failed=True there may be more keys to give some information around
101 the failure like msg, exception. There are other keys that might be
102 returned as well but they are dependent on the failure that occurred.
103
104 Verbosity levels used:
105 2: Message when each reboot step is completed
106 4: Connection plugin operations and their results
107 5: Raw commands run and the results of those commands
108 Debug: Everything, very verbose
109
110 Args:
111 task_action: The name of the action plugin that is running for logging.
112 connection: The connection plugin to run the reboot commands on.
113 boot_time_command: The command to run when getting the boot timeout.
114 connect_timeout: Override the connection timeout of the connection
115 plugin when polling the rebooted host.
116 msg: The message to display to interactive users when rebooting the
117 host.
118 post_reboot_delay: Seconds to wait after sending the reboot command
119 before checking to see if it has returned.
120 pre_reboot_delay: Seconds to wait when sending the reboot command.
121 reboot_timeout: Seconds to wait while polling for the host to come
122 back online.
123 test_command: Command to run when the host is back online and
124 determines the machine is ready for management. When not defined
125 the default command should wait until the reboot is complete and
126 all pre-login configuration has completed.
127 previous_boot_time: The previous boot time of the host, when set the
128 value is used as the previous boot time check and the code will
129 not initiate the reboot itself as it expects the host to be in a
130 reboot cycle itself. Used when a module has initiated the reboot.
131
132 Returns:
133 (Dict[str, Any]): The return result as a dictionary. Use the 'failed'
134 key to determine if there was a failure or not.
135 """
136 result: t.Dict[str, t.Any] = {
137 "changed": False,
138 "elapsed": 0,
139 "failed": False,
140 "unreachable": False,
141 "rebooted": False,
142 }
143 host_context = {"do_close_on_reset": True}
144
145 send_reboot_command = previous_boot_time is None
146
147 if send_reboot_command:
148 # Get current boot time. A lot of tasks that require a reboot leave the WSMan stack in a bad place. Will try to
149 # get the initial boot time 3 times before giving up.
150 try:
151 previous_boot_time = _do_until_success_or_retry_limit(
152 task_action,
153 connection,
154 host_context,
155 "pre-reboot boot time check",
156 3,
157 _get_system_boot_time,
158 task_action,
159 connection,
160 boot_time_command,
161 )
162
163 except Exception as e:
164 # Report a the failure based on the last exception received.
165 if isinstance(e, _ReturnResultException):
166 result.update(e.result)
167
168 if isinstance(e, AnsibleConnectionFailure):
169 result["unreachable"] = True
170 else:
171 result["failed"] = True
172
173 result["msg"] = str(e)
174 result["exception"] = traceback.format_exc()
175 return result
176
177 # Get the original connection_timeout option var so it can be reset after
178 original_connection_timeout: t.Optional[float] = None
179 try:
180 original_connection_timeout = connection.get_option("connection_timeout")
181 display.vvvv(
182 f"{task_action}: saving original connection_timeout of {original_connection_timeout}"
183 )
184 except KeyError:
185 display.vvvv(
186 f"{task_action}: connection_timeout connection option has not been set"
187 )
188
189 # Initiate reboot
190 # This command may be wrapped in other shells or command making it hard to detect what shutdown.exe actually
191 # returned. We use this hackery to return a json that contains the stdout/stderr/rc as a structured object for our
192 # code to parse and detect if something went wrong.
193 reboot_command = """$ErrorActionPreference = 'Continue'
194
195 if ($%s) {
196 Remove-Item -LiteralPath '%s' -Force -ErrorAction SilentlyContinue
197 }
198
199 $stdout = $null
200 $stderr = . { shutdown.exe /r /t %s /c %s | Set-Variable stdout } 2>&1 | ForEach-Object ToString
201
202 ConvertTo-Json -Compress -InputObject @{
203 stdout = (@($stdout) -join "`n")
204 stderr = (@($stderr) -join "`n")
205 rc = $LASTEXITCODE
206 }
207 """ % (
208 str(not test_command),
209 _LOGON_UI_KEY,
210 int(pre_reboot_delay),
211 _quote_pwsh(msg),
212 )
213
214 expected_test_result = (
215 None # We cannot have an expected result if the command is user defined
216 )
217 if not test_command:
218 # It turns out that LogonUI will create this registry key if it does not exist when it's about to show the
219 # logon prompt. Normally this is a volatile key but if someone has explicitly created it that might no longer
220 # be the case. We ensure it is not present on a reboot so we can wait until LogonUI creates it to determine
221 # the host is actually online and ready, e.g. no configurations/updates still to be applied.
222 # We echo a known successful statement to catch issues with powershell failing to start but the rc mysteriously
223 # being 0 causing it to consider a successful reboot too early (seen on ssh connections).
224 expected_test_result = f"success-{uuid.uuid4()}"
225 test_command = f"Get-Item -LiteralPath '{_LOGON_UI_KEY}' -ErrorAction Stop; '{expected_test_result}'"
226
227 start = None
228 try:
229 if send_reboot_command:
230 _perform_reboot(task_action, connection, reboot_command)
231
232 start = datetime.datetime.now(datetime.timezone.utc)
233 result["changed"] = True
234 result["rebooted"] = True
235
236 if post_reboot_delay != 0:
237 display.vv(
238 f"{task_action}: waiting an additional {post_reboot_delay} seconds"
239 )
240 time.sleep(post_reboot_delay)
241
242 # Keep on trying to run the last boot time check until it is successful or the timeout is raised
243 display.vv(f"{task_action} validating reboot")
244 _do_until_success_or_timeout(
245 task_action,
246 connection,
247 host_context,
248 "last boot time check",
249 reboot_timeout,
250 _check_boot_time,
251 task_action,
252 connection,
253 host_context,
254 previous_boot_time,
255 boot_time_command,
256 connect_timeout,
257 )
258
259 # Reset the connection plugin connection timeout back to the original
260 if original_connection_timeout is not None:
261 _set_connection_timeout(
262 task_action,
263 connection,
264 host_context,
265 original_connection_timeout,
266 )
267
268 # Run test command until ti is successful or a timeout occurs
269 display.vv(f"{task_action} running post reboot test command")
270 _do_until_success_or_timeout(
271 task_action,
272 connection,
273 host_context,
274 "post-reboot test command",
275 reboot_timeout,
276 _run_test_command,
277 task_action,
278 connection,
279 test_command,
280 expected=expected_test_result,
281 )
282
283 display.vv(f"{task_action}: system successfully rebooted")
284
285 except Exception as e:
286 if isinstance(e, _ReturnResultException):
287 result.update(e.result)
288
289 result["failed"] = True
290 result["msg"] = str(e)
291 result["exception"] = traceback.format_exc()
292
293 if start:
294 elapsed = datetime.datetime.now(datetime.timezone.utc) - start
295 result["elapsed"] = elapsed.seconds
296
297 return result
298
299
300 def _check_boot_time(
301 task_action: str,
302 connection: ConnectionBase,
303 host_context: t.Dict[str, t.Any],
304 previous_boot_time: int,
305 boot_time_command: str,
306 timeout: int,
307 ):
308 """Checks the system boot time has been changed or not"""
309 display.vvvv("%s: attempting to get system boot time" % task_action)
310
311 # override connection timeout from defaults to custom value
312 if timeout:
313 _set_connection_timeout(task_action, connection, host_context, timeout)
314
315 # try and get boot time
316 current_boot_time = _get_system_boot_time(
317 task_action, connection, boot_time_command
318 )
319 if current_boot_time == previous_boot_time:
320 raise _TestCommandFailure("boot time has not changed")
321
322
323 def _do_until_success_or_retry_limit(
324 task_action: str,
325 connection: ConnectionBase,
326 host_context: t.Dict[str, t.Any],
327 action_desc: str,
328 retries: int,
329 func: t.Callable[..., T],
330 *args: t.Any,
331 **kwargs: t.Any,
332 ) -> t.Optional[T]:
333 """Runs the function multiple times ignoring errors until the retry limit is hit"""
334
335 def wait_condition(idx):
336 return idx < retries
337
338 return _do_until_success_or_condition(
339 task_action,
340 connection,
341 host_context,
342 action_desc,
343 wait_condition,
344 func,
345 *args,
346 **kwargs,
347 )
348
349
350 def _do_until_success_or_timeout(
351 task_action: str,
352 connection: ConnectionBase,
353 host_context: t.Dict[str, t.Any],
354 action_desc: str,
355 timeout: float,
356 func: t.Callable[..., T],
357 *args: t.Any,
358 **kwargs: t.Any,
359 ) -> t.Optional[T]:
360 """Runs the function multiple times ignoring errors until a timeout occurs"""
361 max_end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=timeout)
362
363 def wait_condition(idx):
364 return datetime.datetime.now(datetime.timezone.utc) < max_end_time
365
366 try:
367 return _do_until_success_or_condition(
368 task_action,
369 connection,
370 host_context,
371 action_desc,
372 wait_condition,
373 func,
374 *args,
375 **kwargs,
376 )
377 except Exception:
378 raise Exception(
379 "Timed out waiting for %s (timeout=%s)" % (action_desc, timeout)
380 )
381
382
383 def _do_until_success_or_condition(
384 task_action: str,
385 connection: ConnectionBase,
386 host_context: t.Dict[str, t.Any],
387 action_desc: str,
388 condition: t.Callable[[int], bool],
389 func: t.Callable[..., T],
390 *args: t.Any,
391 **kwargs: t.Any,
392 ) -> t.Optional[T]:
393 """Runs the function multiple times ignoring errors until the condition is false"""
394 fail_count = 0
395 max_fail_sleep = 12
396 reset_required = False
397 last_error = None
398
399 while fail_count == 0 or condition(fail_count):
400 try:
401 if reset_required:
402 # Keep on trying the reset until it succeeds.
403 _reset_connection(task_action, connection, host_context)
404 reset_required = False
405
406 else:
407 res = func(*args, **kwargs)
408 display.vvvvv("%s: %s success" % (task_action, action_desc))
409
410 return res
411
412 except Exception as e:
413 last_error = e
414
415 if not isinstance(e, _TestCommandFailure):
416 # The error may be due to a connection problem, just reset the connection just in case
417 reset_required = True
418
419 # Use exponential backoff with a max timeout, plus a little bit of randomness
420 random_int = random.randint(0, 1000) / 1000
421 fail_sleep = 2**fail_count + random_int
422 if fail_sleep > max_fail_sleep:
423 fail_sleep = max_fail_sleep + random_int
424
425 try:
426 error = str(e).splitlines()[-1]
427 except IndexError:
428 error = str(e)
429
430 display.vvvvv(
431 "{action}: {desc} fail {e_type} '{err}', retrying in {sleep:.4} seconds...\n{tcb}".format(
432 action=task_action,
433 desc=action_desc,
434 e_type=type(e).__name__,
435 err=error,
436 sleep=fail_sleep,
437 tcb=traceback.format_exc(),
438 )
439 )
440
441 fail_count += 1
442 time.sleep(fail_sleep)
443
444 if last_error:
445 raise last_error
446
447 return None
448
449
450 def _execute_command(
451 task_action: str,
452 connection: ConnectionBase,
453 command: str,
454 ) -> t.Tuple[int, str, str]:
455 """Runs a command on the Windows host and returned the result"""
456 display.vvvvv(f"{task_action}: running command: {command}")
457
458 # Need to wrap the command in our PowerShell encoded wrapper. This is done to align the command input to a
459 # common shell and to allow the psrp connection plugin to report the correct exit code without manually setting
460 # $LASTEXITCODE for just that plugin.
461 command = connection._shell._encode_script(command)
462
463 try:
464 rc, stdout, stderr = connection.exec_command(
465 command, in_data=None, sudoable=False
466 )
467 except RequestException as e:
468 # The psrp connection plugin should be doing this but until we can guarantee it does we just convert it here
469 # to ensure AnsibleConnectionFailure refers to actual connection errors.
470 raise AnsibleConnectionFailure(f"Failed to connect to the host: {e}")
471
472 rc = rc or 0
473 stdout = to_text(stdout, errors="surrogate_or_strict").strip()
474 stderr = to_text(stderr, errors="surrogate_or_strict").strip()
475
476 display.vvvvv(
477 f"{task_action}: command result - rc: {rc}, stdout: {stdout}, stderr: {stderr}"
478 )
479
480 return rc, stdout, stderr
481
482
483 def _get_system_boot_time(
484 task_action: str,
485 connection: ConnectionBase,
486 boot_time_command: str,
487 ) -> str:
488 """Gets a unique identifier to represent the boot time of the Windows host"""
489 display.vvvv(f"{task_action}: getting boot time")
490 rc, stdout, stderr = _execute_command(task_action, connection, boot_time_command)
491
492 if rc != 0:
493 msg = f"{task_action}: failed to get host boot time info"
494 raise _ReturnResultException(msg, rc=rc, stdout=stdout, stderr=stderr)
495
496 display.vvvv(f"{task_action}: last boot time: {stdout}")
497 return stdout
498
499
500 def _perform_reboot(
501 task_action: str,
502 connection: ConnectionBase,
503 reboot_command: str,
504 handle_abort: bool = True,
505 ) -> None:
506 """Runs the reboot command"""
507 display.vv(f"{task_action}: rebooting server...")
508
509 stdout = stderr = None
510 try:
511 rc, stdout, stderr = _execute_command(task_action, connection, reboot_command)
512
513 except AnsibleConnectionFailure as e:
514 # If the connection is closed too quickly due to the system being shutdown, carry on
515 display.vvvv(f"{task_action}: AnsibleConnectionFailure caught and handled: {e}")
516 rc = 0
517
518 if stdout:
519 try:
520 reboot_result = json.loads(stdout)
521 except getattr(json.decoder, "JSONDecodeError", ValueError):
522 # While the reboot command should output json it may have failed for some other reason. We continue
523 # reporting with that output instead
524 pass
525 else:
526 stdout = reboot_result.get("stdout", stdout)
527 stderr = reboot_result.get("stderr", stderr)
528 rc = int(reboot_result.get("rc", rc))
529
530 # Test for "A system shutdown has already been scheduled. (1190)" and handle it gracefully
531 if handle_abort and (rc == 1190 or (rc != 0 and stderr and "(1190)" in stderr)):
532 display.warning("A scheduled reboot was pre-empted by Ansible.")
533
534 # Try to abort (this may fail if it was already aborted)
535 rc, stdout, stderr = _execute_command(
536 task_action, connection, "shutdown.exe /a"
537 )
538 display.vvvv(
539 f"{task_action}: result from trying to abort existing shutdown - rc: {rc}, stdout: {stdout}, stderr: {stderr}"
540 )
541
542 return _perform_reboot(
543 task_action, connection, reboot_command, handle_abort=False
544 )
545
546 if rc != 0:
547 msg = f"{task_action}: Reboot command failed"
548 raise _ReturnResultException(msg, rc=rc, stdout=stdout, stderr=stderr)
549
550
551 def _reset_connection(
552 task_action: str,
553 connection: ConnectionBase,
554 host_context: t.Dict[str, t.Any],
555 ignore_errors: bool = False,
556 ) -> None:
557 """Resets the connection handling any errors"""
558
559 def _wrap_conn_err(func, *args, **kwargs):
560 try:
561 func(*args, **kwargs)
562
563 except (AnsibleError, RequestException) as e:
564 if ignore_errors:
565 return False
566
567 raise AnsibleError(e)
568
569 return True
570
571 # While reset() should probably better handle this some connection plugins don't clear the existing connection on
572 # reset() leaving resources still in use on the target (WSMan shells). Instead we try to manually close the
573 # connection then call reset. If it fails once we want to skip closing to avoid a perpetual loop and just hope
574 # reset() brings us back into a good state. If it's successful we still want to try it again.
575 if host_context["do_close_on_reset"]:
576 display.vvvv(f"{task_action}: closing connection plugin")
577 try:
578 success = _wrap_conn_err(connection.close)
579
580 except Exception:
581 host_context["do_close_on_reset"] = False
582 raise
583
584 host_context["do_close_on_reset"] = success
585
586 # For some connection plugins (ssh) reset actually does something more than close so we also class that
587 display.vvvv(f"{task_action}: resetting connection plugin")
588 try:
589 _wrap_conn_err(connection.reset)
590
591 except AttributeError:
592 # Not all connection plugins have reset so we just ignore those, close should have done our job.
593 pass
594
595
596 def _run_test_command(
597 task_action: str,
598 connection: ConnectionBase,
599 command: str,
600 expected: t.Optional[str] = None,
601 ) -> None:
602 """Runs the user specified test command until the host is able to run it properly"""
603 display.vvvv(f"{task_action}: attempting post-reboot test command")
604
605 rc, stdout, stderr = _execute_command(task_action, connection, command)
606
607 if rc != 0:
608 msg = f"{task_action}: Test command failed - rc: {rc}, stdout: {stdout}, stderr: {stderr}"
609 raise _TestCommandFailure(msg)
610
611 if expected and expected not in stdout:
612 msg = f"{task_action}: Test command failed - '{expected}' was not in stdout: {stdout}"
613 raise _TestCommandFailure(msg)
614
615
616 def _set_connection_timeout(
617 task_action: str,
618 connection: ConnectionBase,
619 host_context: t.Dict[str, t.Any],
620 timeout: float,
621 ) -> None:
622 """Sets the connection plugin connection_timeout option and resets the connection"""
623 try:
624 current_connection_timeout = connection.get_option("connection_timeout")
625 except KeyError:
626 # Not all connection plugins implement this, just ignore the setting if it doesn't work
627 return
628
629 if timeout == current_connection_timeout:
630 return
631
632 display.vvvv(f"{task_action}: setting connect_timeout {timeout}")
633 connection.set_option("connection_timeout", timeout)
634
635 _reset_connection(task_action, connection, host_context, ignore_errors=True)
636
637
638 def _quote_pwsh(s: str) -> str:
639 """Quotes a value for PowerShell.
640
641 Quotes a value to be safely used by a PowerShell expression. The input
642 string because something that is safely wrapped in single quotes.
643
644 Args:
645 s: The string to quote.
646
647 Returns:
648 (text_type): The quoted string value.
649 """
650 # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-5.1
651 if not s:
652 return "''"
653
654 # We should always quote values in PowerShell as it has conflicting rules where strings can and can't be quoted.
655 # This means we quote the entire arg with single quotes and just double up on the single quote equivalent chars.
656 return "'{0}'".format(_UNSAFE_PWSH.sub("\\1\\1", s))