1# Copyright: (c) 2018, Matt Davis <mdavis@ansible.com>
2# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4from __future__ import (absolute_import, division, print_function)
5__metaclass__ = type
6
7from datetime import datetime
8
9from ansible.errors import AnsibleError
10from ansible.module_utils._text import to_native
11from ansible.plugins.action import ActionBase
12from ansible.plugins.action.reboot import ActionModule as RebootActionModule
13from ansible.utils.display import Display
14
15display = Display()
16
17
18class TimedOutException(Exception):
19    pass
20
21
22class ActionModule(RebootActionModule, ActionBase):
23    TRANSFERS_FILES = False
24    _VALID_ARGS = frozenset((
25        'connect_timeout', 'connect_timeout_sec', 'msg', 'post_reboot_delay', 'post_reboot_delay_sec', 'pre_reboot_delay', 'pre_reboot_delay_sec',
26        'reboot_timeout', 'reboot_timeout_sec', 'shutdown_timeout', 'shutdown_timeout_sec', 'test_command',
27    ))
28
29    DEFAULT_BOOT_TIME_COMMAND = "(Get-WmiObject -ClassName Win32_OperatingSystem).LastBootUpTime"
30    DEFAULT_CONNECT_TIMEOUT = 5
31    DEFAULT_PRE_REBOOT_DELAY = 2
32    DEFAULT_SUDOABLE = False
33    DEFAULT_SHUTDOWN_COMMAND_ARGS = '/r /t {delay_sec} /c "{message}"'
34
35    DEPRECATED_ARGS = {
36        'shutdown_timeout': '2.5',
37        'shutdown_timeout_sec': '2.5',
38    }
39
40    def __init__(self, *args, **kwargs):
41        super(ActionModule, self).__init__(*args, **kwargs)
42
43    def get_distribution(self, task_vars):
44        return {'name': 'windows', 'version': '', 'family': ''}
45
46    def get_shutdown_command(self, task_vars, distribution):
47        return self.DEFAULT_SHUTDOWN_COMMAND
48
49    def run_test_command(self, distribution, **kwargs):
50        # Need to wrap the test_command in our PowerShell encoded wrapper. This is done to align the command input to a
51        # common shell and to allow the psrp connection plugin to report the correct exit code without manually setting
52        # $LASTEXITCODE for just that plugin.
53        test_command = self._task.args.get('test_command', self.DEFAULT_TEST_COMMAND)
54        kwargs['test_command'] = self._connection._shell._encode_script(test_command)
55        super(ActionModule, self).run_test_command(distribution, **kwargs)
56
57    def perform_reboot(self, task_vars, distribution):
58        shutdown_command = self.get_shutdown_command(task_vars, distribution)
59        shutdown_command_args = self.get_shutdown_command_args(distribution)
60        reboot_command = self._connection._shell._encode_script('{0} {1}'.format(shutdown_command, shutdown_command_args))
61
62        display.vvv("{action}: rebooting server...".format(action=self._task.action))
63        display.debug("{action}: distribution: {dist}".format(action=self._task.action, dist=distribution))
64        display.debug("{action}: rebooting server with command '{command}'".format(action=self._task.action, command=reboot_command))
65
66        result = {}
67        reboot_result = self._low_level_execute_command(reboot_command, sudoable=self.DEFAULT_SUDOABLE)
68        result['start'] = datetime.utcnow()
69
70        # Test for "A system shutdown has already been scheduled. (1190)" and handle it gracefully
71        stdout = reboot_result['stdout']
72        stderr = reboot_result['stderr']
73        if reboot_result['rc'] == 1190 or (reboot_result['rc'] != 0 and "(1190)" in reboot_result['stderr']):
74            display.warning('A scheduled reboot was pre-empted by Ansible.')
75
76            # Try to abort (this may fail if it was already aborted)
77            result1 = self._low_level_execute_command(self._connection._shell._encode_script('shutdown /a'),
78                                                      sudoable=self.DEFAULT_SUDOABLE)
79
80            # Initiate reboot again
81            result2 = self._low_level_execute_command(reboot_command, sudoable=self.DEFAULT_SUDOABLE)
82
83            reboot_result['rc'] = result2['rc']
84            stdout += result1['stdout'] + result2['stdout']
85            stderr += result1['stderr'] + result2['stderr']
86
87        if reboot_result['rc'] != 0:
88            result['failed'] = True
89            result['rebooted'] = False
90            result['msg'] = "Reboot command failed, error was: {stdout} {stderr}".format(
91                stdout=to_native(stdout.strip()),
92                stderr=to_native(stderr.strip()))
93            return result
94
95        result['failed'] = False
96        return result
97