2018-10-04 19:44:50 +00:00
|
|
|
# Copyright: (c) 2016-2018, Matt Davis <mdavis@ansible.com>
|
|
|
|
# Copyright: (c) 2018, Sam Doran <sdoran@redhat.com>
|
2018-08-24 01:12:12 +00:00
|
|
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
|
|
|
|
|
|
|
from __future__ import (absolute_import, division, print_function)
|
|
|
|
__metaclass__ = type
|
|
|
|
|
|
|
|
import random
|
|
|
|
import time
|
|
|
|
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
2018-11-12 16:30:46 +00:00
|
|
|
from ansible.errors import AnsibleError, AnsibleConnectionFailure
|
2018-08-24 01:12:12 +00:00
|
|
|
from ansible.module_utils._text import to_native, to_text
|
2018-10-04 19:44:50 +00:00
|
|
|
from ansible.plugins.action import ActionBase
|
2018-11-20 23:06:51 +00:00
|
|
|
from ansible.utils.display import Display
|
2018-08-24 01:12:12 +00:00
|
|
|
|
2018-11-20 23:06:51 +00:00
|
|
|
display = Display()
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TimedOutException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class ActionModule(ActionBase):
|
|
|
|
TRANSFERS_FILES = False
|
2018-10-08 18:56:40 +00:00
|
|
|
_VALID_ARGS = frozenset(('connect_timeout', 'msg', 'post_reboot_delay', 'pre_reboot_delay', 'test_command', 'reboot_timeout'))
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
DEFAULT_REBOOT_TIMEOUT = 600
|
|
|
|
DEFAULT_CONNECT_TIMEOUT = None
|
|
|
|
DEFAULT_PRE_REBOOT_DELAY = 0
|
|
|
|
DEFAULT_POST_REBOOT_DELAY = 0
|
|
|
|
DEFAULT_TEST_COMMAND = 'whoami'
|
2018-11-08 14:54:58 +00:00
|
|
|
DEFAULT_BOOT_TIME_COMMAND = 'cat /proc/sys/kernel/random/boot_id'
|
2018-08-24 01:12:12 +00:00
|
|
|
DEFAULT_REBOOT_MESSAGE = 'Reboot initiated by Ansible'
|
|
|
|
DEFAULT_SHUTDOWN_COMMAND = 'shutdown'
|
2018-12-11 16:05:10 +00:00
|
|
|
DEFAULT_SHUTDOWN_COMMAND_ARGS = '-r {delay_min} "{message}"'
|
2018-08-24 01:12:12 +00:00
|
|
|
DEFAULT_SUDOABLE = True
|
|
|
|
|
|
|
|
DEPRECATED_ARGS = {}
|
|
|
|
|
2018-09-28 20:07:44 +00:00
|
|
|
BOOT_TIME_COMMANDS = {
|
2018-11-08 14:54:58 +00:00
|
|
|
'freebsd': '/sbin/sysctl kern.boottime',
|
2018-12-11 16:05:10 +00:00
|
|
|
'openbsd': '/sbin/sysctl kern.boottime',
|
|
|
|
'macosx': 'who -b',
|
|
|
|
'solaris': 'who -b',
|
2018-11-08 14:54:58 +00:00
|
|
|
'sunos': 'who -b',
|
2018-12-11 20:30:11 +00:00
|
|
|
'vmkernel': 'grep booted /var/log/vmksummary.log | tail -n 1',
|
2019-01-08 23:12:30 +00:00
|
|
|
'aix': 'who -b',
|
2018-09-28 20:07:44 +00:00
|
|
|
}
|
|
|
|
|
2018-08-24 01:12:12 +00:00
|
|
|
SHUTDOWN_COMMANDS = {
|
2018-12-11 16:05:10 +00:00
|
|
|
'alpine': 'reboot',
|
2018-12-11 20:30:11 +00:00
|
|
|
'vmkernel': 'reboot',
|
2018-08-24 01:12:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
SHUTDOWN_COMMAND_ARGS = {
|
2018-12-11 16:05:10 +00:00
|
|
|
'alpine': '',
|
2018-08-24 01:12:12 +00:00
|
|
|
'freebsd': '-r +{delay_sec}s "{message}"',
|
2018-12-11 16:05:10 +00:00
|
|
|
'linux': DEFAULT_SHUTDOWN_COMMAND_ARGS,
|
|
|
|
'macosx': '-r +{delay_min} "{message}"',
|
2018-09-28 20:07:44 +00:00
|
|
|
'openbsd': '-r +{delay_min} "{message}"',
|
2018-12-11 16:05:10 +00:00
|
|
|
'solaris': '-y -g {delay_sec} -i 6 "{message}"',
|
|
|
|
'sunos': '-y -g {delay_sec} -i 6 "{message}"',
|
2018-12-11 20:30:11 +00:00
|
|
|
'vmkernel': '-d {delay_sec}',
|
2019-01-08 23:12:30 +00:00
|
|
|
'aix': '-Fr',
|
2018-12-11 16:05:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
TEST_COMMANDS = {
|
2018-12-11 20:30:11 +00:00
|
|
|
'solaris': 'who',
|
|
|
|
'vmkernel': 'who',
|
2018-08-24 01:12:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(ActionModule, self).__init__(*args, **kwargs)
|
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
@property
|
|
|
|
def pre_reboot_delay(self):
|
|
|
|
return self._check_delay('pre_reboot_delay', self.DEFAULT_PRE_REBOOT_DELAY)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def post_reboot_delay(self):
|
|
|
|
return self._check_delay('post_reboot_delay', self.DEFAULT_POST_REBOOT_DELAY)
|
|
|
|
|
|
|
|
def _check_delay(self, key, default):
|
|
|
|
"""Ensure that the value is positive or zero"""
|
|
|
|
value = int(self._task.args.get(key, self._task.args.get(key + '_sec', default)))
|
|
|
|
if value < 0:
|
|
|
|
value = 0
|
|
|
|
return value
|
|
|
|
|
|
|
|
def _get_value_from_facts(self, variable_name, distribution, default_value):
|
|
|
|
"""Get dist+version specific args first, then distribution, then family, lastly use default"""
|
|
|
|
attr = getattr(self, variable_name)
|
|
|
|
value = attr.get(
|
|
|
|
distribution['name'] + distribution['version'],
|
|
|
|
attr.get(
|
|
|
|
distribution['name'],
|
|
|
|
attr.get(
|
|
|
|
distribution['family'],
|
|
|
|
getattr(self, default_value))))
|
|
|
|
return value
|
|
|
|
|
|
|
|
def get_shutdown_command_args(self, distribution):
|
|
|
|
args = self._get_value_from_facts('SHUTDOWN_COMMAND_ARGS', distribution, 'DEFAULT_SHUTDOWN_COMMAND_ARGS')
|
|
|
|
# Convert seconds to minutes. If less that 60, set it to 0.
|
|
|
|
delay_min = self.pre_reboot_delay // 60
|
|
|
|
reboot_message = self._task.args.get('msg', self.DEFAULT_REBOOT_MESSAGE)
|
|
|
|
return args.format(delay_sec=self.pre_reboot_delay, delay_min=delay_min, message=reboot_message)
|
|
|
|
|
|
|
|
def get_distribution(self, task_vars):
|
|
|
|
distribution = {}
|
|
|
|
display.debug('{action}: running setup module to get distribution'.format(action=self._task.action))
|
|
|
|
module_output = self._execute_module(
|
|
|
|
task_vars=task_vars,
|
|
|
|
module_name='setup',
|
|
|
|
module_args={'gather_subset': 'min'})
|
|
|
|
try:
|
|
|
|
if module_output.get('failed', False):
|
|
|
|
raise AnsibleError('Failed to determine system distribution. {0}, {1}'.format(
|
|
|
|
to_native(module_output['module_stdout']).strip(),
|
|
|
|
to_native(module_output['module_stderr']).strip()))
|
|
|
|
distribution['name'] = module_output['ansible_facts']['ansible_distribution'].lower()
|
|
|
|
distribution['version'] = to_text(module_output['ansible_facts']['ansible_distribution_version'].split('.')[0])
|
|
|
|
distribution['family'] = to_text(module_output['ansible_facts']['ansible_os_family'].lower())
|
|
|
|
display.debug("{action}: distribution: {dist}".format(action=self._task.action, dist=distribution))
|
|
|
|
return distribution
|
|
|
|
except KeyError as ke:
|
|
|
|
raise AnsibleError('Failed to get distribution information. Missing "{0}" in output.'.format(ke.args[0]))
|
|
|
|
|
|
|
|
def get_shutdown_command(self, task_vars, distribution):
|
|
|
|
shutdown_bin = self._get_value_from_facts('SHUTDOWN_COMMANDS', distribution, 'DEFAULT_SHUTDOWN_COMMAND')
|
|
|
|
|
|
|
|
display.debug('{action}: running find module to get path for "{command}"'.format(action=self._task.action, command=shutdown_bin))
|
|
|
|
find_result = self._execute_module(
|
|
|
|
task_vars=task_vars,
|
|
|
|
module_name='find',
|
|
|
|
module_args={
|
|
|
|
'paths': ['/sbin', '/usr/sbin', '/usr/local/sbin'],
|
|
|
|
'patterns': [shutdown_bin],
|
|
|
|
'file_type': 'any'
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
full_path = [x['path'] for x in find_result['files']]
|
|
|
|
if not full_path:
|
|
|
|
raise AnsibleError('Unable to find command "{0}" in system paths.'.format(shutdown_bin))
|
|
|
|
self._shutdown_command = full_path[0]
|
|
|
|
return self._shutdown_command
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
def deprecated_args(self):
|
|
|
|
for arg, version in self.DEPRECATED_ARGS.items():
|
|
|
|
if self._task.args.get(arg) is not None:
|
2018-12-11 16:05:10 +00:00
|
|
|
display.warning("Since Ansible {version}, {arg} is no longer a valid option for {action}".format(
|
|
|
|
version=version,
|
|
|
|
arg=arg,
|
|
|
|
action=self._task.action))
|
|
|
|
|
|
|
|
def get_system_boot_time(self, distribution):
|
|
|
|
boot_time_command = self._get_value_from_facts('BOOT_TIME_COMMANDS', distribution, 'DEFAULT_BOOT_TIME_COMMAND')
|
|
|
|
display.debug("{action}: getting boot time with command: '{command}'".format(action=self._task.action, command=boot_time_command))
|
2018-09-28 20:07:44 +00:00
|
|
|
command_result = self._low_level_execute_command(boot_time_command, sudoable=self.DEFAULT_SUDOABLE)
|
2018-08-24 01:12:12 +00:00
|
|
|
|
2018-09-17 18:04:03 +00:00
|
|
|
if command_result['rc'] != 0:
|
2018-12-11 16:05:10 +00:00
|
|
|
stdout = command_result['stdout']
|
|
|
|
stderr = command_result['stderr']
|
|
|
|
raise AnsibleError("{action}: failed to get host boot time info, rc: {rc}, stdout: {out}, stderr: {err}".format(
|
|
|
|
action=self._task.action,
|
|
|
|
rc=command_result['rc'],
|
|
|
|
out=to_native(stdout),
|
|
|
|
err=to_native(stderr)))
|
|
|
|
display.debug("{action}: last boot time: {boot}".format(action=self._task.action, boot=command_result['stdout'].strip()))
|
2018-08-24 01:12:12 +00:00
|
|
|
return command_result['stdout'].strip()
|
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
def check_boot_time(self, distribution, previous_boot_time):
|
|
|
|
display.vvv("{action}: attempting to get system boot time".format(action=self._task.action))
|
2018-08-24 01:12:12 +00:00
|
|
|
connect_timeout = self._task.args.get('connect_timeout', self._task.args.get('connect_timeout_sec', self.DEFAULT_CONNECT_TIMEOUT))
|
|
|
|
|
|
|
|
# override connection timeout from defaults to custom value
|
|
|
|
if connect_timeout:
|
|
|
|
try:
|
2018-12-11 16:05:10 +00:00
|
|
|
display.debug("{action}: setting connect_timeout to {value}".format(action=self._task.action, value=connect_timeout))
|
2018-08-24 01:12:12 +00:00
|
|
|
self._connection.set_option("connection_timeout", connect_timeout)
|
|
|
|
self._connection.reset()
|
|
|
|
except AttributeError:
|
|
|
|
display.warning("Connection plugin does not allow the connection timeout to be overridden")
|
|
|
|
|
|
|
|
# try and get boot time
|
|
|
|
try:
|
2018-12-11 16:05:10 +00:00
|
|
|
current_boot_time = self.get_system_boot_time(distribution)
|
2018-08-24 01:12:12 +00:00
|
|
|
except Exception as e:
|
|
|
|
raise e
|
|
|
|
|
|
|
|
# FreeBSD returns an empty string immediately before reboot so adding a length
|
|
|
|
# check to prevent prematurely assuming system has rebooted
|
2018-12-11 16:05:10 +00:00
|
|
|
if len(current_boot_time) == 0 or current_boot_time == previous_boot_time:
|
|
|
|
raise ValueError("boot time has not changed")
|
2018-08-24 01:12:12 +00:00
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
def run_test_command(self, distribution, **kwargs):
|
|
|
|
test_command = self._task.args.get('test_command', self._get_value_from_facts('TEST_COMMANDS', distribution, 'DEFAULT_TEST_COMMAND'))
|
|
|
|
display.vvv("{action}: attempting post-reboot test command".format(action=self._task.action))
|
|
|
|
display.debug("{action}: attempting post-reboot test command '{command}'".format(action=self._task.action, command=test_command))
|
2018-08-28 21:25:37 +00:00
|
|
|
try:
|
|
|
|
command_result = self._low_level_execute_command(test_command, sudoable=self.DEFAULT_SUDOABLE)
|
|
|
|
except Exception:
|
|
|
|
# may need to reset the connection in case another reboot occurred
|
|
|
|
# which has invalidated our connection
|
|
|
|
try:
|
|
|
|
self._connection.reset()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
raise
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
if command_result['rc'] != 0:
|
2018-12-11 16:05:10 +00:00
|
|
|
msg = 'Test command failed: {err} {out}'.format(
|
|
|
|
err=to_native(command_result['stderr']),
|
|
|
|
out=to_native(command_result['stdout']))
|
|
|
|
raise RuntimeError(msg)
|
2018-08-24 01:12:12 +00:00
|
|
|
|
2019-02-17 21:49:40 +00:00
|
|
|
display.vvv("{action}: system successfully rebooted".format(action=self._task.action))
|
2018-08-24 01:12:12 +00:00
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
def do_until_success_or_timeout(self, action, reboot_timeout, action_desc, distribution, action_kwargs=None):
|
2018-08-24 01:12:12 +00:00
|
|
|
max_end_time = datetime.utcnow() + timedelta(seconds=reboot_timeout)
|
2018-12-11 16:05:10 +00:00
|
|
|
if action_kwargs is None:
|
|
|
|
action_kwargs = {}
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
fail_count = 0
|
|
|
|
max_fail_sleep = 12
|
|
|
|
|
|
|
|
while datetime.utcnow() < max_end_time:
|
|
|
|
try:
|
2018-12-11 16:05:10 +00:00
|
|
|
action(distribution=distribution, **action_kwargs)
|
2018-08-24 01:12:12 +00:00
|
|
|
if action_desc:
|
2018-12-11 16:05:10 +00:00
|
|
|
display.debug('{action}: {desc} success'.format(action=self._task.action, desc=action_desc))
|
2018-08-24 01:12:12 +00:00
|
|
|
return
|
|
|
|
except Exception as e:
|
2018-11-27 21:48:57 +00:00
|
|
|
if isinstance(e, AnsibleConnectionFailure):
|
|
|
|
try:
|
|
|
|
self._connection.reset()
|
|
|
|
except AnsibleConnectionFailure:
|
|
|
|
pass
|
2018-08-24 01:12:12 +00:00
|
|
|
# Use exponential backoff with a max timout, plus a little bit of randomness
|
|
|
|
random_int = random.randint(0, 1000) / 1000
|
|
|
|
fail_sleep = 2 ** fail_count + random_int
|
|
|
|
if fail_sleep > max_fail_sleep:
|
|
|
|
|
|
|
|
fail_sleep = max_fail_sleep + random_int
|
|
|
|
if action_desc:
|
2018-11-27 21:48:57 +00:00
|
|
|
try:
|
|
|
|
error = to_text(e).splitlines()[-1]
|
2018-12-04 19:12:00 +00:00
|
|
|
except IndexError as e:
|
2018-11-27 21:48:57 +00:00
|
|
|
error = to_text(e)
|
2018-12-11 16:05:10 +00:00
|
|
|
display.debug("{action}: {desc} fail '{err}', retrying in {sleep:.4} seconds...".format(
|
|
|
|
action=self._task.action,
|
|
|
|
desc=action_desc,
|
|
|
|
err=error,
|
|
|
|
sleep=fail_sleep))
|
2018-08-24 01:12:12 +00:00
|
|
|
fail_count += 1
|
|
|
|
time.sleep(fail_sleep)
|
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
raise TimedOutException('Timed out waiting for {desc} (timeout={timeout})'.format(desc=action_desc, timeout=reboot_timeout))
|
2018-11-12 16:30:46 +00:00
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
def perform_reboot(self, task_vars, distribution):
|
2018-08-24 01:12:12 +00:00
|
|
|
result = {}
|
2018-11-12 16:30:46 +00:00
|
|
|
reboot_result = {}
|
2018-12-11 16:05:10 +00:00
|
|
|
shutdown_command = self.get_shutdown_command(task_vars, distribution)
|
|
|
|
shutdown_command_args = self.get_shutdown_command_args(distribution)
|
|
|
|
reboot_command = '{0} {1}'.format(shutdown_command, shutdown_command_args)
|
2018-11-12 16:30:46 +00:00
|
|
|
|
|
|
|
try:
|
2018-12-11 16:05:10 +00:00
|
|
|
display.vvv("{action}: rebooting server...".format(action=self._task.action))
|
|
|
|
display.debug("{action}: rebooting server with command '{command}'".format(action=self._task.action, command=reboot_command))
|
|
|
|
reboot_result = self._low_level_execute_command(reboot_command, sudoable=self.DEFAULT_SUDOABLE)
|
2018-11-12 16:30:46 +00:00
|
|
|
except AnsibleConnectionFailure as e:
|
|
|
|
# If the connection is closed too quickly due to the system being shutdown, carry on
|
2018-12-11 16:05:10 +00:00
|
|
|
display.debug('{action}: AnsibleConnectionFailure caught and handled: {error}'.format(action=self._task.action, error=to_native(e)))
|
2018-11-12 16:30:46 +00:00
|
|
|
reboot_result['rc'] = 0
|
|
|
|
|
2018-08-24 01:12:12 +00:00
|
|
|
result['start'] = datetime.utcnow()
|
|
|
|
|
|
|
|
if reboot_result['rc'] != 0:
|
|
|
|
result['failed'] = True
|
|
|
|
result['rebooted'] = False
|
2018-12-11 16:05:10 +00:00
|
|
|
result['msg'] = "Reboot command failed. Error was {stdout}, {stderr}".format(
|
|
|
|
stdout=to_native(reboot_result['stdout'].strip()),
|
|
|
|
stderr=to_native(reboot_result['stderr'].strip()))
|
2018-08-24 01:12:12 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
result['failed'] = False
|
|
|
|
return result
|
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
def validate_reboot(self, distribution, original_connection_timeout=None, action_kwargs=None):
|
|
|
|
display.vvv('{action}: validating reboot'.format(action=self._task.action))
|
2018-08-24 01:12:12 +00:00
|
|
|
result = {}
|
|
|
|
|
|
|
|
try:
|
|
|
|
# keep on checking system boot_time with short connection responses
|
|
|
|
reboot_timeout = int(self._task.args.get('reboot_timeout', self._task.args.get('reboot_timeout_sec', self.DEFAULT_REBOOT_TIMEOUT)))
|
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
self.do_until_success_or_timeout(
|
|
|
|
action=self.check_boot_time,
|
|
|
|
action_desc="last boot time check",
|
|
|
|
reboot_timeout=reboot_timeout,
|
|
|
|
distribution=distribution,
|
|
|
|
action_kwargs=action_kwargs)
|
|
|
|
|
2019-01-17 15:45:41 +00:00
|
|
|
# Get the connect_timeout set on the connection to compare to the original
|
|
|
|
try:
|
|
|
|
connect_timeout = self._connection.get_option('connection_timeout')
|
Become plugins (#50991)
* [WIP] become plugins
Move from hardcoded method to plugins for ease of use, expansion and overrides
- load into connection as it is going to be the main consumer
- play_context will also use to keep backwards compat API
- ensure shell is used to construct commands when needed
- migrate settings remove from base config in favor of plugin specific configs
- cleanup ansible-doc
- add become plugin docs
- remove deprecated sudo/su code and keywords
- adjust become options for cli
- set plugin options from context
- ensure config defs are avaialbe before instance
- refactored getting the shell plugin, fixed tests
- changed into regex as they were string matching, which does not work with random string generation
- explicitly set flags for play context tests
- moved plugin loading up front
- now loads for basedir also
- allow pyc/o for non m modules
- fixes to tests and some plugins
- migrate to play objects fro play_context
- simiplify gathering
- added utf8 headers
- moved option setting
- add fail msg to dzdo
- use tuple for multiple options on fail/missing
- fix relative plugin paths
- shift from play context to play
- all tasks already inherit this from play directly
- remove obsolete 'set play'
- correct environment handling
- add wrap_exe option to pfexec
- fix runas to noop
- fixed setting play context
- added password configs
- removed required false
- remove from doc building till they are ready
future development:
- deal with 'enable' and 'runas' which are not 'command wrappers' but 'state flags' and currently hardcoded in diff subsystems
* cleanup
remove callers to removed func
removed --sudo cli doc refs
remove runas become_exe
ensure keyerorr on plugin
also fix backwards compat, missing method is attributeerror, not ansible error
get remote_user consistently
ignore missing system_tmpdirs on plugin load
correct config precedence
add deprecation
fix networking imports
backwards compat for plugins using BECOME_METHODS
* Port become_plugins to context.CLIARGS
This is a work in progress:
* Stop passing options around everywhere as we can use context.CLIARGS
instead
* Refactor make_become_commands as asked for by alikins
* Typo in comment fix
* Stop loading values from the cli in more than one place
Both play and play_context were saving default values from the cli
arguments directly. This changes things so that the default values are
loaded into the play and then play_context takes them from there.
* Rename BECOME_PLUGIN_PATH to DEFAULT_BECOME_PLUGIN_PATH
As alikins said, all other plugin paths are named
DEFAULT_plugintype_PLUGIN_PATH. If we're going to rename these, that
should be done all at one time rather than piecemeal.
* One to throw away
This is a set of hacks to get setting FieldAttribute defaults to command
line args to work. It's not fully done yet.
After talking it over with sivel and jimi-c this should be done by
fixing FieldAttributeBase and _get_parent_attribute() calls to do the
right thing when there is a non-None default.
What we want to be able to do ideally is something like this:
class Base(FieldAttributeBase):
_check_mode = FieldAttribute([..] default=lambda: context.CLIARGS['check'])
class Play(Base):
# lambda so that we have a chance to parse the command line args
# before we get here. In the future we might be able to restructure
# this so that the cli parsing code runs before these classes are
# defined.
class Task(Base):
pass
And still have a playbook like this function:
---
- hosts:
tasks:
- command: whoami
check_mode: True
(The check_mode test that is added as a separate commit in this PR will
let you test variations on this case).
There's a few separate reasons that the code doesn't let us do this or
a non-ugly workaround for this as written right now. The fix that
jimi-c, sivel, and I talked about may let us do this or it may still
require a workaround (but less ugly) (having one class that has the
FieldAttributes with default values and one class that inherits from
that but just overrides the FieldAttributes which now have defaults)
* Revert "One to throw away"
This reverts commit 23aa883cbed11429ef1be2a2d0ed18f83a3b8064.
* Set FieldAttr defaults directly from CLIARGS
* Remove dead code
* Move timeout directly to PlayContext, it's never needed on Play
* just for backwards compat, add a static version of BECOME_METHODS to constants
* Make the become attr on the connection public, since it's used outside of the connection
* Logic fix
* Nuke connection testing if it supports specific become methods
* Remove unused vars
* Address rebase issues
* Fix path encoding issue
* Remove unused import
* Various cleanups
* Restore network_cli check in _low_level_execute_command
* type improvements for cliargs_deferred_get and swap shallowcopy to default to False
* minor cleanups
* Allow the su plugin to work, since it doesn't define a prompt the same way
* Fix up ksu become plugin
* Only set prompt if build_become_command was called
* Add helper to assist connection plugins in knowing they need to wait for a prompt
* Fix tests and code expectations
* Doc updates
* Various additional minor cleanups
* Make doas functional
* Don't change connection signature, load become plugin from TaskExecutor
* Remove unused imports
* Add comment about setting the become plugin on the playcontext
* Fix up tests for recent changes
* Support 'Password:' natively for the doas plugin
* Make default prompts raw
* wording cleanups. ci_complete
* Remove unrelated changes
* Address spelling mistake
* Restore removed test, and udpate to use new functionality
* Add changelog fragment
* Don't hard fail in set_attributes_from_cli on missing CLI keys
* Remove unrelated change to loader
* Remove internal deprecated FieldAttributes now
* Emit deprecation warnings now
2019-02-11 17:27:44 +00:00
|
|
|
except KeyError:
|
2019-01-17 15:45:41 +00:00
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if original_connection_timeout != connect_timeout:
|
|
|
|
try:
|
|
|
|
display.debug("{action}: setting connect_timeout back to original value of {value}".format(
|
|
|
|
action=self._task.action,
|
|
|
|
value=original_connection_timeout))
|
|
|
|
self._connection.set_option("connection_timeout", original_connection_timeout)
|
|
|
|
self._connection.reset()
|
|
|
|
except (AnsibleError, AttributeError) as e:
|
|
|
|
# reset the connection to clear the custom connection timeout
|
|
|
|
display.debug("{action}: failed to reset connection_timeout back to default: {error}".format(action=self._task.action,
|
|
|
|
error=to_text(e)))
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
# finally run test command to ensure everything is working
|
|
|
|
# FUTURE: add a stability check (system must remain up for N seconds) to deal with self-multi-reboot updates
|
2018-12-11 16:05:10 +00:00
|
|
|
self.do_until_success_or_timeout(
|
|
|
|
action=self.run_test_command,
|
|
|
|
action_desc="post-reboot test command",
|
|
|
|
reboot_timeout=reboot_timeout,
|
|
|
|
distribution=distribution,
|
|
|
|
action_kwargs=action_kwargs)
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
result['rebooted'] = True
|
|
|
|
result['changed'] = True
|
|
|
|
|
|
|
|
except TimedOutException as toex:
|
|
|
|
result['failed'] = True
|
|
|
|
result['rebooted'] = True
|
|
|
|
result['msg'] = to_text(toex)
|
|
|
|
return result
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
def run(self, tmp=None, task_vars=None):
|
|
|
|
self._supports_check_mode = True
|
|
|
|
self._supports_async = True
|
|
|
|
|
|
|
|
# If running with local connection, fail so we don't reboot ourself
|
|
|
|
if self._connection.transport == 'local':
|
|
|
|
msg = 'Running {0} with local connection would reboot the control node.'.format(self._task.action)
|
2018-12-11 16:05:10 +00:00
|
|
|
return {'changed': False, 'elapsed': 0, 'rebooted': False, 'failed': True, 'msg': msg}
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
if self._play_context.check_mode:
|
2018-12-11 16:05:10 +00:00
|
|
|
return {'changed': True, 'elapsed': 0, 'rebooted': True}
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
if task_vars is None:
|
2018-12-11 16:05:10 +00:00
|
|
|
task_vars = {}
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
self.deprecated_args()
|
|
|
|
|
|
|
|
result = super(ActionModule, self).run(tmp, task_vars)
|
|
|
|
|
|
|
|
if result.get('skipped', False) or result.get('failed', False):
|
|
|
|
return result
|
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
distribution = self.get_distribution(task_vars)
|
|
|
|
|
2018-08-24 01:12:12 +00:00
|
|
|
# Get current boot time
|
|
|
|
try:
|
2018-12-11 16:05:10 +00:00
|
|
|
previous_boot_time = self.get_system_boot_time(distribution)
|
2018-08-24 01:12:12 +00:00
|
|
|
except Exception as e:
|
|
|
|
result['failed'] = True
|
|
|
|
result['reboot'] = False
|
|
|
|
result['msg'] = to_text(e)
|
|
|
|
return result
|
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
# Get the original connection_timeout option var so it can be reset after
|
|
|
|
original_connection_timeout = None
|
|
|
|
try:
|
|
|
|
original_connection_timeout = self._connection.get_option('connection_timeout')
|
|
|
|
display.debug("{action}: saving original connect_timeout of {timeout}".format(action=self._task.action, timeout=original_connection_timeout))
|
Become plugins (#50991)
* [WIP] become plugins
Move from hardcoded method to plugins for ease of use, expansion and overrides
- load into connection as it is going to be the main consumer
- play_context will also use to keep backwards compat API
- ensure shell is used to construct commands when needed
- migrate settings remove from base config in favor of plugin specific configs
- cleanup ansible-doc
- add become plugin docs
- remove deprecated sudo/su code and keywords
- adjust become options for cli
- set plugin options from context
- ensure config defs are avaialbe before instance
- refactored getting the shell plugin, fixed tests
- changed into regex as they were string matching, which does not work with random string generation
- explicitly set flags for play context tests
- moved plugin loading up front
- now loads for basedir also
- allow pyc/o for non m modules
- fixes to tests and some plugins
- migrate to play objects fro play_context
- simiplify gathering
- added utf8 headers
- moved option setting
- add fail msg to dzdo
- use tuple for multiple options on fail/missing
- fix relative plugin paths
- shift from play context to play
- all tasks already inherit this from play directly
- remove obsolete 'set play'
- correct environment handling
- add wrap_exe option to pfexec
- fix runas to noop
- fixed setting play context
- added password configs
- removed required false
- remove from doc building till they are ready
future development:
- deal with 'enable' and 'runas' which are not 'command wrappers' but 'state flags' and currently hardcoded in diff subsystems
* cleanup
remove callers to removed func
removed --sudo cli doc refs
remove runas become_exe
ensure keyerorr on plugin
also fix backwards compat, missing method is attributeerror, not ansible error
get remote_user consistently
ignore missing system_tmpdirs on plugin load
correct config precedence
add deprecation
fix networking imports
backwards compat for plugins using BECOME_METHODS
* Port become_plugins to context.CLIARGS
This is a work in progress:
* Stop passing options around everywhere as we can use context.CLIARGS
instead
* Refactor make_become_commands as asked for by alikins
* Typo in comment fix
* Stop loading values from the cli in more than one place
Both play and play_context were saving default values from the cli
arguments directly. This changes things so that the default values are
loaded into the play and then play_context takes them from there.
* Rename BECOME_PLUGIN_PATH to DEFAULT_BECOME_PLUGIN_PATH
As alikins said, all other plugin paths are named
DEFAULT_plugintype_PLUGIN_PATH. If we're going to rename these, that
should be done all at one time rather than piecemeal.
* One to throw away
This is a set of hacks to get setting FieldAttribute defaults to command
line args to work. It's not fully done yet.
After talking it over with sivel and jimi-c this should be done by
fixing FieldAttributeBase and _get_parent_attribute() calls to do the
right thing when there is a non-None default.
What we want to be able to do ideally is something like this:
class Base(FieldAttributeBase):
_check_mode = FieldAttribute([..] default=lambda: context.CLIARGS['check'])
class Play(Base):
# lambda so that we have a chance to parse the command line args
# before we get here. In the future we might be able to restructure
# this so that the cli parsing code runs before these classes are
# defined.
class Task(Base):
pass
And still have a playbook like this function:
---
- hosts:
tasks:
- command: whoami
check_mode: True
(The check_mode test that is added as a separate commit in this PR will
let you test variations on this case).
There's a few separate reasons that the code doesn't let us do this or
a non-ugly workaround for this as written right now. The fix that
jimi-c, sivel, and I talked about may let us do this or it may still
require a workaround (but less ugly) (having one class that has the
FieldAttributes with default values and one class that inherits from
that but just overrides the FieldAttributes which now have defaults)
* Revert "One to throw away"
This reverts commit 23aa883cbed11429ef1be2a2d0ed18f83a3b8064.
* Set FieldAttr defaults directly from CLIARGS
* Remove dead code
* Move timeout directly to PlayContext, it's never needed on Play
* just for backwards compat, add a static version of BECOME_METHODS to constants
* Make the become attr on the connection public, since it's used outside of the connection
* Logic fix
* Nuke connection testing if it supports specific become methods
* Remove unused vars
* Address rebase issues
* Fix path encoding issue
* Remove unused import
* Various cleanups
* Restore network_cli check in _low_level_execute_command
* type improvements for cliargs_deferred_get and swap shallowcopy to default to False
* minor cleanups
* Allow the su plugin to work, since it doesn't define a prompt the same way
* Fix up ksu become plugin
* Only set prompt if build_become_command was called
* Add helper to assist connection plugins in knowing they need to wait for a prompt
* Fix tests and code expectations
* Doc updates
* Various additional minor cleanups
* Make doas functional
* Don't change connection signature, load become plugin from TaskExecutor
* Remove unused imports
* Add comment about setting the become plugin on the playcontext
* Fix up tests for recent changes
* Support 'Password:' natively for the doas plugin
* Make default prompts raw
* wording cleanups. ci_complete
* Remove unrelated changes
* Address spelling mistake
* Restore removed test, and udpate to use new functionality
* Add changelog fragment
* Don't hard fail in set_attributes_from_cli on missing CLI keys
* Remove unrelated change to loader
* Remove internal deprecated FieldAttributes now
* Emit deprecation warnings now
2019-02-11 17:27:44 +00:00
|
|
|
except KeyError:
|
2018-12-11 16:05:10 +00:00
|
|
|
display.debug("{action}: connect_timeout connection option has not been set".format(action=self._task.action))
|
2018-08-24 01:12:12 +00:00
|
|
|
# Initiate reboot
|
2018-12-11 16:05:10 +00:00
|
|
|
reboot_result = self.perform_reboot(task_vars, distribution)
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
if reboot_result['failed']:
|
|
|
|
result = reboot_result
|
|
|
|
elapsed = datetime.utcnow() - reboot_result['start']
|
|
|
|
result['elapsed'] = elapsed.seconds
|
|
|
|
return result
|
|
|
|
|
2018-12-11 16:05:10 +00:00
|
|
|
if self.post_reboot_delay != 0:
|
|
|
|
display.debug("{action}: waiting an additional {delay} seconds".format(action=self._task.action, delay=self.post_reboot_delay))
|
|
|
|
display.vvv("{action}: waiting an additional {delay} seconds".format(action=self._task.action, delay=self.post_reboot_delay))
|
|
|
|
time.sleep(self.post_reboot_delay)
|
2018-10-04 19:44:50 +00:00
|
|
|
|
2018-08-24 01:12:12 +00:00
|
|
|
# Make sure reboot was successful
|
2018-12-11 16:05:10 +00:00
|
|
|
result = self.validate_reboot(distribution, original_connection_timeout, action_kwargs={'previous_boot_time': previous_boot_time})
|
2018-08-24 01:12:12 +00:00
|
|
|
|
|
|
|
elapsed = datetime.utcnow() - reboot_result['start']
|
|
|
|
result['elapsed'] = elapsed.seconds
|
|
|
|
|
|
|
|
return result
|