| 1 |
# (c) 2012, Daniel Hokka Zakrisson <[email protected]> |
| 2 |
# (c) 2012-2014, Michael DeHaan <[email protected]> and others |
| 3 |
# (c) 2017, Toshio Kuratomi <[email protected]> |
| 4 |
# |
| 5 |
# This file is part of Ansible |
| 6 |
# |
| 7 |
# Ansible is free software: you can redistribute it and/or modify |
| 8 |
# it under the terms of the GNU General Public License as published by |
| 9 |
# the Free Software Foundation, either version 3 of the License, or |
| 10 |
# (at your option) any later version. |
| 11 |
# |
| 12 |
# Ansible is distributed in the hope that it will be useful, |
| 13 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 |
# GNU General Public License for more details. |
| 16 |
# |
| 17 |
# You should have received a copy of the GNU General Public License |
| 18 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 19 |
|
| 20 |
from __future__ import annotations |
| 21 |
|
| 22 |
import abc |
| 23 |
import functools |
| 24 |
import types |
| 25 |
import typing as t |
| 26 |
|
| 27 |
from ansible import constants as C |
| 28 |
from ansible.errors import AnsibleError |
| 29 |
from ansible.utils.display import Display |
| 30 |
from ansible.utils import display as _display |
| 31 |
|
| 32 |
from ansible.module_utils._internal import _plugin_info |
| 33 |
|
| 34 |
display = Display() |
| 35 |
|
| 36 |
if t.TYPE_CHECKING: |
| 37 |
from . import loader as _t_loader |
| 38 |
|
| 39 |
# Global so that all instances of a PluginLoader will share the caches |
| 40 |
MODULE_CACHE = {} # type: dict[str, dict[str, types.ModuleType]] |
| 41 |
PATH_CACHE = {} # type: dict[str, list[_t_loader.PluginPathContext] | None] |
| 42 |
PLUGIN_PATH_CACHE = {} # type: dict[str, dict[str, dict[str, _t_loader.PluginPathContext]]] |
| 43 |
|
| 44 |
|
| 45 |
def get_plugin_class(obj): |
| 46 |
if isinstance(obj, str): |
| 47 |
return obj.lower().replace('module', '') |
| 48 |
else: |
| 49 |
return obj.__class__.__name__.lower().replace('module', '') |
| 50 |
|
| 51 |
|
| 52 |
class _ConfigurablePlugin(t.Protocol): |
| 53 |
"""Protocol to provide type-safe access to config for plugin-related mixins.""" |
| 54 |
|
| 55 |
def get_option(self, option: str, hostvars: dict[str, object] | None = None) -> t.Any: ... |
| 56 |
|
| 57 |
|
| 58 |
class _AnsiblePluginInfoMixin(_plugin_info.HasPluginInfo): |
| 59 |
"""Mixin to provide type annotations and default values for existing PluginLoader-set load-time attrs.""" |
| 60 |
_original_path: str | None = None |
| 61 |
_load_name: str | None = None |
| 62 |
_redirected_names: list[str] | None = None |
| 63 |
ansible_aliases: list[str] | None = None |
| 64 |
ansible_name: str | None = None |
| 65 |
|
| 66 |
@property |
| 67 |
def plugin_type(self) -> str: |
| 68 |
return self.__class__.__name__.lower().replace('module', '') |
| 69 |
|
| 70 |
|
| 71 |
class AnsiblePlugin(_AnsiblePluginInfoMixin, _ConfigurablePlugin, metaclass=abc.ABCMeta): |
| 72 |
|
| 73 |
# Set by plugin loader |
| 74 |
_load_name: str |
| 75 |
|
| 76 |
# allow extra passthrough parameters |
| 77 |
allow_extras: bool = False |
| 78 |
_extras_prefix: str | None = None |
| 79 |
|
| 80 |
def __init__(self): |
| 81 |
self._options = {} |
| 82 |
self._origins = {} |
| 83 |
self._defs = None |
| 84 |
|
| 85 |
@property |
| 86 |
def extras_prefix(self): |
| 87 |
if not self._extras_prefix: |
| 88 |
self._extras_prefix = self._load_name.split('.')[-1] |
| 89 |
return self._extras_prefix |
| 90 |
|
| 91 |
def matches_name(self, possible_names): |
| 92 |
possible_fqcns = set() |
| 93 |
for name in possible_names: |
| 94 |
if '.' not in name: |
| 95 |
possible_fqcns.add(f"ansible.builtin.{name}") |
| 96 |
elif name.startswith("ansible.legacy."): |
| 97 |
possible_fqcns.add(name.removeprefix("ansible.legacy.")) |
| 98 |
possible_fqcns.add(name) |
| 99 |
return bool(possible_fqcns.intersection(set(self.ansible_aliases))) |
| 100 |
|
| 101 |
def get_option_and_origin(self, option, hostvars=None): |
| 102 |
if option not in self._options: |
| 103 |
try: |
| 104 |
# some plugins don't use set_option(s) and cannot use direct settings, so this populates the local copy for them |
| 105 |
self._options[option], self._origins[option] = C.config.get_config_value_and_origin(option, plugin_type=self.plugin_type, |
| 106 |
plugin_name=self._load_name, variables=hostvars) |
| 107 |
except AnsibleError as e: |
| 108 |
# callers expect key error on missing |
| 109 |
raise KeyError() from e |
| 110 |
|
| 111 |
return self._options[option], self._origins[option] |
| 112 |
|
| 113 |
@functools.cached_property |
| 114 |
def __plugin_info(self): |
| 115 |
""" |
| 116 |
Internal cached property to retrieve `PluginInfo` for this plugin instance. |
| 117 |
Only for use by the `AnsiblePlugin` base class. |
| 118 |
""" |
| 119 |
return _plugin_info.get_plugin_info(self) |
| 120 |
|
| 121 |
def get_option(self, option, hostvars=None): |
| 122 |
if option not in self._options: |
| 123 |
# let it populate _options |
| 124 |
self.get_option_and_origin(option, hostvars=hostvars) |
| 125 |
return self._options[option] |
| 126 |
|
| 127 |
def get_options(self, hostvars=None): |
| 128 |
options = {} |
| 129 |
for option in self.option_definitions.keys(): |
| 130 |
options[option] = self.get_option(option, hostvars=hostvars) |
| 131 |
return options |
| 132 |
|
| 133 |
def set_option(self, option, value): |
| 134 |
self._options[option] = C.config.get_config_value(option, plugin_type=self.plugin_type, plugin_name=self._load_name, direct={option: value}) |
| 135 |
self._origins[option] = 'Direct' |
| 136 |
_display._report_config_warnings(self.__plugin_info) |
| 137 |
|
| 138 |
def set_options(self, task_keys=None, var_options=None, direct=None): |
| 139 |
""" |
| 140 |
Sets the _options attribute with the configuration/keyword information for this plugin |
| 141 |
|
| 142 |
:arg task_keys: Dict with playbook keywords that affect this option |
| 143 |
:arg var_options: Dict with either 'connection variables' |
| 144 |
:arg direct: Dict with 'direct assignment' |
| 145 |
""" |
| 146 |
self._options, self._origins = C.config.get_plugin_options_and_origins(self.plugin_type, self._load_name, keys=task_keys, |
| 147 |
variables=var_options, direct=direct) |
| 148 |
|
| 149 |
# allow extras/wildcards from vars that are not directly consumed in configuration |
| 150 |
# this is needed to support things like winrm that can have extended protocol options we don't directly handle |
| 151 |
if self.allow_extras and var_options and '_extras' in var_options: |
| 152 |
# these are largely unvalidated passthroughs, either plugin or underlying API will validate |
| 153 |
# TODO: deprecate and remove, most plugins that needed this don't use this facility anymore |
| 154 |
self._options['_extras'] = var_options['_extras'] |
| 155 |
_display._report_config_warnings(self.__plugin_info) |
| 156 |
|
| 157 |
def has_option(self, option): |
| 158 |
if not self._options: |
| 159 |
self.set_options() |
| 160 |
return option in self._options |
| 161 |
|
| 162 |
@property |
| 163 |
def option_definitions(self): |
| 164 |
if (not hasattr(self, "_defs")) or self._defs is None: |
| 165 |
self._defs = C.config.get_configuration_definitions(plugin_type=self.plugin_type, name=self._load_name) |
| 166 |
return self._defs |
| 167 |
|
| 168 |
def _check_required(self): |
| 169 |
# FIXME: standardize required check based on config |
| 170 |
pass |
| 171 |
|
| 172 |
def __repr__(self): |
| 173 |
ansible_name = getattr(self, 'ansible_name', '(unknown)') |
| 174 |
load_name = getattr(self, '_load_name', '(unknown)') |
| 175 |
return f'{type(self).__name__}(plugin_type={self.plugin_type!r}, {ansible_name=!r}, {load_name=!r})' |
| 176 |
|
| 177 |
|
| 178 |
class AnsibleJinja2Plugin(AnsiblePlugin, metaclass=abc.ABCMeta): |
| 179 |
def __init__(self, function: t.Callable) -> None: |
| 180 |
super(AnsibleJinja2Plugin, self).__init__() |
| 181 |
self._function = function |
| 182 |
|
| 183 |
# Declare support for markers. Plugins with `False` here will never be invoked with markers for top-level arguments. |
| 184 |
self.accept_args_markers = getattr(self._function, 'accept_args_markers', False) |
| 185 |
self.accept_lazy_markers = getattr(self._function, 'accept_lazy_markers', False) |
| 186 |
|
| 187 |
@property |
| 188 |
@abc.abstractmethod |
| 189 |
def plugin_type(self) -> str: |
| 190 |
... |
| 191 |
|
| 192 |
def _no_options(self, *args, **kwargs) -> t.NoReturn: |
| 193 |
raise NotImplementedError() |
| 194 |
|
| 195 |
has_option = get_option = get_options = option_definitions = set_option = set_options = _no_options |
| 196 |
|
| 197 |
@property |
| 198 |
def j2_function(self) -> t.Callable: |
| 199 |
return self._function |