| 1 |
# Copyright (c) 2020, Amin Vakil <[email protected]> |
| 2 |
# Copyright (c) 2016-2018, Matt Davis <[email protected]> |
| 3 |
# Copyright (c) 2018, Sam Doran <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import typing as t |
| 10 |
|
| 11 |
from ansible.errors import AnsibleConnectionFailure, AnsibleError |
| 12 |
from ansible.module_utils.common.collections import is_string |
| 13 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 14 |
from ansible.plugins.action import ActionBase |
| 15 |
from ansible.utils.display import Display |
| 16 |
|
| 17 |
if t.TYPE_CHECKING: |
| 18 |
|
| 19 |
class Distribution(t.TypedDict): |
| 20 |
name: str |
| 21 |
version: str |
| 22 |
family: str |
| 23 |
|
| 24 |
|
| 25 |
display = Display() |
| 26 |
|
| 27 |
|
| 28 |
class TimedOutException(Exception): |
| 29 |
pass |
| 30 |
|
| 31 |
|
| 32 |
class ActionModule(ActionBase): |
| 33 |
TRANSFERS_FILES = False |
| 34 |
_VALID_ARGS = frozenset(("msg", "delay", "search_paths")) |
| 35 |
|
| 36 |
DEFAULT_CONNECT_TIMEOUT = None |
| 37 |
DEFAULT_PRE_SHUTDOWN_DELAY = 0 |
| 38 |
DEFAULT_SHUTDOWN_MESSAGE = "Shut down initiated by Ansible" |
| 39 |
DEFAULT_SHUTDOWN_COMMAND = "shutdown" |
| 40 |
DEFAULT_SHUTDOWN_COMMAND_ARGS = '-h {delay_min} "{message}"' |
| 41 |
DEFAULT_SUDOABLE = True |
| 42 |
|
| 43 |
SHUTDOWN_COMMANDS = { |
| 44 |
"alpine": "poweroff", |
| 45 |
"vmkernel": "halt", |
| 46 |
} |
| 47 |
|
| 48 |
SHUTDOWN_COMMAND_ARGS = { |
| 49 |
"alpine": "", |
| 50 |
"void": '-h +{delay_min} "{message}"', |
| 51 |
"freebsd": '-p +{delay_sec}s "{message}"', |
| 52 |
"linux": DEFAULT_SHUTDOWN_COMMAND_ARGS, |
| 53 |
"macosx": '-h +{delay_min} "{message}"', |
| 54 |
"openbsd": '-h +{delay_min} "{message}"', |
| 55 |
"solaris": '-y -g {delay_sec} -i 5 "{message}"', |
| 56 |
"sunos": '-y -g {delay_sec} -i 5 "{message}"', |
| 57 |
"vmkernel": "-d {delay_sec}", |
| 58 |
"aix": "-Fh", |
| 59 |
} |
| 60 |
|
| 61 |
def __init__(self, *args, **kwargs): |
| 62 |
super().__init__(*args, **kwargs) |
| 63 |
|
| 64 |
@property |
| 65 |
def delay(self): |
| 66 |
return self._check_delay("delay", self.DEFAULT_PRE_SHUTDOWN_DELAY) |
| 67 |
|
| 68 |
def _check_delay(self, key: str, default: int) -> int: |
| 69 |
"""Ensure that the value is positive or zero""" |
| 70 |
value = int(self._task.args.get(key, default)) |
| 71 |
if value < 0: |
| 72 |
value = 0 |
| 73 |
return value |
| 74 |
|
| 75 |
@staticmethod |
| 76 |
def _get_value_from_facts(data: dict[str, str], distribution: Distribution, default_value: str) -> str: |
| 77 |
"""Get dist+version specific args first, then distribution, then family, lastly use default""" |
| 78 |
return data.get( |
| 79 |
distribution["name"] + distribution["version"], |
| 80 |
data.get(distribution["name"], data.get(distribution["family"], default_value)), |
| 81 |
) |
| 82 |
|
| 83 |
def get_distribution(self, task_vars: dict[str, t.Any]) -> Distribution: |
| 84 |
# FIXME: only execute the module if we don't already have the facts we need |
| 85 |
display.debug(f"{self._task.action}: running setup module to get distribution") |
| 86 |
module_output = self._execute_module( |
| 87 |
task_vars=task_vars, module_name="ansible.legacy.setup", module_args={"gather_subset": "min"} |
| 88 |
) |
| 89 |
try: |
| 90 |
if module_output.get("failed", False): |
| 91 |
raise AnsibleError( |
| 92 |
f"Failed to determine system distribution. {to_native(module_output['module_stdout'])}, {to_native(module_output['module_stderr'])}" |
| 93 |
) |
| 94 |
# For some reason, ansible-core insists of using "object" for "arbitrary JSON", which makes it very awkward to use the result... |
| 95 |
ansible_facts: dict[str, t.Any] = module_output["ansible_facts"] # type: ignore |
| 96 |
distribution: Distribution = { |
| 97 |
"name": ansible_facts["ansible_distribution"].lower(), |
| 98 |
"version": to_text(ansible_facts["ansible_distribution_version"].split(".")[0]), |
| 99 |
"family": to_text(ansible_facts["ansible_os_family"].lower()), |
| 100 |
} |
| 101 |
display.debug(f"{self._task.action}: distribution: {distribution}") |
| 102 |
return distribution |
| 103 |
except KeyError as ke: |
| 104 |
raise AnsibleError(f'Failed to get distribution information. Missing "{ke.args[0]}" in output.') from ke |
| 105 |
|
| 106 |
def get_shutdown_command(self, task_vars: dict[str, t.Any], distribution: Distribution) -> str: |
| 107 |
def find_command(command: str, find_search_paths: list[str]) -> list[str]: |
| 108 |
display.debug( |
| 109 |
f'{self._task.action}: running find module looking in {find_search_paths} to get path for "{command}"' |
| 110 |
) |
| 111 |
find_result = self._execute_module( |
| 112 |
task_vars=task_vars, |
| 113 |
# prevent collection search by calling with ansible.legacy (still allows library/ override of find) |
| 114 |
module_name="ansible.legacy.find", |
| 115 |
module_args={"paths": find_search_paths, "patterns": [command], "file_type": "any"}, |
| 116 |
) |
| 117 |
files: list[dict[str, t.Any]] = find_result["files"] # type: ignore |
| 118 |
return [x["path"] for x in files] |
| 119 |
|
| 120 |
shutdown_bin = self._get_value_from_facts(self.SHUTDOWN_COMMANDS, distribution, self.DEFAULT_SHUTDOWN_COMMAND) |
| 121 |
default_search_paths = ["/sbin", "/usr/sbin", "/usr/local/sbin"] |
| 122 |
search_paths = self._task.args.get("search_paths", default_search_paths) |
| 123 |
|
| 124 |
# FIXME: switch all this to user arg spec validation methods when they are available |
| 125 |
# Convert bare strings to a list |
| 126 |
if is_string(search_paths): |
| 127 |
search_paths = [search_paths] |
| 128 |
|
| 129 |
try: |
| 130 |
incorrect_type = any(not is_string(x) for x in search_paths) |
| 131 |
if not isinstance(search_paths, list) or incorrect_type: |
| 132 |
raise TypeError |
| 133 |
except TypeError as e: |
| 134 |
# Error if we didn't get a list |
| 135 |
err_msg = f"'search_paths' must be a string or flat list of strings, got {search_paths}" |
| 136 |
raise AnsibleError(err_msg) from e |
| 137 |
|
| 138 |
full_path = find_command(shutdown_bin, search_paths) # find the path to the shutdown command |
| 139 |
if not full_path: # if we could not find the shutdown command |
| 140 |
# tell the user we will try with systemd |
| 141 |
display.vvv( |
| 142 |
f'Unable to find command "{shutdown_bin}" in search paths: {search_paths}, will attempt a shutdown using systemd directly.' |
| 143 |
) |
| 144 |
systemctl_search_paths = ["/bin", "/usr/bin"] |
| 145 |
full_path = find_command("systemctl", systemctl_search_paths) # find the path to the systemctl command |
| 146 |
if not full_path: # if we couldn't find systemctl |
| 147 |
raise AnsibleError( |
| 148 |
f'Could not find command "{shutdown_bin}" in search paths: {search_paths} or systemctl' |
| 149 |
f" command in search paths: {systemctl_search_paths}, unable to shutdown." |
| 150 |
) # we give up here |
| 151 |
else: |
| 152 |
return f"{full_path[0]} poweroff" # done, since we cannot use args with systemd shutdown |
| 153 |
|
| 154 |
# systemd case taken care of, here we add args to the command |
| 155 |
args = self._get_value_from_facts(self.SHUTDOWN_COMMAND_ARGS, distribution, self.DEFAULT_SHUTDOWN_COMMAND_ARGS) |
| 156 |
# Convert seconds to minutes. If less that 60, set it to 0. |
| 157 |
delay_sec = self.delay |
| 158 |
shutdown_message = self._task.args.get("msg", self.DEFAULT_SHUTDOWN_MESSAGE) |
| 159 |
|
| 160 |
af = args.format(delay_sec=delay_sec, delay_min=delay_sec // 60, message=shutdown_message) |
| 161 |
return f"{full_path[0]} {af}" |
| 162 |
|
| 163 |
def perform_shutdown(self, task_vars, distribution) -> dict[str, t.Any]: |
| 164 |
result: dict[str, t.Any] = {} |
| 165 |
shutdown_result: dict[str, t.Any] = {} |
| 166 |
shutdown_command_exec = self.get_shutdown_command(task_vars, distribution) |
| 167 |
|
| 168 |
self.cleanup(force=True) |
| 169 |
try: |
| 170 |
display.vvv(f"{self._task.action}: shutting down server...") |
| 171 |
display.debug(f"{self._task.action}: shutting down server with command '{shutdown_command_exec}'") |
| 172 |
if self._play_context.check_mode: |
| 173 |
shutdown_result["rc"] = 0 |
| 174 |
else: |
| 175 |
shutdown_result.update( |
| 176 |
self._low_level_execute_command(shutdown_command_exec, sudoable=self.DEFAULT_SUDOABLE) |
| 177 |
) |
| 178 |
except AnsibleConnectionFailure as e: |
| 179 |
# If the connection is closed too quickly due to the system being shutdown, carry on |
| 180 |
display.debug(f"{self._task.action}: AnsibleConnectionFailure caught and handled: {e}") |
| 181 |
shutdown_result["rc"] = 0 |
| 182 |
|
| 183 |
if shutdown_result["rc"] != 0: |
| 184 |
result["failed"] = True |
| 185 |
result["shutdown"] = False |
| 186 |
result["msg"] = ( |
| 187 |
f"Shutdown command failed. Error was {to_native(shutdown_result['stdout'])}, {to_native(shutdown_result['stderr'])}" |
| 188 |
) |
| 189 |
return result |
| 190 |
|
| 191 |
result["failed"] = False |
| 192 |
result["shutdown_command"] = shutdown_command_exec |
| 193 |
return result |
| 194 |
|
| 195 |
def run(self, tmp: str | None = None, task_vars: dict[str, t.Any] | None = None) -> dict[str, t.Any]: |
| 196 |
self._supports_check_mode = True |
| 197 |
self._supports_async = True |
| 198 |
|
| 199 |
# If running with local connection, fail so we don't shutdown ourself |
| 200 |
if self._connection.transport == "local" and (not self._play_context.check_mode): |
| 201 |
msg = f"Running {self._task.action} with local connection would shutdown the control node." |
| 202 |
return {"changed": False, "elapsed": 0, "shutdown": False, "failed": True, "msg": msg} |
| 203 |
|
| 204 |
if task_vars is None: |
| 205 |
task_vars = {} |
| 206 |
|
| 207 |
result = super().run(tmp, task_vars) |
| 208 |
|
| 209 |
if result.get("skipped", False) or result.get("failed", False): |
| 210 |
return result |
| 211 |
|
| 212 |
distribution = self.get_distribution(task_vars) |
| 213 |
|
| 214 |
# Initiate shutdown |
| 215 |
shutdown_result = self.perform_shutdown(task_vars, distribution) |
| 216 |
|
| 217 |
if shutdown_result["failed"]: |
| 218 |
result = shutdown_result |
| 219 |
return result |
| 220 |
|
| 221 |
result["shutdown"] = True |
| 222 |
result["changed"] = True |
| 223 |
result["shutdown_command"] = shutdown_result["shutdown_command"] |
| 224 |
|
| 225 |
return result |