Debian Codegraph @

ansible_collections/community/crypto/plugins/plugin_utils/_action_module.py

raw
1 # Copyright (c) 2012-2013 Michael DeHaan <[email protected]>
2 # Copyright (c) 2016 Toshio Kuratomi <[email protected]>
3 # Copyright (c) 2019 Ansible Project
4 # Copyright (c) 2020 Felix Fontein <[email protected]>
5 # Copyright (c) 2021 Ansible Project
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 # Note that this plugin util is **PRIVATE** to the collection. It can have breaking changes at any time.
10 # Do not use this from other collections or standalone plugins/modules!
11
12 # Parts taken from ansible.module_utils.basic and ansible.module_utils.common.warnings.
13
14 # NOTE: THIS IS ONLY FOR ACTION PLUGINS!
15
16 from __future__ import annotations
17
18 import abc
19 import copy
20 import traceback
21 import typing as t
22
23 from ansible.errors import AnsibleError
24 from ansible.module_utils.basic import remove_values
25 from ansible.module_utils.common.arg_spec import ArgumentSpecValidator
26 from ansible.module_utils.errors import UnsupportedError
27 from ansible.plugins.action import ActionBase
28
29 if t.TYPE_CHECKING:
30 from ansible_collections.community.crypto.plugins.module_utils._argspec import (
31 ArgumentSpec,
32 )
33
34
35 class _ModuleExitException(Exception):
36 def __init__(self, result: dict[str, t.Any]) -> None:
37 super().__init__()
38 self.result = result
39
40
41 class AnsibleActionModule:
42 def __init__(
43 self,
44 action_plugin: ActionModuleBase,
45 argument_spec: dict[str, t.Any],
46 *,
47 bypass_checks: bool = False,
48 supports_check_mode: bool = False,
49 mutually_exclusive: list[list[str] | tuple[str, ...]] | None = None,
50 required_together: list[list[str] | tuple[str, ...]] | None = None,
51 required_one_of: list[list[str] | tuple[str, ...]] | None = None,
52 required_if: list[tuple[str, t.Any, list[str] | tuple[str, ...]]] | None = None,
53 required_by: dict[str, tuple[str, ...] | list[str]] | None = None,
54 ) -> None:
55 # Internal data
56 self.__action_plugin = action_plugin
57 self.__warnings: list[str] = []
58 self.__deprecations: list[dict[str, str | None]] = []
59
60 # AnsibleModule data
61 self._name = self.__action_plugin._task.action
62 self.argument_spec = argument_spec
63 self.supports_check_mode = supports_check_mode
64 self.check_mode = self.__action_plugin._play_context.check_mode
65 self.bypass_checks = bypass_checks
66 self.no_log = self.__action_plugin._play_context.no_log
67
68 self.mutually_exclusive = mutually_exclusive
69 self.required_together = required_together
70 self.required_one_of = required_one_of
71 self.required_if = required_if
72 self.required_by = required_by
73 self._diff = self.__action_plugin._play_context.diff
74 self._verbosity = self.__action_plugin._display.verbosity
75
76 self.params = copy.deepcopy(self.__action_plugin._task.args)
77 self.no_log_values = set()
78 self._validator = ArgumentSpecValidator(
79 self.argument_spec,
80 self.mutually_exclusive,
81 self.required_together,
82 self.required_one_of,
83 self.required_if,
84 self.required_by,
85 )
86 self._validation_result = self._validator.validate(self.params)
87 self.params.update(self._validation_result.validated_parameters)
88 self.no_log_values.update(self._validation_result._no_log_values)
89
90 try:
91 error = self._validation_result.errors[0]
92 except IndexError:
93 error = None
94
95 # We cannot use ModuleArgumentSpecValidator directly since it uses mechanisms for reporting
96 # warnings and deprecations that do not work in plugins. This is a copy of that code adjusted
97 # for our use-case:
98 for d in self._validation_result._deprecations:
99 # Before ansible-core 2.14.2, deprecations were always for aliases:
100 if "name" in d:
101 self.deprecate(
102 f"Alias '{d['name']}' is deprecated. See the module docs for more information",
103 version=d.get("version"),
104 date=d.get("date"),
105 collection_name=d.get("collection_name"),
106 )
107 # Since ansible-core 2.14.2, a message is present that can be directly printed:
108 if "msg" in d:
109 self.deprecate(
110 d["msg"],
111 version=d.get("version"),
112 date=d.get("date"),
113 collection_name=d.get("collection_name"),
114 )
115
116 for w in self._validation_result._warnings:
117 self.warn(f"Both option {w['option']} and its alias {w['alias']} are set.")
118
119 # Fail for validation errors, even in check mode
120 if error:
121 msg = self._validation_result.errors.msg
122 if isinstance(error, UnsupportedError):
123 msg = f"Unsupported parameters for ({self._name}) module: {msg}"
124
125 self.fail_json(msg=msg)
126
127 def warn(self, warning: str) -> None:
128 # Copied from ansible.module_utils.common.warnings:
129 if isinstance(warning, str):
130 self.__warnings.append(warning)
131 else:
132 raise TypeError(f"warn requires a string not a {type(warning)}")
133
134 def deprecate(
135 self,
136 msg: str,
137 version: str | None = None,
138 date: str | None = None,
139 collection_name: str | None = None,
140 ) -> None:
141 if version is not None and date is not None:
142 raise AssertionError( # pragma: no cover
143 "implementation error -- version and date must not both be set"
144 )
145
146 # Copied from ansible.module_utils.common.warnings:
147 if not isinstance(msg, str):
148 raise TypeError(f"deprecate requires a string not a {type(msg)}")
149
150 # For compatibility, we accept that neither version nor date is set,
151 # and treat that the same as if version would haven been set
152 if date is not None:
153 self.__deprecations.append(
154 {"msg": msg, "date": date, "collection_name": collection_name}
155 )
156 else:
157 self.__deprecations.append(
158 {"msg": msg, "version": version, "collection_name": collection_name}
159 )
160
161 def _return_formatted(self, kwargs: dict[str, t.Any]) -> t.NoReturn:
162 if "invocation" not in kwargs:
163 kwargs["invocation"] = {"module_args": self.params}
164
165 if self.__warnings:
166 kwargs["warnings"] = self.__warnings
167
168 if self.__deprecations:
169 kwargs["deprecations"] = self.__deprecations
170
171 kwargs = remove_values(kwargs, self.no_log_values)
172 raise _ModuleExitException(kwargs)
173
174 def exit_json(self, **kwargs: t.Any) -> t.NoReturn:
175 result = dict(kwargs)
176 if "failed" not in result:
177 result["failed"] = False
178 self._return_formatted(result)
179
180 def fail_json(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
181 result = dict(kwargs)
182 result["failed"] = True
183 result["msg"] = msg
184 self._return_formatted(result)
185
186
187 class ActionModuleBase(ActionBase, metaclass=abc.ABCMeta):
188 @abc.abstractmethod
189 def setup_module(self) -> tuple[ArgumentSpec, dict[str, t.Any]]:
190 """Return pair (ArgumentSpec, kwargs)."""
191
192 @abc.abstractmethod
193 def run_module(self, module: AnsibleActionModule) -> None:
194 """Run module code"""
195 module.fail_json(msg="Not implemented.")
196
197 def run(
198 self, tmp: str | None = None, task_vars: dict[str, t.Any] | None = None
199 ) -> dict[str, t.Any]:
200 if task_vars is None:
201 task_vars = {}
202
203 result = super().run(tmp, task_vars)
204 del tmp # tmp no longer has any effect
205
206 try:
207 argument_spec, kwargs = self.setup_module()
208 module = argument_spec.create_ansible_module_helper(
209 AnsibleActionModule, (self,), **kwargs
210 )
211 self.run_module(module)
212 raise AnsibleError(
213 "Internal error: action module did not call module.exit_json()"
214 )
215 except _ModuleExitException as mee:
216 result.update(mee.result)
217 return result
218 except Exception:
219 result["failed"] = True
220 result["msg"] = "MODULE FAILURE"
221 result["exception"] = traceback.format_exc()
222 return result
223
224
225 __all__ = ("ActionModuleBase", "AnsibleActionModule")