| 1 |
# Copyright (c) 2022, Alexei Znamensky <[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 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 6 |
# Do not use this from other collections or standalone plugins/modules! |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import os |
| 11 |
import typing as t |
| 12 |
|
| 13 |
from ansible.module_utils.common.collections import is_sequence |
| 14 |
from ansible.module_utils.common.locale import get_best_parsable_locale |
| 15 |
|
| 16 |
from ansible_collections.community.general.plugins.module_utils import _cmd_runner_fmt as cmd_runner_fmt |
| 17 |
|
| 18 |
if t.TYPE_CHECKING: |
| 19 |
from collections.abc import Callable, Mapping, Sequence |
| 20 |
|
| 21 |
from ansible.module_utils.basic import AnsibleModule |
| 22 |
|
| 23 |
from ansible_collections.community.general.plugins.module_utils._cmd_runner_fmt import ArgFormatType |
| 24 |
|
| 25 |
ArgFormatter = t.Union[ArgFormatType, cmd_runner_fmt._ArgFormat] # noqa: UP007 |
| 26 |
|
| 27 |
|
| 28 |
def _ensure_list(value): |
| 29 |
return list(value) if is_sequence(value) else [value] |
| 30 |
|
| 31 |
|
| 32 |
def _process_as_is(rc, out, err): |
| 33 |
return rc, out, err |
| 34 |
|
| 35 |
|
| 36 |
class CmdRunnerException(Exception): |
| 37 |
pass |
| 38 |
|
| 39 |
|
| 40 |
class MissingArgumentFormat(CmdRunnerException): |
| 41 |
def __init__(self, arg, args_order: tuple[str, ...], args_formats) -> None: |
| 42 |
self.args_order = args_order |
| 43 |
self.arg = arg |
| 44 |
self.args_formats = args_formats |
| 45 |
|
| 46 |
def __repr__(self): |
| 47 |
return f"MissingArgumentFormat({self.arg!r}, {self.args_order!r}, {self.args_formats!r})" |
| 48 |
|
| 49 |
def __str__(self): |
| 50 |
return f"Cannot find format for parameter {self.arg} {self.args_order} in: {self.args_formats}" |
| 51 |
|
| 52 |
|
| 53 |
class MissingArgumentValue(CmdRunnerException): |
| 54 |
def __init__(self, args_order: tuple[str, ...], arg) -> None: |
| 55 |
self.args_order = args_order |
| 56 |
self.arg = arg |
| 57 |
|
| 58 |
def __repr__(self): |
| 59 |
return f"MissingArgumentValue({self.args_order!r}, {self.arg!r})" |
| 60 |
|
| 61 |
def __str__(self): |
| 62 |
return f"Cannot find value for parameter {self.arg} in {self.args_order}" |
| 63 |
|
| 64 |
|
| 65 |
class FormatError(CmdRunnerException): |
| 66 |
def __init__(self, name, value, args_formats, exc): |
| 67 |
self.name = name |
| 68 |
self.value = value |
| 69 |
self.args_formats = args_formats |
| 70 |
self.exc = exc |
| 71 |
super().__init__() |
| 72 |
|
| 73 |
def __repr__(self): |
| 74 |
return f"FormatError({self.name!r}, {self.value!r}, {self.args_formats!r}, {self.exc!r})" |
| 75 |
|
| 76 |
def __str__(self): |
| 77 |
return f"Failed to format parameter {self.name} with value {self.value}: {self.exc}" |
| 78 |
|
| 79 |
|
| 80 |
class CmdRunner: |
| 81 |
""" |
| 82 |
Wrapper for ``AnsibleModule.run_command()``. |
| 83 |
|
| 84 |
It aims to provide a reusable runner with consistent argument formatting |
| 85 |
and sensible defaults. |
| 86 |
""" |
| 87 |
|
| 88 |
@staticmethod |
| 89 |
def _prepare_args_order(order: str | Sequence[str]) -> tuple[str, ...]: |
| 90 |
return tuple(order) if is_sequence(order) else tuple(order.split()) # type: ignore |
| 91 |
|
| 92 |
def __init__( |
| 93 |
self, |
| 94 |
module: AnsibleModule, |
| 95 |
command, |
| 96 |
arg_formats: Mapping[str, ArgFormatter] | None = None, |
| 97 |
default_args_order: str | Sequence[str] = (), |
| 98 |
check_rc: bool = False, |
| 99 |
force_lang: str = "C", |
| 100 |
path_prefix: Sequence[str] | None = None, |
| 101 |
environ_update: dict[str, str] | None = None, |
| 102 |
): |
| 103 |
self.module = module |
| 104 |
self.command = _ensure_list(command) |
| 105 |
self.default_args_order = self._prepare_args_order(default_args_order) |
| 106 |
if arg_formats is None: |
| 107 |
arg_formats = {} |
| 108 |
self.arg_formats = {} |
| 109 |
for fmt_name, fmt in arg_formats.items(): |
| 110 |
if not cmd_runner_fmt.is_argformat(fmt): |
| 111 |
fmt = cmd_runner_fmt.as_func(func=fmt, ignore_none=True) |
| 112 |
self.arg_formats[fmt_name] = fmt |
| 113 |
self.check_rc = check_rc |
| 114 |
if force_lang == "auto": |
| 115 |
try: |
| 116 |
self.force_lang = get_best_parsable_locale(module) |
| 117 |
except RuntimeWarning: |
| 118 |
self.force_lang = "C" |
| 119 |
else: |
| 120 |
self.force_lang = force_lang |
| 121 |
self.path_prefix = path_prefix |
| 122 |
if environ_update is None: |
| 123 |
environ_update = {} |
| 124 |
self.environ_update = environ_update |
| 125 |
|
| 126 |
_cmd = self.command[0] |
| 127 |
self.command[0] = ( |
| 128 |
_cmd |
| 129 |
if (os.path.isabs(_cmd) or "/" in _cmd) |
| 130 |
else module.get_bin_path(_cmd, opt_dirs=path_prefix, required=True) |
| 131 |
) |
| 132 |
|
| 133 |
@property |
| 134 |
def binary(self) -> str: |
| 135 |
return self.command[0] |
| 136 |
|
| 137 |
def __call__( |
| 138 |
self, |
| 139 |
args_order: str | Sequence[str] | None = None, |
| 140 |
output_process: Callable[[int, str, str], t.Any] | None = None, |
| 141 |
check_mode_skip: bool = False, |
| 142 |
check_mode_return: t.Any | None = None, |
| 143 |
**kwargs, |
| 144 |
): |
| 145 |
if output_process is None: |
| 146 |
output_process = _process_as_is |
| 147 |
if args_order is None: |
| 148 |
args_order = self.default_args_order |
| 149 |
args_order = self._prepare_args_order(args_order) |
| 150 |
for p in args_order: |
| 151 |
if p not in self.arg_formats: |
| 152 |
raise MissingArgumentFormat(p, args_order, tuple(self.arg_formats.keys())) |
| 153 |
return _CmdRunnerContext( |
| 154 |
runner=self, |
| 155 |
args_order=args_order, |
| 156 |
output_process=output_process, |
| 157 |
check_mode_skip=check_mode_skip, |
| 158 |
check_mode_return=check_mode_return, |
| 159 |
**kwargs, |
| 160 |
) |
| 161 |
|
| 162 |
def has_arg_format(self, arg): |
| 163 |
return arg in self.arg_formats |
| 164 |
|
| 165 |
# not decided whether to keep it or not, but if deprecating it will happen in a farther future. |
| 166 |
context = __call__ |
| 167 |
|
| 168 |
|
| 169 |
class _CmdRunnerContext: |
| 170 |
def __init__( |
| 171 |
self, |
| 172 |
runner: CmdRunner, |
| 173 |
args_order: tuple[str, ...], |
| 174 |
output_process: Callable[[int, str, str], t.Any], |
| 175 |
check_mode_skip: bool, |
| 176 |
check_mode_return: t.Any, |
| 177 |
**kwargs, |
| 178 |
) -> None: |
| 179 |
self.runner = runner |
| 180 |
self.args_order = tuple(args_order) |
| 181 |
self.output_process = output_process |
| 182 |
self.check_mode_skip = check_mode_skip |
| 183 |
self.check_mode_return = check_mode_return |
| 184 |
self.run_command_args = dict(kwargs) |
| 185 |
|
| 186 |
self.environ_update = runner.environ_update |
| 187 |
self.environ_update.update(self.run_command_args.get("environ_update", {})) |
| 188 |
if runner.force_lang: |
| 189 |
self.environ_update.update( |
| 190 |
{ |
| 191 |
"LANGUAGE": runner.force_lang, |
| 192 |
"LC_ALL": runner.force_lang, |
| 193 |
} |
| 194 |
) |
| 195 |
self.run_command_args["environ_update"] = self.environ_update |
| 196 |
|
| 197 |
if "check_rc" not in self.run_command_args: |
| 198 |
self.run_command_args["check_rc"] = runner.check_rc |
| 199 |
self.check_rc = self.run_command_args["check_rc"] |
| 200 |
|
| 201 |
self.cmd = None |
| 202 |
self.results_rc = None |
| 203 |
self.results_out = None |
| 204 |
self.results_err = None |
| 205 |
self.results_processed = None |
| 206 |
|
| 207 |
def run(self, **kwargs): |
| 208 |
runner = self.runner |
| 209 |
module = self.runner.module |
| 210 |
self.cmd = list(runner.command) |
| 211 |
self.context_run_args = dict(kwargs) |
| 212 |
|
| 213 |
named_args = dict(module.params) |
| 214 |
named_args.update(kwargs) |
| 215 |
for arg_name in self.args_order: |
| 216 |
value = None |
| 217 |
try: |
| 218 |
if arg_name in named_args: |
| 219 |
value = named_args[arg_name] |
| 220 |
elif not runner.arg_formats[arg_name].ignore_missing_value: |
| 221 |
raise MissingArgumentValue(self.args_order, arg_name) |
| 222 |
self.cmd.extend(runner.arg_formats[arg_name](value)) |
| 223 |
except MissingArgumentValue: |
| 224 |
raise |
| 225 |
except Exception as e: |
| 226 |
raise FormatError(arg_name, value, runner.arg_formats[arg_name], e) from e |
| 227 |
|
| 228 |
if self.check_mode_skip and module.check_mode: |
| 229 |
return self.check_mode_return |
| 230 |
results = module.run_command(self.cmd, **self.run_command_args) |
| 231 |
self.results_rc, self.results_out, self.results_err = results |
| 232 |
self.results_processed = self.output_process(*results) |
| 233 |
return self.results_processed |
| 234 |
|
| 235 |
@property |
| 236 |
def run_info(self) -> dict[str, t.Any]: |
| 237 |
return dict( |
| 238 |
check_rc=self.check_rc, |
| 239 |
environ_update=self.environ_update, |
| 240 |
args_order=self.args_order, |
| 241 |
cmd=self.cmd, |
| 242 |
run_command_args=self.run_command_args, |
| 243 |
context_run_args=self.context_run_args, |
| 244 |
results_rc=self.results_rc, |
| 245 |
results_out=self.results_out, |
| 246 |
results_err=self.results_err, |
| 247 |
results_processed=self.results_processed, |
| 248 |
) |
| 249 |
|
| 250 |
def __enter__(self): |
| 251 |
return self |
| 252 |
|
| 253 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 254 |
return False |