| 1 |
# Copyright (c) 2020, quidame <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import time |
| 8 |
import typing as t |
| 9 |
|
| 10 |
from ansible.errors import AnsibleActionFail, AnsibleConnectionFailure |
| 11 |
from ansible.plugins.action import ActionBase |
| 12 |
from ansible.utils.display import Display |
| 13 |
from ansible.utils.vars import merge_hash |
| 14 |
|
| 15 |
display = Display() |
| 16 |
|
| 17 |
|
| 18 |
class ActionModule(ActionBase): |
| 19 |
# Keep internal params away from user interactions |
| 20 |
_VALID_ARGS = frozenset(("path", "state", "table", "noflush", "counters", "modprobe", "ip_version", "wait")) |
| 21 |
DEFAULT_SUDOABLE = True |
| 22 |
|
| 23 |
@staticmethod |
| 24 |
def msg_error__async_and_poll_not_zero(task_poll, task_async, max_timeout) -> str: |
| 25 |
return ( |
| 26 |
"This module doesn't support async>0 and poll>0 when its 'state' param " |
| 27 |
"is set to 'restored'. To enable its rollback feature (that needs the " |
| 28 |
"module to run asynchronously on the remote), please set task attribute " |
| 29 |
f"'poll' (={task_poll}) to 0, and 'async' (={task_async}) to a value >2 and not greater than " |
| 30 |
f"'ansible_timeout' (={max_timeout}) (recommended)." |
| 31 |
) |
| 32 |
|
| 33 |
@staticmethod |
| 34 |
def msg_warning__no_async_is_no_rollback(task_poll, task_async, max_timeout) -> str: |
| 35 |
return ( |
| 36 |
"Attempts to restore iptables state without rollback in case of mistake " |
| 37 |
"may lead the ansible controller to loose access to the hosts and never " |
| 38 |
"regain it before fixing firewall rules through a serial console, or any " |
| 39 |
f"other way except SSH. Please set task attribute 'poll' (={task_poll}) to 0, and " |
| 40 |
f"'async' (={task_async}) to a value >2 and not greater than 'ansible_timeout' (={max_timeout}) " |
| 41 |
"(recommended)." |
| 42 |
) |
| 43 |
|
| 44 |
@staticmethod |
| 45 |
def msg_warning__async_greater_than_timeout(task_poll, task_async, max_timeout) -> str: |
| 46 |
return ( |
| 47 |
"You attempt to restore iptables state with rollback in case of mistake, " |
| 48 |
"but with settings that will lead this rollback to happen AFTER that the " |
| 49 |
"controller will reach its own timeout. Please set task attribute 'poll' " |
| 50 |
f"(={task_poll}) to 0, and 'async' (={task_async}) to a value >2 and not greater than " |
| 51 |
f"'ansible_timeout' (={max_timeout}) (recommended)." |
| 52 |
) |
| 53 |
|
| 54 |
def _async_result( |
| 55 |
self, async_status_args: dict[str, t.Any], task_vars: dict[str, t.Any], timeout: int |
| 56 |
) -> dict[str, t.Any]: |
| 57 |
""" |
| 58 |
Retrieve results of the asynchronous task, and display them in place of |
| 59 |
the async wrapper results (those with the ansible_job_id key). |
| 60 |
""" |
| 61 |
async_status = self._task.copy() |
| 62 |
async_status.args = async_status_args |
| 63 |
async_status.action = "ansible.builtin.async_status" |
| 64 |
async_status.async_val = 0 |
| 65 |
async_action = self._shared_loader_obj.action_loader.get( |
| 66 |
async_status.action, |
| 67 |
task=async_status, |
| 68 |
connection=self._connection, |
| 69 |
play_context=self._play_context, |
| 70 |
loader=self._loader, |
| 71 |
templar=self._templar, |
| 72 |
shared_loader_obj=self._shared_loader_obj, |
| 73 |
) |
| 74 |
|
| 75 |
if async_status.args["mode"] == "cleanup": |
| 76 |
return async_action.run(task_vars=task_vars) |
| 77 |
|
| 78 |
# At least one iteration is required, even if timeout is 0. |
| 79 |
for dummy in range(max(1, timeout)): |
| 80 |
async_result = async_action.run(task_vars=task_vars) |
| 81 |
if async_result.get("finished", 0) == 1: |
| 82 |
break |
| 83 |
time.sleep(min(1, timeout)) |
| 84 |
|
| 85 |
return async_result |
| 86 |
|
| 87 |
def run(self, tmp: str | None = None, task_vars: dict[str, t.Any] | None = None) -> dict[str, t.Any]: |
| 88 |
self._supports_check_mode = True |
| 89 |
self._supports_async = True |
| 90 |
|
| 91 |
if task_vars is None: |
| 92 |
task_vars = {} |
| 93 |
|
| 94 |
result = super().run(tmp, task_vars) |
| 95 |
del tmp # tmp no longer has any effect |
| 96 |
|
| 97 |
if not result.get("skipped"): |
| 98 |
# FUTURE: better to let _execute_module calculate this internally? |
| 99 |
wrap_async = self._task.async_val and not self._connection.has_native_async |
| 100 |
|
| 101 |
# Set short names for values we'll have to compare or reuse |
| 102 |
task_poll = self._task.poll |
| 103 |
task_async = self._task.async_val |
| 104 |
check_mode = self._play_context.check_mode |
| 105 |
max_timeout = self._connection._play_context.timeout |
| 106 |
module_args = self._task.args |
| 107 |
|
| 108 |
async_status_args = {} |
| 109 |
starter_cmd = None |
| 110 |
confirm_cmd = None |
| 111 |
|
| 112 |
if module_args.get("state", None) == "restored": |
| 113 |
if not wrap_async: |
| 114 |
if not check_mode: |
| 115 |
display.warning(self.msg_error__async_and_poll_not_zero(task_poll, task_async, max_timeout)) |
| 116 |
elif task_poll: |
| 117 |
raise AnsibleActionFail( |
| 118 |
self.msg_warning__no_async_is_no_rollback(task_poll, task_async, max_timeout) |
| 119 |
) |
| 120 |
else: |
| 121 |
if task_async > max_timeout and not check_mode: |
| 122 |
display.warning( |
| 123 |
self.msg_warning__async_greater_than_timeout(task_poll, task_async, max_timeout) |
| 124 |
) |
| 125 |
|
| 126 |
# inject the async directory based on the shell option into the |
| 127 |
# module args |
| 128 |
async_dir = self.get_shell_option("async_dir", default="~/.ansible_async") |
| 129 |
|
| 130 |
# Bind the loop max duration to consistent values on both |
| 131 |
# remote and local sides (if not the same, make the loop |
| 132 |
# longer on the controller); and set a backup file path. |
| 133 |
module_args["_timeout"] = task_async |
| 134 |
module_args["_back"] = f"{async_dir}/iptables.state" |
| 135 |
async_status_args = dict(mode="status") |
| 136 |
confirm_cmd = f"rm -f {module_args['_back']}" |
| 137 |
starter_cmd = f"touch {module_args['_back']}.starter" |
| 138 |
remaining_time = max(task_async, max_timeout) |
| 139 |
|
| 140 |
# do work! |
| 141 |
result = merge_hash( |
| 142 |
result, self._execute_module(module_args=module_args, task_vars=task_vars, wrap_async=wrap_async) |
| 143 |
) |
| 144 |
|
| 145 |
# Then the 3-steps "go ahead or rollback": |
| 146 |
# 1. Catch early errors of the module (in asynchronous task) if any. |
| 147 |
# Touch a file on the target to signal the module to process now. |
| 148 |
# 2. Reset connection to ensure a persistent one will not be reused. |
| 149 |
# 3. Confirm the restored state by removing the backup on the remote. |
| 150 |
# Retrieve the results of the asynchronous task to return them. |
| 151 |
if starter_cmd is not None and confirm_cmd is not None: |
| 152 |
async_status_args["jid"] = result.get("ansible_job_id", None) |
| 153 |
if async_status_args["jid"] is None: |
| 154 |
raise AnsibleActionFail("Unable to get 'ansible_job_id'.") |
| 155 |
|
| 156 |
# Catch early errors due to missing mandatory option, bad |
| 157 |
# option type/value, missing required system command, etc. |
| 158 |
result = merge_hash(result, self._async_result(async_status_args, task_vars, 0)) |
| 159 |
|
| 160 |
# The module is aware to not process the main iptables-restore |
| 161 |
# command before finding (and deleting) the 'starter' cookie on |
| 162 |
# the host, so the previous query will not reach ssh timeout. |
| 163 |
self._low_level_execute_command(starter_cmd, sudoable=self.DEFAULT_SUDOABLE) |
| 164 |
|
| 165 |
# As the main command is not yet executed on the target, here |
| 166 |
# 'finished' means 'failed before main command be executed'. |
| 167 |
if not result["finished"]: |
| 168 |
try: |
| 169 |
self._connection.reset() |
| 170 |
except AttributeError: |
| 171 |
pass |
| 172 |
|
| 173 |
for dummy in range(max_timeout): |
| 174 |
time.sleep(1) |
| 175 |
remaining_time -= 1 |
| 176 |
# - AnsibleConnectionFailure covers rejected requests (i.e. |
| 177 |
# by rules with '--jump REJECT') |
| 178 |
# - ansible_timeout is able to cover dropped requests (due |
| 179 |
# to a rule or policy DROP) if not lower than async_val. |
| 180 |
try: |
| 181 |
self._low_level_execute_command(confirm_cmd, sudoable=self.DEFAULT_SUDOABLE) |
| 182 |
break |
| 183 |
except AnsibleConnectionFailure: |
| 184 |
continue |
| 185 |
|
| 186 |
result = merge_hash(result, self._async_result(async_status_args, task_vars, remaining_time)) |
| 187 |
|
| 188 |
# Cleanup async related stuff and internal params |
| 189 |
for key in ("ansible_job_id", "results_file", "started", "finished"): |
| 190 |
if result.get(key): |
| 191 |
del result[key] |
| 192 |
|
| 193 |
if result.get("invocation", {}).get("module_args"): |
| 194 |
for key in ("_back", "_timeout", "_async_dir", "jid"): |
| 195 |
if result["invocation"]["module_args"].get(key): |
| 196 |
del result["invocation"]["module_args"][key] |
| 197 |
|
| 198 |
async_status_args["mode"] = "cleanup" |
| 199 |
self._async_result(async_status_args, task_vars, 0) |
| 200 |
|
| 201 |
if not wrap_async: |
| 202 |
# remove a temporary path we created |
| 203 |
self._remove_tmp_path(self._connection._shell.tmpdir) |
| 204 |
|
| 205 |
return result |