| 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 |
# (c) 2017 Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import functools |
| 10 |
import glob |
| 11 |
import os |
| 12 |
import os.path |
| 13 |
import pkgutil |
| 14 |
import sys |
| 15 |
import types |
| 16 |
import warnings |
| 17 |
import typing as t |
| 18 |
|
| 19 |
import yaml |
| 20 |
|
| 21 |
from collections import defaultdict, namedtuple |
| 22 |
from importlib import import_module |
| 23 |
from yaml.parser import ParserError |
| 24 |
|
| 25 |
from ansible import __version__ as ansible_version |
| 26 |
from ansible import _internal, constants as C |
| 27 |
from ansible.errors import AnsibleError, AnsiblePluginCircularRedirect, AnsiblePluginRemovedError, AnsibleCollectionUnsupportedVersionError |
| 28 |
from ansible.module_utils.common.sentinel import Sentinel |
| 29 |
from ansible.module_utils.common.text.converters import to_bytes, to_text, to_native |
| 30 |
from ansible.module_utils.datatag import deprecator_from_collection_name |
| 31 |
from ansible.parsing.yaml.loader import AnsibleLoader |
| 32 |
from ansible._internal._yaml._loader import AnsibleInstrumentedLoader |
| 33 |
from ansible.plugins import get_plugin_class, MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CACHE, AnsibleJinja2Plugin |
| 34 |
from ansible.utils.collection_loader import AnsibleCollectionConfig, AnsibleCollectionRef |
| 35 |
from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder, _get_collection_metadata |
| 36 |
from ansible.utils.display import Display |
| 37 |
from ansible.utils.plugin_docs import add_fragments |
| 38 |
from ansible._internal._datatag import _tags |
| 39 |
from ansible._internal import _display_utils |
| 40 |
|
| 41 |
from . import _AnsiblePluginInfoMixin |
| 42 |
from .filter import AnsibleJinja2Filter |
| 43 |
from .test import AnsibleJinja2Test |
| 44 |
from .._internal._plugins import _cache |
| 45 |
|
| 46 |
# TODO: take the packaging dep, or vendor SpecifierSet? |
| 47 |
|
| 48 |
try: |
| 49 |
from packaging.specifiers import SpecifierSet |
| 50 |
from packaging.version import Version |
| 51 |
except ImportError: |
| 52 |
SpecifierSet = None # type: ignore[misc] |
| 53 |
Version = None # type: ignore[misc] |
| 54 |
|
| 55 |
import importlib.util |
| 56 |
|
| 57 |
if t.TYPE_CHECKING: |
| 58 |
from ansible.plugins.cache import BaseCacheModule |
| 59 |
|
| 60 |
_ALIASES_MSG = ( |
| 61 |
"Aliases should be defined in the collection's meta/runtime.yml file, " |
| 62 |
"by using symlinks, or the caller should query the plugin loader for " |
| 63 |
"each identifier. Set the DISPLAY_TRACEBACK configuration to 'deprecated' " |
| 64 |
"to see details." |
| 65 |
) |
| 66 |
|
| 67 |
_PLUGIN_FILTERS = defaultdict(frozenset) # type: t.DefaultDict[str, frozenset] |
| 68 |
display = Display() |
| 69 |
|
| 70 |
get_with_context_result = namedtuple('get_with_context_result', ['object', 'plugin_load_context']) |
| 71 |
|
| 72 |
|
| 73 |
@functools.cache |
| 74 |
def get_all_plugin_loaders() -> list[tuple[str, 'PluginLoader']]: |
| 75 |
return [(name, obj) for (name, obj) in globals().items() if isinstance(obj, PluginLoader)] |
| 76 |
|
| 77 |
|
| 78 |
@functools.cache |
| 79 |
def get_plugin_loader_namespace() -> types.SimpleNamespace: |
| 80 |
ns = types.SimpleNamespace() |
| 81 |
for name, obj in get_all_plugin_loaders(): |
| 82 |
setattr(ns, name, obj) |
| 83 |
return ns |
| 84 |
|
| 85 |
|
| 86 |
def add_all_plugin_dirs(path): |
| 87 |
""" add any existing plugin dirs in the path provided """ |
| 88 |
b_path = os.path.expanduser(to_bytes(path, errors='surrogate_or_strict')) |
| 89 |
if os.path.isdir(b_path): |
| 90 |
for name, obj in get_all_plugin_loaders(): |
| 91 |
if obj.subdir: |
| 92 |
plugin_path = os.path.join(b_path, to_bytes(obj.subdir)) |
| 93 |
if os.path.isdir(plugin_path): |
| 94 |
obj.add_directory(to_text(plugin_path)) |
| 95 |
else: |
| 96 |
display.warning("Ignoring invalid path provided to plugin path: '%s' is not a directory" % to_text(path)) |
| 97 |
|
| 98 |
|
| 99 |
def get_shell_plugin(shell_type=None, executable=None): |
| 100 |
|
| 101 |
if not shell_type: |
| 102 |
# default to sh |
| 103 |
shell_type = 'sh' |
| 104 |
|
| 105 |
# mostly for backwards compat |
| 106 |
if executable: |
| 107 |
if isinstance(executable, str): |
| 108 |
shell_filename = os.path.basename(executable) |
| 109 |
try: |
| 110 |
shell = shell_loader.get(shell_filename) |
| 111 |
except Exception: |
| 112 |
shell = None |
| 113 |
|
| 114 |
if shell is None: |
| 115 |
for shell in shell_loader.all(): |
| 116 |
if shell_filename in shell.COMPATIBLE_SHELLS: |
| 117 |
shell_type = shell.SHELL_FAMILY |
| 118 |
break |
| 119 |
else: |
| 120 |
raise AnsibleError("Either a shell type or a shell executable must be provided ") |
| 121 |
|
| 122 |
shell = shell_loader.get(shell_type) |
| 123 |
if not shell: |
| 124 |
raise AnsibleError("Could not find the shell plugin required (%s)." % shell_type) |
| 125 |
|
| 126 |
if executable: |
| 127 |
setattr(shell, 'executable', executable) |
| 128 |
|
| 129 |
return shell |
| 130 |
|
| 131 |
|
| 132 |
def add_dirs_to_loader(which_loader, paths): |
| 133 |
|
| 134 |
loader = getattr(sys.modules[__name__], '%s_loader' % which_loader) |
| 135 |
for path in paths: |
| 136 |
loader.add_directory(path, with_subdir=True) |
| 137 |
|
| 138 |
|
| 139 |
class PluginPathContext(object): |
| 140 |
def __init__(self, path, internal): |
| 141 |
self.path = path |
| 142 |
self.internal = internal |
| 143 |
|
| 144 |
|
| 145 |
class PluginLoadContext(object): |
| 146 |
def __init__(self, plugin_type: str, legacy_package_name: str, *, ignore_deprecated: bool = False) -> None: |
| 147 |
self.original_name: str | None = None |
| 148 |
self.redirect_list: list[str] = [] |
| 149 |
self.raw_error_list: list[Exception] = [] |
| 150 |
"""All exception instances encountered during the plugin load.""" |
| 151 |
self.error_list: list[str] = [] |
| 152 |
"""Stringified exceptions, excluding import errors.""" |
| 153 |
self.import_error_list: list[Exception] = [] |
| 154 |
"""All ImportError exception instances encountered during the plugin load.""" |
| 155 |
self.load_attempts: list[str] = [] |
| 156 |
self.pending_redirect: str | None = None |
| 157 |
self.exit_reason: str | None = None |
| 158 |
self.plugin_resolved_path: str | None = None |
| 159 |
self.plugin_resolved_name: str | None = None |
| 160 |
"""For collection plugins, the resolved Python module FQ __name__; for non-collections, the short name.""" |
| 161 |
self.plugin_resolved_collection: str | None = None # empty string for resolved plugins from user-supplied paths |
| 162 |
"""For collection plugins, the resolved collection {ns}.{col}; empty string for non-collection plugins.""" |
| 163 |
self.deprecated: bool = False |
| 164 |
self.removal_date: str | None = None |
| 165 |
self.removal_version: str | None = None |
| 166 |
self.deprecation_warnings: list[str] = [] |
| 167 |
self.resolved: bool = False |
| 168 |
self._resolved_fqcn: str | None = None |
| 169 |
self.action_plugin: str | None = None |
| 170 |
self._plugin_type: str = plugin_type |
| 171 |
"""The type of the plugin.""" |
| 172 |
self._legacy_package_name = legacy_package_name |
| 173 |
"""The legacy sys.modules package name from the plugin loader instance; stored to prevent potentially incorrect manual computation.""" |
| 174 |
self._python_module_name: str | None = None |
| 175 |
""" |
| 176 |
The fully qualified Python module name for the plugin (accessible via `sys.modules`). |
| 177 |
For non-collection non-core plugins, this may include a non-existent synthetic package element with a hash of the file path to avoid collisions. |
| 178 |
""" |
| 179 |
self.ignore_deprecated: bool = ignore_deprecated |
| 180 |
"""When true, the load context should not record deprecation warnings.""" |
| 181 |
|
| 182 |
@property |
| 183 |
def resolved_fqcn(self) -> str | None: |
| 184 |
if not self.resolved: |
| 185 |
return None |
| 186 |
|
| 187 |
if not self._resolved_fqcn: |
| 188 |
final_plugin = self.redirect_list[-1] |
| 189 |
if AnsibleCollectionRef.is_valid_fqcr(final_plugin) and final_plugin.startswith('ansible.legacy.'): |
| 190 |
final_plugin = final_plugin.split('ansible.legacy.')[-1] |
| 191 |
if self.plugin_resolved_collection and not AnsibleCollectionRef.is_valid_fqcr(final_plugin): |
| 192 |
final_plugin = self.plugin_resolved_collection + '.' + final_plugin |
| 193 |
self._resolved_fqcn = final_plugin |
| 194 |
|
| 195 |
return self._resolved_fqcn |
| 196 |
|
| 197 |
def record_deprecation(self, name: str, deprecation: dict[str, t.Any] | None, collection_name: str) -> t.Self: |
| 198 |
if self.ignore_deprecated or not deprecation: |
| 199 |
return self |
| 200 |
|
| 201 |
# The `or ''` instead of using `.get(..., '')` makes sure that even if the user explicitly |
| 202 |
# sets `warning_text` to `~` (None) or `false`, we still get an empty string. |
| 203 |
warning_text = deprecation.get('warning_text', None) or '' |
| 204 |
removal_date = deprecation.get('removal_date', None) |
| 205 |
removal_version = deprecation.get('removal_version', None) |
| 206 |
# If both removal_date and removal_version are specified, use removal_date |
| 207 |
if removal_date is not None: |
| 208 |
removal_version = None |
| 209 |
warning_text = '{0} has been deprecated.{1}{2}'.format(name, ' ' if warning_text else '', warning_text) |
| 210 |
|
| 211 |
display.deprecated( # pylint: disable=ansible-deprecated-date-not-permitted,ansible-deprecated-unnecessary-collection-name |
| 212 |
msg=warning_text, |
| 213 |
date=removal_date, |
| 214 |
version=removal_version, |
| 215 |
deprecator=deprecator_from_collection_name(collection_name), |
| 216 |
obj=name, |
| 217 |
) |
| 218 |
|
| 219 |
self.deprecated = True |
| 220 |
if removal_date: |
| 221 |
self.removal_date = removal_date |
| 222 |
if removal_version: |
| 223 |
self.removal_version = removal_version |
| 224 |
self.deprecation_warnings.append(warning_text) |
| 225 |
return self |
| 226 |
|
| 227 |
def resolve(self, resolved_name: str, resolved_path: str, resolved_collection: str, exit_reason: str, action_plugin: str) -> t.Self: |
| 228 |
"""Record a resolved collection plugin.""" |
| 229 |
self.pending_redirect = None |
| 230 |
self.plugin_resolved_name = resolved_name |
| 231 |
self.plugin_resolved_path = resolved_path |
| 232 |
self.plugin_resolved_collection = resolved_collection |
| 233 |
self.exit_reason = exit_reason |
| 234 |
self._python_module_name = resolved_name |
| 235 |
self.resolved = True |
| 236 |
self.action_plugin = action_plugin |
| 237 |
|
| 238 |
return self |
| 239 |
|
| 240 |
def resolve_legacy(self, name: str, pull_cache: dict[str, PluginPathContext]) -> t.Self: |
| 241 |
"""Record a resolved legacy plugin.""" |
| 242 |
plugin_path_context = pull_cache[name] |
| 243 |
|
| 244 |
self.plugin_resolved_name = name |
| 245 |
self.plugin_resolved_path = plugin_path_context.path |
| 246 |
self.plugin_resolved_collection = 'ansible.builtin' if plugin_path_context.internal else '' |
| 247 |
self._resolved_fqcn = 'ansible.builtin.' + name if plugin_path_context.internal else name |
| 248 |
self._python_module_name = self._make_legacy_python_module_name() |
| 249 |
self.resolved = True |
| 250 |
|
| 251 |
return self |
| 252 |
|
| 253 |
def resolve_legacy_jinja_plugin(self, name: str, known_plugin: AnsibleJinja2Plugin) -> t.Self: |
| 254 |
"""Record a resolved legacy Jinja plugin.""" |
| 255 |
internal = known_plugin.ansible_name.startswith('ansible.builtin.') |
| 256 |
|
| 257 |
self.plugin_resolved_name = name |
| 258 |
self.plugin_resolved_path = known_plugin._original_path |
| 259 |
self.plugin_resolved_collection = 'ansible.builtin' if internal else '' |
| 260 |
self._resolved_fqcn = known_plugin.ansible_name |
| 261 |
self._python_module_name = self._make_legacy_python_module_name() |
| 262 |
self.resolved = True |
| 263 |
|
| 264 |
return self |
| 265 |
|
| 266 |
def redirect(self, redirect_name: str) -> t.Self: |
| 267 |
self.pending_redirect = redirect_name |
| 268 |
self.exit_reason = 'pending redirect resolution from {0} to {1}'.format(self.original_name, redirect_name) |
| 269 |
self.resolved = False |
| 270 |
|
| 271 |
return self |
| 272 |
|
| 273 |
def nope(self, exit_reason: str) -> t.Self: |
| 274 |
self.pending_redirect = None |
| 275 |
self.exit_reason = exit_reason |
| 276 |
self.resolved = False |
| 277 |
|
| 278 |
return self |
| 279 |
|
| 280 |
def _make_legacy_python_module_name(self) -> str: |
| 281 |
""" |
| 282 |
Generate a fully-qualified Python module name for a legacy/builtin plugin. |
| 283 |
|
| 284 |
The same package namespace is shared for builtin and legacy plugins. |
| 285 |
Explicit requests for builtins via `ansible.builtin` are handled elsewhere with an aliased collection package resolved by the collection loader. |
| 286 |
Only unqualified and `ansible.legacy`-qualified requests land here; whichever plugin is visible at the time will end up in sys.modules. |
| 287 |
Filter and test plugin host modules receive special name suffixes to avoid collisions unrelated to the actual plugin name. |
| 288 |
""" |
| 289 |
name = os.path.splitext(self.plugin_resolved_path)[0] |
| 290 |
basename = os.path.basename(name) |
| 291 |
|
| 292 |
if self._plugin_type in ('filter', 'test'): |
| 293 |
# Unlike other plugin types, filter and test plugin names are independent of the file where they are defined. |
| 294 |
# As a result, the Python module name must be derived from the full path of the plugin. |
| 295 |
# This prevents accidental shadowing of unrelated plugins of the same type. |
| 296 |
basename += f'_{abs(hash(self.plugin_resolved_path))}' |
| 297 |
|
| 298 |
return f'{self._legacy_package_name}.{basename}' |
| 299 |
|
| 300 |
|
| 301 |
class PluginLoader: |
| 302 |
""" |
| 303 |
PluginLoader loads plugins from the configured plugin directories. |
| 304 |
|
| 305 |
It searches for plugins by iterating through the combined list of play basedirs, configured |
| 306 |
paths, and the python path. The first match is used. |
| 307 |
""" |
| 308 |
|
| 309 |
def __init__( |
| 310 |
self, |
| 311 |
class_name: str, |
| 312 |
package: str, |
| 313 |
config: str | list[str], |
| 314 |
subdir: str, |
| 315 |
aliases: dict[str, str] | None | t.Type[Sentinel] = Sentinel, |
| 316 |
required_base_class: str | None = None, |
| 317 |
) -> None: |
| 318 |
|
| 319 |
self.class_name = class_name |
| 320 |
self.base_class = required_base_class |
| 321 |
self.package = package |
| 322 |
self.subdir = subdir |
| 323 |
|
| 324 |
if aliases is not Sentinel: |
| 325 |
display.deprecated( |
| 326 |
msg=f"Instantiating {self.type} PluginLoader with aliases is deprecated. {_ALIASES_MSG}", |
| 327 |
version="2.25", |
| 328 |
) |
| 329 |
self._aliases: dict[str, str] = aliases if aliases and aliases is not Sentinel else {} # type: ignore[assignment] |
| 330 |
|
| 331 |
if config and not isinstance(config, list): |
| 332 |
config = [config] |
| 333 |
elif not config: |
| 334 |
config = [] |
| 335 |
|
| 336 |
self.config = config |
| 337 |
|
| 338 |
if class_name not in MODULE_CACHE: |
| 339 |
MODULE_CACHE[class_name] = {} |
| 340 |
if class_name not in PATH_CACHE: |
| 341 |
PATH_CACHE[class_name] = None |
| 342 |
if class_name not in PLUGIN_PATH_CACHE: |
| 343 |
PLUGIN_PATH_CACHE[class_name] = defaultdict(dict) |
| 344 |
|
| 345 |
# hold dirs added at runtime outside of config |
| 346 |
self._extra_dirs: list[str] = [] |
| 347 |
|
| 348 |
# caches |
| 349 |
self._module_cache = MODULE_CACHE[class_name] |
| 350 |
self._paths = PATH_CACHE[class_name] |
| 351 |
self._plugin_path_cache = PLUGIN_PATH_CACHE[class_name] |
| 352 |
self._plugin_instance_cache: dict[str, tuple[object, PluginLoadContext]] | None = {} if self.subdir == 'vars_plugins' else None |
| 353 |
|
| 354 |
self._searched_paths: set[str] = set() |
| 355 |
|
| 356 |
@property |
| 357 |
def aliases(self): |
| 358 |
display.deprecated( |
| 359 |
msg=f"The {self.type} PluginLoader attribute 'aliases' is deprecated. {_ALIASES_MSG}", |
| 360 |
version="2.25", |
| 361 |
) |
| 362 |
return self._aliases |
| 363 |
|
| 364 |
@aliases.setter |
| 365 |
def aliases(self, value): |
| 366 |
display.deprecated( |
| 367 |
msg=f"Setting {self.type} PluginLoader attribute 'aliases' is deprecated. {_ALIASES_MSG}", |
| 368 |
version="2.25", |
| 369 |
) |
| 370 |
self._aliases = value |
| 371 |
|
| 372 |
@property |
| 373 |
def type(self): |
| 374 |
return AnsibleCollectionRef.legacy_plugin_dir_to_plugin_type(self.subdir) |
| 375 |
|
| 376 |
def __repr__(self): |
| 377 |
return 'PluginLoader(type={0})'.format(self.type) |
| 378 |
|
| 379 |
def _clear_caches(self): |
| 380 |
|
| 381 |
if C.OLD_PLUGIN_CACHE_CLEARING: |
| 382 |
self._paths = None |
| 383 |
else: |
| 384 |
# reset global caches |
| 385 |
MODULE_CACHE[self.class_name] = {} |
| 386 |
PATH_CACHE[self.class_name] = None |
| 387 |
PLUGIN_PATH_CACHE[self.class_name] = defaultdict(dict) |
| 388 |
|
| 389 |
# reset internal caches |
| 390 |
self._module_cache = MODULE_CACHE[self.class_name] |
| 391 |
self._paths = PATH_CACHE[self.class_name] |
| 392 |
self._plugin_path_cache = PLUGIN_PATH_CACHE[self.class_name] |
| 393 |
self._plugin_instance_cache = {} if self.subdir == 'vars_plugins' else None |
| 394 |
self._searched_paths = set() |
| 395 |
|
| 396 |
def __setstate__(self, data): |
| 397 |
""" |
| 398 |
Deserializer. |
| 399 |
""" |
| 400 |
|
| 401 |
class_name = data.get('class_name') |
| 402 |
package = data.get('package') |
| 403 |
config = data.get('config') |
| 404 |
subdir = data.get('subdir') |
| 405 |
aliases = data.get('aliases') |
| 406 |
base_class = data.get('base_class') |
| 407 |
|
| 408 |
PATH_CACHE[class_name] = data.get('PATH_CACHE') |
| 409 |
PLUGIN_PATH_CACHE[class_name] = data.get('PLUGIN_PATH_CACHE') |
| 410 |
|
| 411 |
self.__init__(class_name, package, config, subdir, aliases, base_class) |
| 412 |
self._extra_dirs = data.get('_extra_dirs', []) |
| 413 |
self._searched_paths = data.get('_searched_paths', set()) |
| 414 |
|
| 415 |
def __getstate__(self): |
| 416 |
""" |
| 417 |
Serializer. |
| 418 |
""" |
| 419 |
|
| 420 |
return dict( |
| 421 |
class_name=self.class_name, |
| 422 |
base_class=self.base_class, |
| 423 |
package=self.package, |
| 424 |
config=self.config, |
| 425 |
subdir=self.subdir, |
| 426 |
aliases=self._aliases, |
| 427 |
_extra_dirs=self._extra_dirs, |
| 428 |
_searched_paths=self._searched_paths, |
| 429 |
PATH_CACHE=PATH_CACHE[self.class_name], |
| 430 |
PLUGIN_PATH_CACHE=PLUGIN_PATH_CACHE[self.class_name], |
| 431 |
) |
| 432 |
|
| 433 |
def format_paths(self, paths): |
| 434 |
""" Returns a string suitable for printing of the search path """ |
| 435 |
|
| 436 |
# Uses a list to get the order right |
| 437 |
ret = [] |
| 438 |
for i in paths: |
| 439 |
if i not in ret: |
| 440 |
ret.append(i) |
| 441 |
return os.pathsep.join(ret) |
| 442 |
|
| 443 |
def print_paths(self): |
| 444 |
return self.format_paths(self._get_paths(subdirs=False)) |
| 445 |
|
| 446 |
def _all_directories(self, dir): |
| 447 |
results = [] |
| 448 |
results.append(dir) |
| 449 |
for root, subdirs, files in os.walk(dir, followlinks=True): |
| 450 |
if '__init__.py' in files: |
| 451 |
for x in subdirs: |
| 452 |
results.append(os.path.join(root, x)) |
| 453 |
return results |
| 454 |
|
| 455 |
def _get_package_paths(self, subdirs=True): |
| 456 |
""" Gets the path of a Python package """ |
| 457 |
|
| 458 |
if not self.package: |
| 459 |
return [] |
| 460 |
if not hasattr(self, 'package_path'): |
| 461 |
m = __import__(self.package) |
| 462 |
parts = self.package.split('.')[1:] |
| 463 |
for parent_mod in parts: |
| 464 |
m = getattr(m, parent_mod) |
| 465 |
self.package_path = to_text(os.path.dirname(m.__file__), errors='surrogate_or_strict') |
| 466 |
if subdirs: |
| 467 |
return self._all_directories(self.package_path) |
| 468 |
return [self.package_path] |
| 469 |
|
| 470 |
def _get_paths_with_context(self, subdirs=True): |
| 471 |
""" Return a list of PluginPathContext objects to search for plugins in """ |
| 472 |
|
| 473 |
# FIXME: This is potentially buggy if subdirs is sometimes True and sometimes False. |
| 474 |
# In current usage, everything calls this with subdirs=True except for module_utils_loader and ansible-doc |
| 475 |
# which always calls it with subdirs=False. So there currently isn't a problem with this caching. |
| 476 |
if self._paths is not None: |
| 477 |
return self._paths |
| 478 |
|
| 479 |
ret = [PluginPathContext(p, False) for p in self._extra_dirs] |
| 480 |
|
| 481 |
# look in any configured plugin paths, allow one level deep for subcategories |
| 482 |
if self.config is not None: |
| 483 |
for path in self.config: |
| 484 |
path = os.path.abspath(os.path.expanduser(path)) |
| 485 |
if subdirs: |
| 486 |
contents = glob.glob("%s/*" % path) + glob.glob("%s/*/*" % path) |
| 487 |
for c in contents: |
| 488 |
c = to_text(c, errors='surrogate_or_strict') |
| 489 |
if os.path.isdir(c) and c not in ret: |
| 490 |
ret.append(PluginPathContext(c, False)) |
| 491 |
|
| 492 |
path = to_text(path, errors='surrogate_or_strict') |
| 493 |
if path not in ret: |
| 494 |
ret.append(PluginPathContext(path, False)) |
| 495 |
|
| 496 |
# look for any plugins installed in the package subtree |
| 497 |
# Note package path always gets added last so that every other type of |
| 498 |
# path is searched before it. |
| 499 |
ret.extend([PluginPathContext(p, True) for p in self._get_package_paths(subdirs=subdirs)]) |
| 500 |
|
| 501 |
# HACK: because powershell modules are in the same directory |
| 502 |
# hierarchy as other modules we have to process them last. This is |
| 503 |
# because powershell only works on windows but the other modules work |
| 504 |
# anywhere (possibly including windows if the correct language |
| 505 |
# interpreter is installed). the non-powershell modules can have any |
| 506 |
# file extension and thus powershell modules are picked up in that. |
| 507 |
# The non-hack way to fix this is to have powershell modules be |
| 508 |
# a different PluginLoader/ModuleLoader. But that requires changing |
| 509 |
# other things too (known thing to change would be PATHS_CACHE, |
| 510 |
# PLUGIN_PATHS_CACHE, and MODULE_CACHE. Since those three dicts key |
| 511 |
# on the class_name and neither regular modules nor powershell modules |
| 512 |
# would have class_names, they would not work as written. |
| 513 |
# |
| 514 |
# The expected sort order is paths in the order in 'ret' with paths ending in '/windows' at the end, |
| 515 |
# also in the original order they were found in 'ret'. |
| 516 |
# The .sort() method is guaranteed to be stable, so original order is preserved. |
| 517 |
ret.sort(key=lambda p: p.path.endswith('/windows')) |
| 518 |
|
| 519 |
# cache and return the result |
| 520 |
self._paths = ret |
| 521 |
return ret |
| 522 |
|
| 523 |
def _get_paths(self, subdirs=True): |
| 524 |
""" Return a list of paths to search for plugins in """ |
| 525 |
|
| 526 |
paths_with_context = self._get_paths_with_context(subdirs=subdirs) |
| 527 |
return [path_with_context.path for path_with_context in paths_with_context] |
| 528 |
|
| 529 |
def _load_config_defs(self, name, module, path): |
| 530 |
""" Reads plugin docs to find configuration setting definitions, to push to config manager for later use """ |
| 531 |
|
| 532 |
# plugins w/o class name don't support config |
| 533 |
if self.class_name: |
| 534 |
type_name = get_plugin_class(self.class_name) |
| 535 |
|
| 536 |
# if type name != 'module_doc_fragment': |
| 537 |
if type_name in C.CONFIGURABLE_PLUGINS and not C.config.has_configuration_definition(type_name, name): |
| 538 |
# trust-tagged source propagates to loaded values; expressions and templates in config require trust |
| 539 |
documentation_source = _tags.TrustedAsTemplate().tag(getattr(module, 'DOCUMENTATION', '')) |
| 540 |
try: |
| 541 |
dstring = yaml.load(_tags.Origin(path=path).tag(documentation_source), Loader=AnsibleLoader) |
| 542 |
except ParserError as e: |
| 543 |
raise AnsibleError(f"plugin {name} has malformed documentation!") from e |
| 544 |
|
| 545 |
# TODO: allow configurable plugins to use sidecar |
| 546 |
# if not dstring: |
| 547 |
# filename, cn = find_plugin_docfile( name, type_name, self, [os.path.dirname(path)], C.YAML_DOC_EXTENSIONS) |
| 548 |
|
| 549 |
if dstring: |
| 550 |
add_fragments(dstring, path, fragment_loader=fragment_loader, is_module=(type_name == 'module'), section='DOCUMENTATION') |
| 551 |
|
| 552 |
if 'options' in dstring and isinstance(dstring['options'], dict): |
| 553 |
C.config.initialize_plugin_configuration_definitions(type_name, name, dstring['options']) |
| 554 |
display.debug('Loaded config def from plugin (%s/%s)' % (type_name, name)) |
| 555 |
|
| 556 |
def add_directory(self, directory, with_subdir=False): |
| 557 |
""" Adds an additional directory to the search path """ |
| 558 |
|
| 559 |
directory = os.path.realpath(directory) |
| 560 |
|
| 561 |
if directory is not None: |
| 562 |
if with_subdir: |
| 563 |
directory = os.path.join(directory, self.subdir) |
| 564 |
if directory not in self._extra_dirs: |
| 565 |
# append the directory and invalidate the path cache |
| 566 |
self._extra_dirs.append(directory) |
| 567 |
self._clear_caches() |
| 568 |
display.debug('Added %s to loader search path' % (directory)) |
| 569 |
|
| 570 |
def _query_collection_routing_meta(self, acr, plugin_type, extension=None): |
| 571 |
try: |
| 572 |
if not (collection_pkg := import_module(acr.n_python_collection_package_name)): |
| 573 |
return None |
| 574 |
except ImportError: |
| 575 |
return None |
| 576 |
|
| 577 |
# FIXME: shouldn't need this... |
| 578 |
try: |
| 579 |
# force any type-specific metadata postprocessing to occur |
| 580 |
import_module(acr.n_python_collection_package_name + '.plugins.{0}'.format(plugin_type)) |
| 581 |
except ImportError: |
| 582 |
pass |
| 583 |
|
| 584 |
# this will be created by the collection PEP302 loader |
| 585 |
collection_meta = getattr(collection_pkg, '_collection_meta', None) |
| 586 |
|
| 587 |
if not collection_meta: |
| 588 |
return None |
| 589 |
|
| 590 |
# TODO: add subdirs support |
| 591 |
# check for extension-specific entry first (eg 'setup.ps1') |
| 592 |
# TODO: str/bytes on extension/name munging |
| 593 |
if acr.subdirs: |
| 594 |
subdir_qualified_resource = '.'.join([acr.subdirs, acr.resource]) |
| 595 |
else: |
| 596 |
subdir_qualified_resource = acr.resource |
| 597 |
entry = collection_meta.get('plugin_routing', {}).get(plugin_type, {}).get(subdir_qualified_resource + (extension or ''), None) |
| 598 |
if not entry: |
| 599 |
# try for extension-agnostic entry |
| 600 |
entry = collection_meta.get('plugin_routing', {}).get(plugin_type, {}).get(subdir_qualified_resource, None) |
| 601 |
return entry |
| 602 |
|
| 603 |
def _find_fq_plugin( |
| 604 |
self, |
| 605 |
fq_name: str, |
| 606 |
extension: str | None, |
| 607 |
plugin_load_context: PluginLoadContext, |
| 608 |
) -> PluginLoadContext: |
| 609 |
"""Search builtin paths to find a plugin. No external paths are searched, |
| 610 |
meaning plugins inside roles inside collections will be ignored. |
| 611 |
""" |
| 612 |
|
| 613 |
plugin_load_context.resolved = False |
| 614 |
|
| 615 |
plugin_type = AnsibleCollectionRef.legacy_plugin_dir_to_plugin_type(self.subdir) |
| 616 |
|
| 617 |
acr = AnsibleCollectionRef.from_fqcr(fq_name, plugin_type) |
| 618 |
|
| 619 |
# check collection metadata to see if any special handling is required for this plugin |
| 620 |
routing_metadata = self._query_collection_routing_meta(acr, plugin_type, extension=extension) |
| 621 |
|
| 622 |
action_plugin = None |
| 623 |
# TODO: factor this into a wrapper method |
| 624 |
if routing_metadata: |
| 625 |
deprecation = routing_metadata.get('deprecation', None) |
| 626 |
|
| 627 |
# this will no-op if there's no deprecation metadata for this plugin |
| 628 |
plugin_load_context.record_deprecation(fq_name, deprecation, acr.collection) |
| 629 |
|
| 630 |
tombstone = routing_metadata.get('tombstone', None) |
| 631 |
|
| 632 |
# FIXME: clean up text gen |
| 633 |
if tombstone: |
| 634 |
removal_date = tombstone.get('removal_date') |
| 635 |
removal_version = tombstone.get('removal_version') |
| 636 |
warning_text = tombstone.get('warning_text') or '' |
| 637 |
warning_plugin_type = "module" if self.type == "modules" else f'{self.type} plugin' |
| 638 |
warning_text = f'The {fq_name!r} {warning_plugin_type} has been removed.{" " if warning_text else ""}{warning_text}' |
| 639 |
removed_msg = _display_utils.get_deprecation_message_with_plugin_info( |
| 640 |
msg=warning_text, |
| 641 |
version=removal_version, |
| 642 |
date=removal_date, |
| 643 |
removed=True, |
| 644 |
deprecator=deprecator_from_collection_name(acr.collection), |
| 645 |
) |
| 646 |
plugin_load_context.date = removal_date |
| 647 |
plugin_load_context.version = removal_version |
| 648 |
plugin_load_context.resolved = True |
| 649 |
plugin_load_context.exit_reason = removed_msg |
| 650 |
raise AnsiblePluginRemovedError(message=removed_msg, plugin_load_context=plugin_load_context) |
| 651 |
|
| 652 |
redirect = routing_metadata.get('redirect', None) |
| 653 |
|
| 654 |
if redirect: |
| 655 |
# Prevent mystery redirects that would be determined by the collections keyword |
| 656 |
if not AnsibleCollectionRef.is_valid_fqcr(redirect): |
| 657 |
raise AnsibleError( |
| 658 |
f"Collection {acr.collection} contains invalid redirect for {fq_name}: {redirect}. " |
| 659 |
"Redirects must use fully qualified collection names." |
| 660 |
) |
| 661 |
|
| 662 |
# FIXME: remove once this is covered in debug or whatever |
| 663 |
display.vv("redirecting (type: {0}) {1} to {2}".format(plugin_type, fq_name, redirect)) |
| 664 |
|
| 665 |
# The name doing the redirection is added at the beginning of _resolve_plugin_step, |
| 666 |
# but if the unqualified name is used in conjunction with the collections keyword, only |
| 667 |
# the unqualified name is in the redirect list. |
| 668 |
if fq_name not in plugin_load_context.redirect_list: |
| 669 |
plugin_load_context.redirect_list.append(fq_name) |
| 670 |
return plugin_load_context.redirect(redirect) |
| 671 |
# TODO: non-FQCN case, do we support `.` prefix for current collection, assume it with no dots, require it for subdirs in current, or ? |
| 672 |
|
| 673 |
if self.type == 'modules': |
| 674 |
action_plugin = routing_metadata.get('action_plugin') |
| 675 |
|
| 676 |
n_resource = to_native(acr.resource, errors='strict') |
| 677 |
# we want this before the extension is added |
| 678 |
full_name = '{0}.{1}'.format(acr.n_python_package_name, n_resource) |
| 679 |
|
| 680 |
if extension: |
| 681 |
n_resource += extension |
| 682 |
|
| 683 |
pkg = sys.modules.get(acr.n_python_package_name) |
| 684 |
if not pkg: |
| 685 |
# FIXME: there must be cheaper/safer way to do this |
| 686 |
try: |
| 687 |
pkg = import_module(acr.n_python_package_name) |
| 688 |
except ImportError: |
| 689 |
return plugin_load_context.nope('Python package {0} not found'.format(acr.n_python_package_name)) |
| 690 |
|
| 691 |
pkg_path = os.path.dirname(pkg.__file__) |
| 692 |
|
| 693 |
n_resource_path = os.path.join(pkg_path, n_resource) |
| 694 |
|
| 695 |
# FIXME: and is file or file link or ... |
| 696 |
if os.path.exists(n_resource_path): |
| 697 |
return plugin_load_context.resolve( |
| 698 |
full_name, to_text(n_resource_path), acr.collection, 'found exact match for {0} in {1}'.format(full_name, acr.collection), action_plugin) |
| 699 |
|
| 700 |
if extension: |
| 701 |
# the request was extension-specific, don't try for an extensionless match |
| 702 |
return plugin_load_context.nope('no match for {0} in {1}'.format(to_text(n_resource), acr.collection)) |
| 703 |
|
| 704 |
# look for any matching extension in the package location (sans filter) |
| 705 |
found_files = [f |
| 706 |
for f in glob.iglob(os.path.join(pkg_path, n_resource) + '.*') |
| 707 |
if os.path.isfile(f) and not any(f.endswith(ext) for ext in C.MODULE_IGNORE_EXTS)] |
| 708 |
|
| 709 |
if not found_files: |
| 710 |
return plugin_load_context.nope('failed fuzzy extension match for {0} in {1}'.format(full_name, acr.collection)) |
| 711 |
|
| 712 |
found_files = sorted(found_files) # sort to ensure deterministic results, with the shortest match first |
| 713 |
|
| 714 |
if len(found_files) > 1: |
| 715 |
display.debug('Found several possible candidates for the plugin but using first: %s' % ','.join(found_files)) |
| 716 |
|
| 717 |
return plugin_load_context.resolve( |
| 718 |
full_name, to_text(found_files[0]), acr.collection, |
| 719 |
'found fuzzy extension match for {0} in {1}'.format(full_name, acr.collection), action_plugin) |
| 720 |
|
| 721 |
def find_plugin(self, name, mod_type='', ignore_deprecated=False, check_aliases=False, collection_list=None): |
| 722 |
""" Find a plugin named name """ |
| 723 |
result = self.find_plugin_with_context(name, mod_type, ignore_deprecated, check_aliases, collection_list) |
| 724 |
if result.resolved and result.plugin_resolved_path: |
| 725 |
return result.plugin_resolved_path |
| 726 |
|
| 727 |
return None |
| 728 |
|
| 729 |
def find_plugin_with_context( |
| 730 |
self, |
| 731 |
name: str, |
| 732 |
mod_type: str = '', |
| 733 |
ignore_deprecated: bool = False, |
| 734 |
check_aliases: bool = False, |
| 735 |
collection_list: list[str] | None = None, |
| 736 |
) -> PluginLoadContext: |
| 737 |
""" Find a plugin named name, returning contextual info about the load, recursively resolving redirection """ |
| 738 |
plugin_load_context = PluginLoadContext(self.type, self.package, ignore_deprecated=ignore_deprecated) |
| 739 |
plugin_load_context.original_name = name |
| 740 |
while True: |
| 741 |
result = self._resolve_plugin_step(name, mod_type, check_aliases, collection_list, plugin_load_context=plugin_load_context) |
| 742 |
if result.pending_redirect: |
| 743 |
if result.pending_redirect in result.redirect_list: |
| 744 |
raise AnsiblePluginCircularRedirect('plugin redirect loop resolving {0} (path: {1})'.format(result.original_name, result.redirect_list)) |
| 745 |
name = result.pending_redirect |
| 746 |
result.pending_redirect = None |
| 747 |
plugin_load_context = result |
| 748 |
else: |
| 749 |
break |
| 750 |
|
| 751 |
for ex in plugin_load_context.raw_error_list: |
| 752 |
display.error_as_warning(f"Error loading plugin {name!r}.", ex) |
| 753 |
|
| 754 |
# FIXME: store structured deprecation data in PluginLoadContext and use display.deprecate |
| 755 |
# if plugin_load_context.deprecated and C.config.get_config_value('DEPRECATION_WARNINGS'): |
| 756 |
# for dw in plugin_load_context.deprecation_warnings: |
| 757 |
# # TODO: need to smuggle these to the controller if we're in a worker context |
| 758 |
# display.warning('[DEPRECATION WARNING] ' + dw) |
| 759 |
|
| 760 |
return plugin_load_context |
| 761 |
|
| 762 |
def _resolve_plugin_step( |
| 763 |
self, |
| 764 |
name: str, |
| 765 |
mod_type: str = '', |
| 766 |
check_aliases: bool = False, |
| 767 |
collection_list: list[str] | None = None, |
| 768 |
plugin_load_context: PluginLoadContext | None = None, |
| 769 |
) -> PluginLoadContext: |
| 770 |
if not plugin_load_context: |
| 771 |
raise ValueError('A PluginLoadContext is required') |
| 772 |
|
| 773 |
plugin_load_context.redirect_list.append(name) |
| 774 |
plugin_load_context.resolved = False |
| 775 |
|
| 776 |
if name in _PLUGIN_FILTERS[self.package]: |
| 777 |
plugin_load_context.exit_reason = '{0} matched a defined plugin filter'.format(name) |
| 778 |
return plugin_load_context |
| 779 |
|
| 780 |
if mod_type: |
| 781 |
suffix = mod_type |
| 782 |
elif self.class_name: |
| 783 |
# Ansible plugins that run in the controller process (most plugins) |
| 784 |
suffix = '.py' |
| 785 |
else: |
| 786 |
# Only Ansible Modules. Ansible modules can be any executable so |
| 787 |
# they can have any suffix |
| 788 |
suffix = '' |
| 789 |
|
| 790 |
# FIXME: need this right now so we can still load shipped PS module_utils- come up with a more robust solution |
| 791 |
if (AnsibleCollectionRef.is_valid_fqcr(name) or collection_list) and not name.startswith('Ansible'): |
| 792 |
if '.' in name or not collection_list: |
| 793 |
candidates = [name] |
| 794 |
else: |
| 795 |
candidates = ['{0}.{1}'.format(c, name) for c in collection_list] |
| 796 |
|
| 797 |
for candidate_name in candidates: |
| 798 |
try: |
| 799 |
plugin_load_context.load_attempts.append(candidate_name) |
| 800 |
# HACK: refactor this properly |
| 801 |
if candidate_name.startswith('ansible.legacy'): |
| 802 |
# 'ansible.legacy' refers to the plugin finding behavior used before collections existed. |
| 803 |
# They need to search 'library' and the various '*_plugins' directories in order to find the file. |
| 804 |
plugin_load_context = self._find_plugin_legacy(name.removeprefix('ansible.legacy.'), |
| 805 |
plugin_load_context, check_aliases, suffix) |
| 806 |
else: |
| 807 |
# 'ansible.builtin' should be handled here. This means only internal, or builtin, paths are searched. |
| 808 |
plugin_load_context = self._find_fq_plugin(candidate_name, suffix, plugin_load_context=plugin_load_context) |
| 809 |
|
| 810 |
# Pending redirects are added to the redirect_list at the beginning of _resolve_plugin_step. |
| 811 |
# Once redirects are resolved, ensure the final FQCN is added here. |
| 812 |
# e.g. 'ns.coll.module' is included rather than only 'module' if a collections list is provided: |
| 813 |
# - module: |
| 814 |
# collections: ['ns.coll'] |
| 815 |
if plugin_load_context.resolved and candidate_name not in plugin_load_context.redirect_list: |
| 816 |
plugin_load_context.redirect_list.append(candidate_name) |
| 817 |
|
| 818 |
if plugin_load_context.resolved or plugin_load_context.pending_redirect: # if we got an answer or need to chase down a redirect, return |
| 819 |
return plugin_load_context |
| 820 |
except (AnsiblePluginRemovedError, AnsiblePluginCircularRedirect, AnsibleCollectionUnsupportedVersionError): |
| 821 |
# these are generally fatal, let them fly |
| 822 |
raise |
| 823 |
except Exception as ex: |
| 824 |
plugin_load_context.raw_error_list.append(ex) |
| 825 |
|
| 826 |
# DTFIX-FUTURE: can we deprecate/remove these stringified versions? |
| 827 |
if isinstance(ex, ImportError): |
| 828 |
plugin_load_context.import_error_list.append(ex) |
| 829 |
else: |
| 830 |
plugin_load_context.error_list.append(str(ex)) |
| 831 |
|
| 832 |
if plugin_load_context.error_list: |
| 833 |
display.debug(msg='plugin lookup for {0} failed; errors: {1}'.format(name, '; '.join(plugin_load_context.error_list))) |
| 834 |
|
| 835 |
plugin_load_context.exit_reason = 'no matches found for {0}'.format(name) |
| 836 |
|
| 837 |
return plugin_load_context |
| 838 |
|
| 839 |
# if we got here, there's no collection list and it's not an FQ name, so do legacy lookup |
| 840 |
|
| 841 |
return self._find_plugin_legacy(name, plugin_load_context, check_aliases, suffix) |
| 842 |
|
| 843 |
@functools.lru_cache(maxsize=100) |
| 844 |
def _get_builtin_routing_metadata(self, name: str) -> dict[str, t.Any]: |
| 845 |
"""Cached metadata lookups for core plugins.""" |
| 846 |
routing_metadata = self._query_collection_routing_meta(acr := AnsibleCollectionRef.from_fqcr(f'ansible.builtin.{name}', self.type), self.type) |
| 847 |
|
| 848 |
return routing_metadata or {} |
| 849 |
|
| 850 |
def _check_core_deprecation(self, name: str, plugin_load_context: PluginLoadContext) -> None: |
| 851 |
""" |
| 852 |
Inspect core runtime metadata for deprecations on core plugins loaded through a non-collection name. |
| 853 |
|
| 854 |
This method has no effect for non-core plugins loaded through a short name, and is not needed for collection plugins. |
| 855 |
""" |
| 856 |
if not plugin_load_context.resolved or plugin_load_context.plugin_resolved_collection != 'ansible.builtin': |
| 857 |
return |
| 858 |
|
| 859 |
if (routing_metadata := self._get_builtin_routing_metadata(name)) and (deprecation := routing_metadata.get('deprecation')): |
| 860 |
plugin_load_context.record_deprecation(name, deprecation, 'ansible.builtin') |
| 861 |
|
| 862 |
def _find_plugin_legacy(self, name, plugin_load_context, check_aliases=False, suffix=None): |
| 863 |
"""Search library and various *_plugins paths in order to find the file. |
| 864 |
This was behavior prior to the existence of collections. |
| 865 |
""" |
| 866 |
plugin_load_context.resolved = False |
| 867 |
|
| 868 |
if check_aliases: |
| 869 |
name = self._aliases.get(name, name) |
| 870 |
|
| 871 |
# The particular cache to look for modules within. This matches the |
| 872 |
# requested mod_type |
| 873 |
pull_cache = self._plugin_path_cache[suffix] |
| 874 |
try: |
| 875 |
resolved = plugin_load_context.resolve_legacy(name=name, pull_cache=pull_cache) |
| 876 |
self._check_core_deprecation(name, plugin_load_context) |
| 877 |
|
| 878 |
return resolved |
| 879 |
except KeyError: |
| 880 |
# Cache miss. Now let's find the plugin |
| 881 |
pass |
| 882 |
|
| 883 |
# TODO: Instead of using the self._paths cache (PATH_CACHE) and |
| 884 |
# self._searched_paths we could use an iterator. Before enabling that |
| 885 |
# we need to make sure we don't want to add additional directories |
| 886 |
# (add_directory()) once we start using the iterator. |
| 887 |
# We can use _get_paths_with_context() since add_directory() forces a cache refresh. |
| 888 |
for path_with_context in (p for p in self._get_paths_with_context() if p.path not in self._searched_paths and os.path.isdir(to_bytes(p.path))): |
| 889 |
path = path_with_context.path |
| 890 |
b_path = to_bytes(path) |
| 891 |
display.debug('trying %s' % path) |
| 892 |
plugin_load_context.load_attempts.append(path) |
| 893 |
internal = path_with_context.internal |
| 894 |
try: |
| 895 |
full_paths = (os.path.join(b_path, f) for f in os.listdir(b_path)) |
| 896 |
except OSError as e: |
| 897 |
display.warning("Error accessing plugin paths: %s" % to_text(e)) |
| 898 |
|
| 899 |
for full_path in (to_native(f) for f in full_paths if os.path.isfile(f) and not f.endswith(b'__init__.py')): |
| 900 |
full_name = os.path.basename(full_path) |
| 901 |
|
| 902 |
# HACK: We have no way of executing python byte compiled files as ansible modules so specifically exclude them |
| 903 |
# FIXME: I believe this is only correct for modules and module_utils. |
| 904 |
# For all other plugins we want .pyc and .pyo should be valid |
| 905 |
if any(full_path.endswith(x) for x in C.MODULE_IGNORE_EXTS): |
| 906 |
continue |
| 907 |
splitname = os.path.splitext(full_name) |
| 908 |
base_name = splitname[0] |
| 909 |
try: |
| 910 |
extension = splitname[1] |
| 911 |
except IndexError: |
| 912 |
extension = '' |
| 913 |
|
| 914 |
# everything downstream expects unicode |
| 915 |
full_path = to_text(full_path, errors='surrogate_or_strict') |
| 916 |
# Module found, now enter it into the caches that match this file |
| 917 |
if base_name not in self._plugin_path_cache['']: |
| 918 |
self._plugin_path_cache[''][base_name] = PluginPathContext(full_path, internal) |
| 919 |
|
| 920 |
if full_name not in self._plugin_path_cache['']: |
| 921 |
self._plugin_path_cache[''][full_name] = PluginPathContext(full_path, internal) |
| 922 |
|
| 923 |
if base_name not in self._plugin_path_cache[extension]: |
| 924 |
self._plugin_path_cache[extension][base_name] = PluginPathContext(full_path, internal) |
| 925 |
|
| 926 |
if full_name not in self._plugin_path_cache[extension]: |
| 927 |
self._plugin_path_cache[extension][full_name] = PluginPathContext(full_path, internal) |
| 928 |
|
| 929 |
self._searched_paths.add(path) |
| 930 |
try: |
| 931 |
resolved = plugin_load_context.resolve_legacy(name=name, pull_cache=pull_cache) |
| 932 |
self._check_core_deprecation(name, plugin_load_context) |
| 933 |
|
| 934 |
return resolved |
| 935 |
except KeyError: |
| 936 |
# Didn't find the plugin in this directory. Load modules from the next one |
| 937 |
pass |
| 938 |
|
| 939 |
# if nothing is found, try finding alias/deprecated |
| 940 |
if not name.startswith('_'): |
| 941 |
alias_name = '_' + name |
| 942 |
|
| 943 |
try: |
| 944 |
plugin_load_context.resolve_legacy(name=alias_name, pull_cache=pull_cache) |
| 945 |
except KeyError: |
| 946 |
pass |
| 947 |
else: |
| 948 |
display.deprecated( |
| 949 |
msg=f'Plugin {name!r} automatically redirected to {alias_name!r}.', |
| 950 |
help_text=f'Use {alias_name!r} instead of {name!r} to refer to the plugin.', |
| 951 |
version='2.23', |
| 952 |
) |
| 953 |
|
| 954 |
return plugin_load_context |
| 955 |
|
| 956 |
# last ditch, if it's something that can be redirected, look for a builtin redirect before giving up |
| 957 |
candidate_fqcr = 'ansible.builtin.{0}'.format(name) |
| 958 |
if '.' not in name and AnsibleCollectionRef.is_valid_fqcr(candidate_fqcr): |
| 959 |
return self._find_fq_plugin(fq_name=candidate_fqcr, extension=suffix, plugin_load_context=plugin_load_context) |
| 960 |
|
| 961 |
return plugin_load_context.nope('{0} is not eligible for last-chance resolution'.format(name)) |
| 962 |
|
| 963 |
def has_plugin(self, name: str, collection_list: list[str] | None = None) -> bool: |
| 964 |
""" Checks if a plugin named name exists """ |
| 965 |
|
| 966 |
try: |
| 967 |
return self.find_plugin(name, collection_list=collection_list) is not None |
| 968 |
except Exception as ex: |
| 969 |
if isinstance(ex, AnsibleError): |
| 970 |
raise |
| 971 |
# log and continue, likely an innocuous type/package loading failure in collections import |
| 972 |
display.debug('has_plugin error: {0}'.format(to_text(ex))) |
| 973 |
|
| 974 |
return False |
| 975 |
|
| 976 |
__contains__ = has_plugin |
| 977 |
|
| 978 |
def _load_module_source(self, *, python_module_name: str, path: str) -> types.ModuleType: |
| 979 |
if python_module_name in sys.modules: |
| 980 |
# Avoids double loading, See https://github.com/ansible/ansible/issues/13110 |
| 981 |
return sys.modules[python_module_name] |
| 982 |
|
| 983 |
with warnings.catch_warnings(): |
| 984 |
# FIXME: this still has issues if the module was previously imported but not "cached", |
| 985 |
# we should bypass this entire codepath for things that are directly importable |
| 986 |
warnings.simplefilter("ignore", RuntimeWarning) |
| 987 |
spec = importlib.util.spec_from_file_location(to_native(python_module_name), to_native(path)) |
| 988 |
module = importlib.util.module_from_spec(spec) |
| 989 |
|
| 990 |
# mimic import machinery; make the module-being-loaded available in sys.modules during import |
| 991 |
# and remove if there's a failure... |
| 992 |
sys.modules[python_module_name] = module |
| 993 |
|
| 994 |
try: |
| 995 |
spec.loader.exec_module(module) |
| 996 |
except Exception: |
| 997 |
del sys.modules[python_module_name] |
| 998 |
raise |
| 999 |
|
| 1000 |
return module |
| 1001 |
|
| 1002 |
def _update_object( |
| 1003 |
self, |
| 1004 |
*, |
| 1005 |
obj: _AnsiblePluginInfoMixin, |
| 1006 |
name: str, |
| 1007 |
path: str, |
| 1008 |
redirected_names: list[str] | None = None, |
| 1009 |
resolved: str | None = None, |
| 1010 |
) -> None: |
| 1011 |
# DTFIX-FUTURE: clean this up- standardize types, document, split/remove redundant bits |
| 1012 |
|
| 1013 |
# set extra info on the module, in case we want it later |
| 1014 |
obj._original_path = path |
| 1015 |
obj._load_name = name |
| 1016 |
obj._redirected_names = redirected_names or [] |
| 1017 |
|
| 1018 |
names = [] |
| 1019 |
if resolved: |
| 1020 |
names.append(resolved) |
| 1021 |
if redirected_names: |
| 1022 |
# reverse list so best name comes first |
| 1023 |
names.extend(redirected_names[::-1]) |
| 1024 |
if not names: |
| 1025 |
raise AnsibleError(f"Missing FQCN for plugin source {name}") |
| 1026 |
|
| 1027 |
obj.ansible_aliases = names |
| 1028 |
obj.ansible_name = names[0] |
| 1029 |
|
| 1030 |
def get(self, name, *args, **kwargs): |
| 1031 |
ctx = self.get_with_context(name, *args, **kwargs) |
| 1032 |
is_core_plugin = ctx.plugin_load_context.plugin_resolved_collection == 'ansible.builtin' |
| 1033 |
if self.class_name == 'StrategyModule' and not is_core_plugin: |
| 1034 |
display.deprecated( # pylint: disable=ansible-deprecated-no-version |
| 1035 |
msg='Use of strategy plugins not included in ansible.builtin are deprecated and do not carry ' |
| 1036 |
'any backwards compatibility guarantees. No alternative for third party strategy plugins ' |
| 1037 |
'is currently planned.', |
| 1038 |
) |
| 1039 |
|
| 1040 |
return ctx.object |
| 1041 |
|
| 1042 |
def get_with_context(self, name, *args, **kwargs) -> get_with_context_result: |
| 1043 |
""" instantiates a plugin of the given name using arguments """ |
| 1044 |
|
| 1045 |
if not name: |
| 1046 |
raise ValueError('A non-empty plugin name is required.') |
| 1047 |
|
| 1048 |
found_in_cache = True |
| 1049 |
class_only = kwargs.pop('class_only', False) |
| 1050 |
collection_list = kwargs.pop('collection_list', None) |
| 1051 |
if name in self._aliases: |
| 1052 |
name = self._aliases[name] |
| 1053 |
|
| 1054 |
if (cached_result := (self._plugin_instance_cache or {}).get(name)) and cached_result[1].resolved: |
| 1055 |
# Resolving the FQCN is slow, even if we've passed in the resolved FQCN. |
| 1056 |
# Short-circuit here if we've previously resolved this name. |
| 1057 |
# This will need to be restricted if non-vars plugins start using the cache, since |
| 1058 |
# some non-fqcn plugin need to be resolved again with the collections list. |
| 1059 |
return get_with_context_result(*cached_result) |
| 1060 |
|
| 1061 |
plugin_load_context = self.find_plugin_with_context(name, collection_list=collection_list) |
| 1062 |
if not plugin_load_context.resolved or not plugin_load_context.plugin_resolved_path: |
| 1063 |
# FIXME: this is probably an error (eg removed plugin) |
| 1064 |
return get_with_context_result(None, plugin_load_context) |
| 1065 |
|
| 1066 |
fq_name = plugin_load_context.resolved_fqcn |
| 1067 |
resolved_type_name = plugin_load_context.plugin_resolved_name |
| 1068 |
path = plugin_load_context.plugin_resolved_path |
| 1069 |
if (cached_result := (self._plugin_instance_cache or {}).get(fq_name)) and cached_result[1].resolved: |
| 1070 |
# This is unused by vars plugins, but it's here in case the instance cache expands to other plugin types. |
| 1071 |
# We get here if we've seen this plugin before, but it wasn't called with the resolved FQCN. |
| 1072 |
return get_with_context_result(*cached_result) |
| 1073 |
redirected_names = plugin_load_context.redirect_list or [] |
| 1074 |
|
| 1075 |
if path not in self._module_cache: |
| 1076 |
self._module_cache[path] = self._load_module_source(python_module_name=plugin_load_context._python_module_name, path=path) |
| 1077 |
found_in_cache = False |
| 1078 |
|
| 1079 |
self._load_config_defs(resolved_type_name, self._module_cache[path], path) |
| 1080 |
|
| 1081 |
obj = getattr(self._module_cache[path], self.class_name) |
| 1082 |
|
| 1083 |
if self.base_class: |
| 1084 |
# The import path is hardcoded and should be the right place, |
| 1085 |
# so we are not expecting an ImportError. |
| 1086 |
module = __import__(self.package, fromlist=[self.base_class]) |
| 1087 |
# Check whether this obj has the required base class. |
| 1088 |
try: |
| 1089 |
plugin_class = getattr(module, self.base_class) |
| 1090 |
except AttributeError: |
| 1091 |
return get_with_context_result(None, plugin_load_context) |
| 1092 |
if not issubclass(obj, plugin_class): |
| 1093 |
display.warning(f"Ignoring {self.type} plugin {resolved_type_name!r} due to missing base class {self.base_class!r}.") |
| 1094 |
return get_with_context_result(None, plugin_load_context) |
| 1095 |
|
| 1096 |
# FIXME: update this to use the load context |
| 1097 |
self._display_plugin_load(self.class_name, resolved_type_name, self._searched_paths, path, found_in_cache=found_in_cache, class_only=class_only) |
| 1098 |
|
| 1099 |
if not class_only: |
| 1100 |
try: |
| 1101 |
# A plugin may need to use its _load_name in __init__ (for example, to set |
| 1102 |
# or get options from config), so update the object before using the constructor |
| 1103 |
instance = object.__new__(obj) |
| 1104 |
self._update_object(obj=instance, name=resolved_type_name, path=path, redirected_names=redirected_names, resolved=fq_name) |
| 1105 |
obj.__init__(instance, *args, **kwargs) # pylint: disable=unnecessary-dunder-call |
| 1106 |
obj = instance |
| 1107 |
except TypeError as e: |
| 1108 |
if "abstract" in e.args[0]: |
| 1109 |
# Abstract Base Class or incomplete plugin, don't load |
| 1110 |
display.v('Returning not found on "%s" as it has unimplemented abstract methods; %s' % (resolved_type_name, to_native(e))) |
| 1111 |
return get_with_context_result(None, plugin_load_context) |
| 1112 |
raise |
| 1113 |
|
| 1114 |
self._update_object(obj=obj, name=resolved_type_name, path=path, redirected_names=redirected_names, resolved=fq_name) |
| 1115 |
if self._plugin_instance_cache is not None and getattr(obj, 'is_stateless', False): |
| 1116 |
self._plugin_instance_cache[fq_name] = (obj, plugin_load_context) |
| 1117 |
elif self._plugin_instance_cache is not None: |
| 1118 |
# The cache doubles as the load order, so record the FQCN even if the plugin hasn't set is_stateless = True |
| 1119 |
self._plugin_instance_cache[fq_name] = (None, PluginLoadContext(self.type, self.package)) |
| 1120 |
return get_with_context_result(obj, plugin_load_context) |
| 1121 |
|
| 1122 |
def _display_plugin_load(self, class_name, name, searched_paths, path, found_in_cache=None, class_only=None): |
| 1123 |
""" formats data to display debug info for plugin loading, also avoids processing unless really needed """ |
| 1124 |
if C.DEFAULT_DEBUG: |
| 1125 |
msg = 'Loading %s \'%s\' from %s' % (class_name, os.path.basename(name), path) |
| 1126 |
|
| 1127 |
if len(searched_paths) > 1: |
| 1128 |
msg = '%s (searched paths: %s)' % (msg, self.format_paths(searched_paths)) |
| 1129 |
|
| 1130 |
if found_in_cache or class_only: |
| 1131 |
msg = '%s (found_in_cache=%s, class_only=%s)' % (msg, found_in_cache, class_only) |
| 1132 |
|
| 1133 |
display.debug(msg) |
| 1134 |
|
| 1135 |
def all(self, *args, **kwargs): |
| 1136 |
""" |
| 1137 |
Iterate through all plugins of this type, in configured paths (no collections) |
| 1138 |
|
| 1139 |
A plugin loader is initialized with a specific type. This function is an iterator returning |
| 1140 |
all of the plugins of that type to the caller. |
| 1141 |
|
| 1142 |
:kwarg path_only: If this is set to True, then we return the paths to where the plugins reside |
| 1143 |
instead of an instance of the plugin. This conflicts with class_only and both should |
| 1144 |
not be set. |
| 1145 |
:kwarg class_only: If this is set to True then we return the python class which implements |
| 1146 |
a plugin rather than an instance of the plugin. This conflicts with path_only and both |
| 1147 |
should not be set. |
| 1148 |
:kwarg _dedupe: By default, we only return one plugin per plugin name. Deduplication happens |
| 1149 |
in the same way as the :meth:`get` and :meth:`find_plugin` methods resolve which plugin |
| 1150 |
should take precedence. If this is set to False, then we return all of the plugins |
| 1151 |
found, including those with duplicate names. In the case of duplicates, the order in |
| 1152 |
which they are returned is the one that would take precedence first, followed by the |
| 1153 |
others in decreasing precedence order. This should only be used by subclasses which |
| 1154 |
want to manage their own deduplication of the plugins. |
| 1155 |
:*args: Any extra arguments are passed to each plugin when it is instantiated. |
| 1156 |
:**kwargs: Any extra keyword arguments are passed to each plugin when it is instantiated. |
| 1157 |
""" |
| 1158 |
# TODO: Change the signature of this method to: |
| 1159 |
# def all(return_type='instance', args=None, kwargs=None): |
| 1160 |
# if args is None: args = [] |
| 1161 |
# if kwargs is None: kwargs = {} |
| 1162 |
# return_type can be instance, class, or path. |
| 1163 |
# These changes will mean that plugin parameters won't conflict with our params and |
| 1164 |
# will also make it impossible to request both a path and a class at the same time. |
| 1165 |
# |
| 1166 |
# Move _dedupe to be a class attribute, CUSTOM_DEDUPE, with subclasses for filters and |
| 1167 |
# tests setting it to True |
| 1168 |
|
| 1169 |
dedupe = kwargs.pop('_dedupe', True) |
| 1170 |
path_only = kwargs.pop('path_only', False) |
| 1171 |
class_only = kwargs.pop('class_only', False) |
| 1172 |
# Having both path_only and class_only is a coding bug |
| 1173 |
if path_only and class_only: |
| 1174 |
raise AnsibleError('Do not set both path_only and class_only when calling PluginLoader.all()') |
| 1175 |
|
| 1176 |
all_matches = [] |
| 1177 |
found_in_cache = True |
| 1178 |
|
| 1179 |
legacy_excluding_builtin = set() |
| 1180 |
for path_with_context in self._get_paths_with_context(): |
| 1181 |
matches = glob.glob(to_native(os.path.join(path_with_context.path, "*.py"))) |
| 1182 |
if not path_with_context.internal: |
| 1183 |
legacy_excluding_builtin.update(matches) |
| 1184 |
# we sort within each path, but keep path precedence from config |
| 1185 |
all_matches.extend(sorted(matches, key=os.path.basename)) |
| 1186 |
|
| 1187 |
loaded_modules = set() |
| 1188 |
for path in all_matches: |
| 1189 |
|
| 1190 |
name = os.path.splitext(path)[0] |
| 1191 |
basename = os.path.basename(name) |
| 1192 |
is_j2 = isinstance(self, Jinja2Loader) |
| 1193 |
|
| 1194 |
if path in legacy_excluding_builtin: |
| 1195 |
fqcn = basename |
| 1196 |
else: |
| 1197 |
fqcn = f"ansible.builtin.{basename}" |
| 1198 |
|
| 1199 |
if is_j2: |
| 1200 |
ref_name = path |
| 1201 |
else: |
| 1202 |
ref_name = fqcn |
| 1203 |
|
| 1204 |
if not is_j2 and basename in _PLUGIN_FILTERS[self.package]: |
| 1205 |
# j2 plugins get processed in own class, here they would just be container files |
| 1206 |
display.debug("'%s' skipped due to a defined plugin filter" % basename) |
| 1207 |
continue |
| 1208 |
|
| 1209 |
if basename == '__init__' or (basename == 'base' and self.package == 'ansible.plugins.cache'): |
| 1210 |
# cache has legacy 'base.py' file, which is wrapper for __init__.py |
| 1211 |
display.debug("'%s' skipped due to reserved name" % name) |
| 1212 |
continue |
| 1213 |
|
| 1214 |
if dedupe and ref_name in loaded_modules: |
| 1215 |
# for j2 this is 'same file', other plugins it is basename |
| 1216 |
display.debug("'%s' skipped as duplicate" % ref_name) |
| 1217 |
continue |
| 1218 |
|
| 1219 |
loaded_modules.add(ref_name) |
| 1220 |
|
| 1221 |
if path_only: |
| 1222 |
yield path |
| 1223 |
continue |
| 1224 |
|
| 1225 |
if (cached_result := (self._plugin_instance_cache or {}).get(fqcn)) and cached_result[1].resolved: |
| 1226 |
# Here just in case, but we don't call all() multiple times for vars plugins, so this should not be used. |
| 1227 |
yield cached_result[0] |
| 1228 |
continue |
| 1229 |
|
| 1230 |
if path not in self._module_cache: |
| 1231 |
path_context = PluginPathContext(path, path not in legacy_excluding_builtin) |
| 1232 |
load_context = PluginLoadContext(self.type, self.package) |
| 1233 |
load_context.resolve_legacy(basename, {basename: path_context}) |
| 1234 |
|
| 1235 |
try: |
| 1236 |
module = self._load_module_source(python_module_name=load_context._python_module_name, path=path) |
| 1237 |
except Exception as e: |
| 1238 |
display.warning("Skipping plugin (%s), cannot load: %s" % (path, to_text(e))) |
| 1239 |
continue |
| 1240 |
|
| 1241 |
self._module_cache[path] = module |
| 1242 |
found_in_cache = False |
| 1243 |
else: |
| 1244 |
module = self._module_cache[path] |
| 1245 |
|
| 1246 |
self._load_config_defs(basename, module, path) |
| 1247 |
|
| 1248 |
try: |
| 1249 |
obj = getattr(module, self.class_name) |
| 1250 |
except AttributeError as e: |
| 1251 |
display.warning("Skipping plugin (%s) as it seems to be invalid: %s" % (path, to_text(e))) |
| 1252 |
continue |
| 1253 |
|
| 1254 |
if self.base_class: |
| 1255 |
# The import path is hardcoded and should be the right place, |
| 1256 |
# so we are not expecting an ImportError. |
| 1257 |
module = __import__(self.package, fromlist=[self.base_class]) |
| 1258 |
# Check whether this obj has the required base class. |
| 1259 |
try: |
| 1260 |
plugin_class = getattr(module, self.base_class) |
| 1261 |
except AttributeError: |
| 1262 |
continue |
| 1263 |
if not issubclass(obj, plugin_class): |
| 1264 |
continue |
| 1265 |
|
| 1266 |
self._display_plugin_load(self.class_name, basename, self._searched_paths, path, found_in_cache=found_in_cache, class_only=class_only) |
| 1267 |
|
| 1268 |
if not class_only: |
| 1269 |
try: |
| 1270 |
obj = obj(*args, **kwargs) |
| 1271 |
except TypeError as e: |
| 1272 |
display.warning("Skipping plugin (%s) as it seems to be incomplete: %s" % (path, to_text(e))) |
| 1273 |
|
| 1274 |
self._update_object(obj=obj, name=basename, path=path, resolved=fqcn) |
| 1275 |
|
| 1276 |
if self._plugin_instance_cache is not None: |
| 1277 |
needs_enabled = False |
| 1278 |
if hasattr(obj, 'REQUIRES_ENABLED'): |
| 1279 |
needs_enabled = obj.REQUIRES_ENABLED |
| 1280 |
if not needs_enabled: |
| 1281 |
# Use get_with_context to cache the plugin the first time we see it. |
| 1282 |
self.get_with_context(fqcn)[0] |
| 1283 |
|
| 1284 |
yield obj |
| 1285 |
|
| 1286 |
|
| 1287 |
class _CacheLoader(PluginLoader): |
| 1288 |
"""Customized loader for cache plugins that wraps the requested plugin with an interposer that schema-qualifies keys and JSON encodes the values.""" |
| 1289 |
|
| 1290 |
def get(self, name: str, *args, **kwargs) -> BaseCacheModule: |
| 1291 |
plugin = super().get(name, *args, **kwargs) |
| 1292 |
|
| 1293 |
if not plugin: |
| 1294 |
raise AnsibleError(f'Unable to load the cache plugin {name!r}.') |
| 1295 |
|
| 1296 |
# NOTE: jsonfile relies on the internal impl detail that the instance of the cache class is initialized at this point |
| 1297 |
if plugin._persistent: |
| 1298 |
return _cache.PluginInterposer(plugin) |
| 1299 |
|
| 1300 |
return plugin |
| 1301 |
|
| 1302 |
|
| 1303 |
class Jinja2Loader(PluginLoader): |
| 1304 |
""" |
| 1305 |
PluginLoader optimized for Jinja2 plugins |
| 1306 |
|
| 1307 |
The filter and test plugins are Jinja2 plugins encapsulated inside of our plugin format. |
| 1308 |
We need to do a few things differently in the base class because of file == plugin |
| 1309 |
assumptions and dedupe logic. |
| 1310 |
""" |
| 1311 |
|
| 1312 |
def __init__(self, class_name, package, config, subdir, plugin_wrapper_type, aliases=Sentinel, required_base_class=None) -> None: |
| 1313 |
super(Jinja2Loader, self).__init__(class_name, package, config, subdir, aliases=aliases, required_base_class=required_base_class) |
| 1314 |
self._plugin_wrapper_type = plugin_wrapper_type |
| 1315 |
self._plugin_type_friendly_name = 'filter' if plugin_wrapper_type is AnsibleJinja2Filter else 'test' |
| 1316 |
self._cached_non_collection_wrappers: dict[str, AnsibleJinja2Filter | AnsibleJinja2Test | _DeferredPluginLoadFailure] = {} |
| 1317 |
|
| 1318 |
def _clear_caches(self): |
| 1319 |
super(Jinja2Loader, self)._clear_caches() |
| 1320 |
self._cached_non_collection_wrappers = {} |
| 1321 |
|
| 1322 |
def find_plugin(self, name, mod_type='', ignore_deprecated=False, check_aliases=False, collection_list=None): |
| 1323 |
raise NotImplementedError('find_plugin is not supported on Jinja2Loader') |
| 1324 |
|
| 1325 |
@property |
| 1326 |
def method_map_name(self): |
| 1327 |
return get_plugin_class(self.class_name) + 's' |
| 1328 |
|
| 1329 |
def _wrap_func(self, name: str, resolved: str, func: t.Callable) -> AnsibleJinja2Test | AnsibleJinja2Filter: |
| 1330 |
"""Wrap a Jinja builtin function in a `AnsibleJinja2Plugin` instance.""" |
| 1331 |
try: |
| 1332 |
path = sys.modules[func.__module__].__file__ |
| 1333 |
except AttributeError: |
| 1334 |
path = None |
| 1335 |
|
| 1336 |
wrapper = self._plugin_wrapper_type(func) |
| 1337 |
|
| 1338 |
self._update_object(obj=wrapper, name=name, path=path, resolved=resolved) |
| 1339 |
|
| 1340 |
return wrapper |
| 1341 |
|
| 1342 |
def _wrap_funcs(self, plugins: dict[str, t.Callable], aliases: dict[str, str]) -> dict[str, AnsibleJinja2Test | AnsibleJinja2Filter]: |
| 1343 |
"""Map a dictionary of Jinja builtin functions to one containing `AnsibleJinja2Plugin` instances.""" |
| 1344 |
wrappers: dict[str, AnsibleJinja2Test | AnsibleJinja2Filter] = {} |
| 1345 |
|
| 1346 |
for load_name, func in plugins.items(): |
| 1347 |
name = aliases.get(load_name, load_name) |
| 1348 |
resolved = f'ansible.builtin.{name}' |
| 1349 |
|
| 1350 |
wrappers[load_name] = self._wrap_func(load_name, resolved, func) |
| 1351 |
|
| 1352 |
if resolved not in wrappers: |
| 1353 |
# When the resolved name hasn't been cached, do so. |
| 1354 |
# Functions that have aliases will appear more than once, and we don't need to overwrite them. |
| 1355 |
wrappers[resolved] = self._wrap_func(resolved, resolved, func) |
| 1356 |
|
| 1357 |
return wrappers |
| 1358 |
|
| 1359 |
def get_contained_plugins(self, collection, plugin_path, name): |
| 1360 |
|
| 1361 |
plugins = [] |
| 1362 |
|
| 1363 |
full_name = '.'.join(['ansible_collections', collection, 'plugins', self.type, name]) |
| 1364 |
try: |
| 1365 |
# use 'parent' loader class to find files, but cannot return this as it can contain multiple plugins per file |
| 1366 |
if plugin_path not in self._module_cache: |
| 1367 |
self._module_cache[plugin_path] = self._load_module_source(python_module_name=full_name, path=plugin_path) |
| 1368 |
module = self._module_cache[plugin_path] |
| 1369 |
obj = getattr(module, self.class_name) |
| 1370 |
except Exception as e: |
| 1371 |
raise KeyError('Failed to load %s for %s: %s' % (plugin_path, collection, to_native(e))) |
| 1372 |
|
| 1373 |
plugin_impl = obj() |
| 1374 |
if plugin_impl is None: |
| 1375 |
raise KeyError('Could not find %s.%s' % (collection, name)) |
| 1376 |
|
| 1377 |
try: |
| 1378 |
method_map = getattr(plugin_impl, self.method_map_name) |
| 1379 |
plugin_map = method_map().items() |
| 1380 |
except Exception as e: |
| 1381 |
display.warning("Ignoring %s plugins in '%s' as it seems to be invalid: %r" % (self.type, to_text(plugin_path), e)) |
| 1382 |
return plugins |
| 1383 |
|
| 1384 |
for func_name, func in plugin_map: |
| 1385 |
fq_name = '.'.join((collection, func_name)) |
| 1386 |
full = '.'.join((full_name, func_name)) |
| 1387 |
plugin = self._plugin_wrapper_type(func) |
| 1388 |
if plugin in plugins: |
| 1389 |
continue |
| 1390 |
self._update_object(obj=plugin, name=full, path=plugin_path, resolved=fq_name) |
| 1391 |
plugins.append(plugin) |
| 1392 |
|
| 1393 |
return plugins |
| 1394 |
|
| 1395 |
# FUTURE: now that the resulting plugins are closer, refactor base class method with some extra |
| 1396 |
# hooks so we can avoid all the duplicated plugin metadata logic, and also cache the collection results properly here |
| 1397 |
def get_with_context(self, name: str, *args, **kwargs) -> get_with_context_result: |
| 1398 |
# pop N/A kwargs to avoid passthrough to parent methods |
| 1399 |
kwargs.pop('class_only', False) |
| 1400 |
kwargs.pop('collection_list', None) |
| 1401 |
|
| 1402 |
requested_name = name |
| 1403 |
|
| 1404 |
context = PluginLoadContext(self.type, self.package) |
| 1405 |
|
| 1406 |
# avoid collection path for legacy |
| 1407 |
name = name.removeprefix('ansible.legacy.') |
| 1408 |
|
| 1409 |
self._ensure_non_collection_wrappers(*args, **kwargs) |
| 1410 |
|
| 1411 |
# check for stuff loaded via legacy/builtin paths first |
| 1412 |
if known_plugin := self._cached_non_collection_wrappers.get(name): |
| 1413 |
if isinstance(known_plugin, _DeferredPluginLoadFailure): |
| 1414 |
raise known_plugin.ex |
| 1415 |
|
| 1416 |
context.resolve_legacy_jinja_plugin(name, known_plugin) |
| 1417 |
|
| 1418 |
return get_with_context_result(known_plugin, context) |
| 1419 |
|
| 1420 |
plugin = None |
| 1421 |
key, leaf_key = get_fqcr_and_name(name) |
| 1422 |
seen = set() |
| 1423 |
|
| 1424 |
# follow the meta! |
| 1425 |
while True: |
| 1426 |
|
| 1427 |
if key in seen: |
| 1428 |
raise AnsibleError('recursive collection redirect found for %r' % name, 0) |
| 1429 |
seen.add(key) |
| 1430 |
|
| 1431 |
acr = AnsibleCollectionRef.try_parse_fqcr(key, self.type) |
| 1432 |
if not acr: |
| 1433 |
raise KeyError('invalid plugin name: {0}'.format(key)) |
| 1434 |
|
| 1435 |
try: |
| 1436 |
ts = _get_collection_metadata(acr.collection) |
| 1437 |
except ValueError as e: |
| 1438 |
# no collection |
| 1439 |
raise KeyError('Invalid plugin FQCN ({0}): {1}'.format(key, to_native(e))) from e |
| 1440 |
|
| 1441 |
# TODO: implement cycle detection (unified across collection redir as well) |
| 1442 |
routing_entry = ts.get('plugin_routing', {}).get(self.type, {}).get(leaf_key, {}) |
| 1443 |
|
| 1444 |
# check deprecations |
| 1445 |
deprecation_entry = routing_entry.get('deprecation') |
| 1446 |
if deprecation_entry: |
| 1447 |
warning_text = deprecation_entry.get('warning_text') or '' |
| 1448 |
removal_date = deprecation_entry.get('removal_date') |
| 1449 |
removal_version = deprecation_entry.get('removal_version') |
| 1450 |
|
| 1451 |
warning_text = f'{self.type.title()} "{key}" has been deprecated.{" " if warning_text else ""}{warning_text}' |
| 1452 |
|
| 1453 |
display.deprecated( # pylint: disable=ansible-deprecated-date-not-permitted,ansible-deprecated-unnecessary-collection-name |
| 1454 |
msg=warning_text, |
| 1455 |
version=removal_version, |
| 1456 |
date=removal_date, |
| 1457 |
deprecator=deprecator_from_collection_name(acr.collection), |
| 1458 |
) |
| 1459 |
|
| 1460 |
# check removal |
| 1461 |
tombstone_entry = routing_entry.get('tombstone') |
| 1462 |
if tombstone_entry: |
| 1463 |
warning_text = tombstone_entry.get('warning_text') or '' |
| 1464 |
removal_date = tombstone_entry.get('removal_date') |
| 1465 |
removal_version = tombstone_entry.get('removal_version') |
| 1466 |
warning_text = f'The {key!r} {self.type} plugin has been removed.{" " if warning_text else ""}{warning_text}' |
| 1467 |
|
| 1468 |
exc_msg = _display_utils.get_deprecation_message_with_plugin_info( |
| 1469 |
msg=warning_text, |
| 1470 |
version=removal_version, |
| 1471 |
date=removal_date, |
| 1472 |
removed=True, |
| 1473 |
deprecator=deprecator_from_collection_name(acr.collection), |
| 1474 |
) |
| 1475 |
|
| 1476 |
raise AnsiblePluginRemovedError(exc_msg) |
| 1477 |
|
| 1478 |
# check redirects |
| 1479 |
redirect = routing_entry.get('redirect', None) |
| 1480 |
if redirect: |
| 1481 |
if not AnsibleCollectionRef.is_valid_fqcr(redirect): |
| 1482 |
raise AnsibleError( |
| 1483 |
f"Collection {acr.collection} contains invalid redirect for {acr.collection}.{acr.resource}: {redirect}. " |
| 1484 |
"Redirects must use fully qualified collection names." |
| 1485 |
) |
| 1486 |
|
| 1487 |
next_key, leaf_key = get_fqcr_and_name(redirect, collection=acr.collection) |
| 1488 |
display.vvv('redirecting (type: {0}) {1}.{2} to {3}'.format(self.type, acr.collection, acr.resource, next_key)) |
| 1489 |
key = next_key |
| 1490 |
else: |
| 1491 |
break |
| 1492 |
|
| 1493 |
try: |
| 1494 |
pkg = import_module(acr.n_python_package_name) |
| 1495 |
except ImportError as e: |
| 1496 |
raise KeyError(to_native(e)) |
| 1497 |
|
| 1498 |
parent_prefix = acr.collection |
| 1499 |
if acr.subdirs: |
| 1500 |
parent_prefix = '{0}.{1}'.format(parent_prefix, acr.subdirs) |
| 1501 |
|
| 1502 |
try: |
| 1503 |
for dummy, module_name, ispkg in pkgutil.iter_modules(pkg.__path__, prefix=parent_prefix + '.'): |
| 1504 |
if ispkg: |
| 1505 |
continue |
| 1506 |
|
| 1507 |
try: |
| 1508 |
# use 'parent' loader class to find files, but cannot return this as it can contain |
| 1509 |
# multiple plugins per file |
| 1510 |
plugin_impl = super(Jinja2Loader, self).get_with_context(module_name, *args, **kwargs) |
| 1511 |
method_map = getattr(plugin_impl.object, self.method_map_name) |
| 1512 |
plugin_map = method_map().items() |
| 1513 |
except Exception as e: |
| 1514 |
display.warning(f"Skipping {self.type} plugins in {module_name}'; an error occurred while loading: {e}") |
| 1515 |
continue |
| 1516 |
|
| 1517 |
for func_name, func in plugin_map: |
| 1518 |
fq_name = '.'.join((parent_prefix, func_name)) |
| 1519 |
src_name = f"ansible_collections.{acr.collection}.plugins.{self.type}.{acr.subdirs}.{func_name}" |
| 1520 |
# TODO: load anyways into CACHE so we only match each at end of loop |
| 1521 |
# the files themselves should already be cached by base class caching of modules(python) |
| 1522 |
if key in (func_name, fq_name): |
| 1523 |
plugin = self._plugin_wrapper_type(func) |
| 1524 |
if plugin: |
| 1525 |
context = plugin_impl.plugin_load_context |
| 1526 |
self._update_object(obj=plugin, name=requested_name, path=plugin_impl.object._original_path, resolved=fq_name) |
| 1527 |
# context will have filename, which for tests/filters might not be correct |
| 1528 |
context._resolved_fqcn = plugin.ansible_name |
| 1529 |
# FIXME: once we start caching these results, we'll be missing functions that would have loaded later |
| 1530 |
break # go to next file as it can override if dupe (dont break both loops) |
| 1531 |
|
| 1532 |
except (AnsibleError, KeyError): |
| 1533 |
raise |
| 1534 |
except Exception as ex: |
| 1535 |
raise AnsibleError('An unexpected error occurred during Jinja2 plugin loading.') from ex |
| 1536 |
|
| 1537 |
return get_with_context_result(plugin, context) |
| 1538 |
|
| 1539 |
def all(self, *args, **kwargs): |
| 1540 |
kwargs.pop('_dedupe', None) |
| 1541 |
path_only = kwargs.pop('path_only', False) |
| 1542 |
class_only = kwargs.pop('class_only', False) # basically ignored for test/filters since they are functions |
| 1543 |
|
| 1544 |
# Having both path_only and class_only is a coding bug |
| 1545 |
if path_only and class_only: |
| 1546 |
raise AnsibleError('Do not set both path_only and class_only when calling PluginLoader.all()') |
| 1547 |
|
| 1548 |
self._ensure_non_collection_wrappers(*args, **kwargs) |
| 1549 |
|
| 1550 |
plugins = [plugin for plugin in self._cached_non_collection_wrappers.values() if not isinstance(plugin, _DeferredPluginLoadFailure)] |
| 1551 |
|
| 1552 |
if path_only: |
| 1553 |
yield from (w._original_path for w in plugins) |
| 1554 |
else: |
| 1555 |
yield from (w for w in plugins) |
| 1556 |
|
| 1557 |
def _ensure_non_collection_wrappers(self, *args, **kwargs): |
| 1558 |
if self._cached_non_collection_wrappers: |
| 1559 |
return |
| 1560 |
|
| 1561 |
# get plugins from files in configured paths (multiple in each) |
| 1562 |
for p_map in super(Jinja2Loader, self).all(*args, **kwargs): |
| 1563 |
is_builtin = p_map.ansible_name.startswith('ansible.builtin.') |
| 1564 |
|
| 1565 |
# p_map is really object from file with class that holds multiple plugins |
| 1566 |
plugins_list = getattr(p_map, self.method_map_name) |
| 1567 |
try: |
| 1568 |
plugins = plugins_list() |
| 1569 |
except Exception as e: |
| 1570 |
display.vvvv("Skipping %s plugins in '%s' as it seems to be invalid: %r" % (self.type, to_text(p_map._original_path), e)) |
| 1571 |
continue |
| 1572 |
|
| 1573 |
for plugin_name in plugins.keys(): |
| 1574 |
if '.' in plugin_name: |
| 1575 |
display.debug(f'{plugin_name} skipped in {p_map._original_path}; Jinja plugin short names may not contain "."') |
| 1576 |
continue |
| 1577 |
|
| 1578 |
if plugin_name in _PLUGIN_FILTERS[self.package]: |
| 1579 |
display.debug("%s skipped due to a defined plugin filter" % plugin_name) |
| 1580 |
continue |
| 1581 |
|
| 1582 |
fqcn = plugin_name |
| 1583 |
collection = '.'.join(p_map.ansible_name.split('.')[:2]) if p_map.ansible_name.count('.') >= 2 else '' |
| 1584 |
if not plugin_name.startswith(collection): |
| 1585 |
fqcn = f"{collection}.{plugin_name}" |
| 1586 |
|
| 1587 |
target_names = {plugin_name, fqcn} |
| 1588 |
|
| 1589 |
if is_builtin: |
| 1590 |
target_names.add(f'ansible.builtin.{plugin_name}') |
| 1591 |
|
| 1592 |
for target_name in target_names: |
| 1593 |
# the plugin class returned by the loader may host multiple Jinja plugins, but we wrap each plugin in |
| 1594 |
# its own surrogate wrapper instance here to ease the bookkeeping... |
| 1595 |
try: |
| 1596 |
wrapper = self._plugin_wrapper_type(plugins[plugin_name]) |
| 1597 |
except Exception as ex: |
| 1598 |
wrapper = _DeferredPluginLoadFailure(ex) |
| 1599 |
|
| 1600 |
self._update_object(obj=wrapper, name=target_name, path=p_map._original_path, resolved=fqcn) |
| 1601 |
|
| 1602 |
if existing_plugin := self._cached_non_collection_wrappers.get(target_name): |
| 1603 |
display.debug(f'Jinja plugin {target_name} from {p_map._original_path} skipped; ' |
| 1604 |
f'shadowed by plugin from {existing_plugin._original_path})') |
| 1605 |
continue |
| 1606 |
|
| 1607 |
self._cached_non_collection_wrappers[target_name] = wrapper |
| 1608 |
|
| 1609 |
|
| 1610 |
class _DeferredPluginLoadFailure: |
| 1611 |
"""Represents a plugin which failed to load. For internal use only within plugin loader.""" |
| 1612 |
|
| 1613 |
def __init__(self, ex: Exception) -> None: |
| 1614 |
self.ex = ex |
| 1615 |
|
| 1616 |
|
| 1617 |
def get_fqcr_and_name(resource, collection='ansible.builtin'): |
| 1618 |
if '.' not in resource: |
| 1619 |
name = resource |
| 1620 |
fqcr = collection + '.' + resource |
| 1621 |
else: |
| 1622 |
name = resource.split('.')[-1] |
| 1623 |
fqcr = resource |
| 1624 |
|
| 1625 |
return fqcr, name |
| 1626 |
|
| 1627 |
|
| 1628 |
def _load_plugin_filter(): |
| 1629 |
filters = _PLUGIN_FILTERS |
| 1630 |
user_set = False |
| 1631 |
if C.PLUGIN_FILTERS_CFG is None: |
| 1632 |
filter_cfg = '/etc/ansible/plugin_filters.yml' |
| 1633 |
else: |
| 1634 |
filter_cfg = C.PLUGIN_FILTERS_CFG |
| 1635 |
user_set = True |
| 1636 |
|
| 1637 |
if os.path.exists(filter_cfg): |
| 1638 |
with open(filter_cfg, 'rb') as f: |
| 1639 |
try: |
| 1640 |
filter_data = yaml.load(f, Loader=AnsibleInstrumentedLoader) |
| 1641 |
except Exception as e: |
| 1642 |
display.warning(u'The plugin filter file, {0} was not parsable.' |
| 1643 |
u' Skipping: {1}'.format(filter_cfg, to_text(e))) |
| 1644 |
return filters |
| 1645 |
|
| 1646 |
try: |
| 1647 |
version = filter_data['filter_version'] |
| 1648 |
except KeyError: |
| 1649 |
display.warning(u'The plugin filter file, {0} was invalid.' |
| 1650 |
u' Skipping.'.format(filter_cfg)) |
| 1651 |
return filters |
| 1652 |
|
| 1653 |
# Try to convert for people specifying version as a float instead of string |
| 1654 |
version = to_text(version) |
| 1655 |
version = version.strip() |
| 1656 |
|
| 1657 |
# Modules and action plugins share the same reject list since the difference between the |
| 1658 |
# two isn't visible to the users |
| 1659 |
if version == u'1.0': |
| 1660 |
try: |
| 1661 |
filters['ansible.modules'] = frozenset(filter_data['module_rejectlist']) |
| 1662 |
except TypeError: |
| 1663 |
display.warning(u'Unable to parse the plugin filter file {0} as' |
| 1664 |
u' module_rejectlist is not a list.' |
| 1665 |
u' Skipping.'.format(filter_cfg)) |
| 1666 |
return filters |
| 1667 |
filters['ansible.plugins.action'] = filters['ansible.modules'] |
| 1668 |
else: |
| 1669 |
display.warning(u'The plugin filter file, {0} was a version not recognized by this' |
| 1670 |
u' version of Ansible. Skipping.'.format(filter_cfg)) |
| 1671 |
else: |
| 1672 |
if user_set: |
| 1673 |
display.warning(u'The plugin filter file, {0} does not exist.' |
| 1674 |
u' Skipping.'.format(filter_cfg)) |
| 1675 |
|
| 1676 |
# Special case: the stat module as Ansible can run very few things if stat is rejected |
| 1677 |
if 'stat' in filters['ansible.modules']: |
| 1678 |
raise AnsibleError('The stat module was specified in the module reject list file, {0}, but' |
| 1679 |
' Ansible will not function without the stat module. Please remove stat' |
| 1680 |
' from the reject list.'.format(to_native(filter_cfg))) |
| 1681 |
return filters |
| 1682 |
|
| 1683 |
|
| 1684 |
# since we don't want the actual collection loader understanding metadata, we'll do it in an event handler |
| 1685 |
def _on_collection_load_handler(collection_name, collection_path): |
| 1686 |
display.vvvv(to_text('Loading collection {0} from {1}'.format(collection_name, collection_path))) |
| 1687 |
|
| 1688 |
collection_meta = _get_collection_metadata(collection_name) |
| 1689 |
|
| 1690 |
try: |
| 1691 |
if not _does_collection_support_ansible_version(collection_meta.get('requires_ansible', ''), ansible_version): |
| 1692 |
mismatch_behavior = C.config.get_config_value('COLLECTIONS_ON_ANSIBLE_VERSION_MISMATCH') |
| 1693 |
message = 'Collection {0} does not support Ansible version {1}'.format(collection_name, ansible_version) |
| 1694 |
if mismatch_behavior == 'warning': |
| 1695 |
display.warning(message) |
| 1696 |
elif mismatch_behavior == 'error': |
| 1697 |
raise AnsibleCollectionUnsupportedVersionError(message) |
| 1698 |
except AnsibleError: |
| 1699 |
raise |
| 1700 |
except Exception as ex: |
| 1701 |
display.warning('Error parsing collection metadata requires_ansible value from collection {0}: {1}'.format(collection_name, ex)) |
| 1702 |
|
| 1703 |
|
| 1704 |
def _does_collection_support_ansible_version(requirement_string, ansible_version): |
| 1705 |
if not requirement_string: |
| 1706 |
return True |
| 1707 |
|
| 1708 |
if not SpecifierSet: |
| 1709 |
display.warning('packaging Python module unavailable; unable to validate collection Ansible version requirements') |
| 1710 |
return True |
| 1711 |
|
| 1712 |
ss = SpecifierSet(requirement_string) |
| 1713 |
|
| 1714 |
# ignore prerelease/postrelease/beta/dev flags for simplicity |
| 1715 |
base_ansible_version = Version(ansible_version).base_version |
| 1716 |
|
| 1717 |
return ss.contains(base_ansible_version) |
| 1718 |
|
| 1719 |
|
| 1720 |
def _configure_collection_loader(prefix_collections_path=None): |
| 1721 |
if AnsibleCollectionConfig.collection_finder: |
| 1722 |
# this must be a Python warning so that it can be filtered out by the import sanity test |
| 1723 |
warnings.warn('AnsibleCollectionFinder has already been configured') |
| 1724 |
return |
| 1725 |
|
| 1726 |
if prefix_collections_path is None: |
| 1727 |
prefix_collections_path = [] |
| 1728 |
|
| 1729 |
# insert the internal ansible._protomatter collection up front |
| 1730 |
paths = [os.path.dirname(_internal.__file__)] + list(prefix_collections_path) + C.COLLECTIONS_PATHS |
| 1731 |
finder = _AnsibleCollectionFinder(paths, C.COLLECTIONS_SCAN_SYS_PATH, internal_collections=paths[0]) |
| 1732 |
finder._install() |
| 1733 |
|
| 1734 |
# this should succeed now |
| 1735 |
AnsibleCollectionConfig.on_collection_load += _on_collection_load_handler |
| 1736 |
|
| 1737 |
|
| 1738 |
def init_plugin_loader(prefix_collections_path=None): |
| 1739 |
"""Initialize the plugin filters and the collection loaders |
| 1740 |
|
| 1741 |
This method must be called to configure and insert the collection python loaders |
| 1742 |
into ``sys.meta_path`` and ``sys.path_hooks``. |
| 1743 |
|
| 1744 |
This method is only called in ``CLI.run`` after CLI args have been parsed, so that |
| 1745 |
instantiation of the collection finder can utilize parsed CLI args, and to not cause |
| 1746 |
side effects. |
| 1747 |
""" |
| 1748 |
_load_plugin_filter() |
| 1749 |
_configure_collection_loader(prefix_collections_path) |
| 1750 |
|
| 1751 |
|
| 1752 |
# TODO: Evaluate making these class instantiations lazy, but keep them in the global scope |
| 1753 |
|
| 1754 |
# doc fragments first |
| 1755 |
fragment_loader = PluginLoader( |
| 1756 |
'ModuleDocFragment', |
| 1757 |
'ansible.plugins.doc_fragments', |
| 1758 |
C.DOC_FRAGMENT_PLUGIN_PATH, |
| 1759 |
'doc_fragments', |
| 1760 |
) |
| 1761 |
|
| 1762 |
action_loader = PluginLoader( |
| 1763 |
'ActionModule', |
| 1764 |
'ansible.plugins.action', |
| 1765 |
C.DEFAULT_ACTION_PLUGIN_PATH, |
| 1766 |
'action_plugins', |
| 1767 |
required_base_class='ActionBase', |
| 1768 |
) |
| 1769 |
|
| 1770 |
cache_loader = _CacheLoader( |
| 1771 |
'CacheModule', |
| 1772 |
'ansible.plugins.cache', |
| 1773 |
C.DEFAULT_CACHE_PLUGIN_PATH, |
| 1774 |
'cache_plugins', |
| 1775 |
) |
| 1776 |
|
| 1777 |
callback_loader = PluginLoader( |
| 1778 |
'CallbackModule', |
| 1779 |
'ansible.plugins.callback', |
| 1780 |
C.DEFAULT_CALLBACK_PLUGIN_PATH, |
| 1781 |
'callback_plugins', |
| 1782 |
required_base_class='CallbackBase', |
| 1783 |
) |
| 1784 |
|
| 1785 |
connection_loader = PluginLoader( |
| 1786 |
'Connection', |
| 1787 |
'ansible.plugins.connection', |
| 1788 |
C.DEFAULT_CONNECTION_PLUGIN_PATH, |
| 1789 |
'connection_plugins', |
| 1790 |
required_base_class='ConnectionBase', |
| 1791 |
) |
| 1792 |
|
| 1793 |
shell_loader = PluginLoader( |
| 1794 |
'ShellModule', |
| 1795 |
'ansible.plugins.shell', |
| 1796 |
'shell_plugins', |
| 1797 |
'shell_plugins', |
| 1798 |
) |
| 1799 |
|
| 1800 |
module_loader = PluginLoader( |
| 1801 |
'', |
| 1802 |
'ansible.modules', |
| 1803 |
C.DEFAULT_MODULE_PATH, |
| 1804 |
'library', |
| 1805 |
) |
| 1806 |
|
| 1807 |
module_utils_loader = PluginLoader( |
| 1808 |
'', |
| 1809 |
'ansible.module_utils', |
| 1810 |
C.DEFAULT_MODULE_UTILS_PATH, |
| 1811 |
'module_utils', |
| 1812 |
) |
| 1813 |
|
| 1814 |
# NB: dedicated loader is currently necessary because PS module_utils expects "with subdir" lookup where |
| 1815 |
# regular module_utils doesn't. This can be revisited once we have more granular loaders. |
| 1816 |
ps_module_utils_loader = PluginLoader( |
| 1817 |
'', |
| 1818 |
'ansible.module_utils', |
| 1819 |
C.DEFAULT_MODULE_UTILS_PATH, |
| 1820 |
'module_utils', |
| 1821 |
) |
| 1822 |
|
| 1823 |
lookup_loader = PluginLoader( |
| 1824 |
'LookupModule', |
| 1825 |
'ansible.plugins.lookup', |
| 1826 |
C.DEFAULT_LOOKUP_PLUGIN_PATH, |
| 1827 |
'lookup_plugins', |
| 1828 |
required_base_class='LookupBase', |
| 1829 |
) |
| 1830 |
|
| 1831 |
filter_loader = Jinja2Loader( |
| 1832 |
'FilterModule', |
| 1833 |
'ansible.plugins.filter', |
| 1834 |
C.DEFAULT_FILTER_PLUGIN_PATH, |
| 1835 |
'filter_plugins', |
| 1836 |
AnsibleJinja2Filter |
| 1837 |
) |
| 1838 |
|
| 1839 |
test_loader = Jinja2Loader( |
| 1840 |
'TestModule', |
| 1841 |
'ansible.plugins.test', |
| 1842 |
C.DEFAULT_TEST_PLUGIN_PATH, |
| 1843 |
'test_plugins', |
| 1844 |
AnsibleJinja2Test |
| 1845 |
) |
| 1846 |
|
| 1847 |
strategy_loader = PluginLoader( |
| 1848 |
'StrategyModule', |
| 1849 |
'ansible.plugins.strategy', |
| 1850 |
C.DEFAULT_STRATEGY_PLUGIN_PATH, |
| 1851 |
'strategy_plugins', |
| 1852 |
required_base_class='StrategyBase', |
| 1853 |
) |
| 1854 |
|
| 1855 |
terminal_loader = PluginLoader( |
| 1856 |
'TerminalModule', |
| 1857 |
'ansible.plugins.terminal', |
| 1858 |
C.DEFAULT_TERMINAL_PLUGIN_PATH, |
| 1859 |
'terminal_plugins', |
| 1860 |
required_base_class='TerminalBase' |
| 1861 |
) |
| 1862 |
|
| 1863 |
vars_loader = PluginLoader( |
| 1864 |
'VarsModule', |
| 1865 |
'ansible.plugins.vars', |
| 1866 |
C.DEFAULT_VARS_PLUGIN_PATH, |
| 1867 |
'vars_plugins', |
| 1868 |
) |
| 1869 |
|
| 1870 |
cliconf_loader = PluginLoader( |
| 1871 |
'Cliconf', |
| 1872 |
'ansible.plugins.cliconf', |
| 1873 |
C.DEFAULT_CLICONF_PLUGIN_PATH, |
| 1874 |
'cliconf_plugins', |
| 1875 |
required_base_class='CliconfBase' |
| 1876 |
) |
| 1877 |
|
| 1878 |
netconf_loader = PluginLoader( |
| 1879 |
'Netconf', |
| 1880 |
'ansible.plugins.netconf', |
| 1881 |
C.DEFAULT_NETCONF_PLUGIN_PATH, |
| 1882 |
'netconf_plugins', |
| 1883 |
required_base_class='NetconfBase' |
| 1884 |
) |
| 1885 |
|
| 1886 |
inventory_loader = PluginLoader( |
| 1887 |
'InventoryModule', |
| 1888 |
'ansible.plugins.inventory', |
| 1889 |
C.DEFAULT_INVENTORY_PLUGIN_PATH, |
| 1890 |
'inventory_plugins' |
| 1891 |
) |
| 1892 |
|
| 1893 |
httpapi_loader = PluginLoader( |
| 1894 |
'HttpApi', |
| 1895 |
'ansible.plugins.httpapi', |
| 1896 |
C.DEFAULT_HTTPAPI_PLUGIN_PATH, |
| 1897 |
'httpapi_plugins', |
| 1898 |
required_base_class='HttpApiBase', |
| 1899 |
) |
| 1900 |
|
| 1901 |
become_loader = PluginLoader( |
| 1902 |
'BecomeModule', |
| 1903 |
'ansible.plugins.become', |
| 1904 |
C.BECOME_PLUGIN_PATH, |
| 1905 |
'become_plugins' |
| 1906 |
) |