| 1 |
# (c) 2019 Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
# CAUTION: This implementation of the collection loader is used by ansible-test. |
| 5 |
# Because of this, it must be compatible with all Python versions supported on the controller or remote. |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import inspect |
| 10 |
import itertools |
| 11 |
import os |
| 12 |
import os.path |
| 13 |
import pathlib |
| 14 |
import re |
| 15 |
import sys |
| 16 |
|
| 17 |
from contextlib import contextmanager |
| 18 |
from importlib import import_module, reload as reload_module |
| 19 |
from importlib.machinery import FileFinder |
| 20 |
from importlib.util import find_spec, spec_from_loader |
| 21 |
from keyword import iskeyword |
| 22 |
from types import ModuleType |
| 23 |
|
| 24 |
# DO NOT add new non-stdlib import deps here, this loader is used by external tools (eg ansible-test import sanity) |
| 25 |
# that only allow stdlib and module_utils |
| 26 |
from . import _to_bytes, _to_text |
| 27 |
from ._collection_config import AnsibleCollectionConfig |
| 28 |
|
| 29 |
try: |
| 30 |
# Available on Python >= 3.11 |
| 31 |
# We ignore the import error that will trigger when running mypy with |
| 32 |
# older Python versions. |
| 33 |
from importlib.resources.abc import TraversableResources # type: ignore[import] |
| 34 |
except ImportError: |
| 35 |
# Used with Python 3.9 and 3.10 only |
| 36 |
# This member is still available as an alias up until Python 3.14 but |
| 37 |
# is deprecated as of Python 3.12. |
| 38 |
# deprecated: description='TraversableResources move' python_version='3.10' |
| 39 |
from importlib.abc import TraversableResources # type: ignore[assignment,no-redef] |
| 40 |
|
| 41 |
# NB: this supports import sanity test providing a different impl |
| 42 |
try: |
| 43 |
from ._collection_meta import _meta_yml_to_dict |
| 44 |
except ImportError: |
| 45 |
_meta_yml_to_dict = None |
| 46 |
|
| 47 |
PB_EXTENSIONS = ('.yml', '.yaml') |
| 48 |
SYNTHETIC_PACKAGE_NAME = '<ansible_synthetic_collection_package>' |
| 49 |
|
| 50 |
|
| 51 |
class _AnsibleNSTraversable: |
| 52 |
"""Class that implements the ``importlib.resources.abc.Traversable`` |
| 53 |
interface for the following ``ansible_collections`` namespace packages:: |
| 54 |
|
| 55 |
* ``ansible_collections`` |
| 56 |
* ``ansible_collections.<namespace>`` |
| 57 |
|
| 58 |
These namespace packages operate differently from a normal Python |
| 59 |
namespace package, in that the same namespace can be distributed across |
| 60 |
multiple directories on the filesystem and still function as a single |
| 61 |
namespace, such as:: |
| 62 |
|
| 63 |
* ``/usr/share/ansible/collections/ansible_collections/ansible/posix/`` |
| 64 |
* ``/home/user/.ansible/collections/ansible_collections/ansible/windows/`` |
| 65 |
|
| 66 |
This class will mimic the behavior of various ``pathlib.Path`` methods, |
| 67 |
by combining the results of multiple root paths into the output. |
| 68 |
|
| 69 |
This class does not do anything to remove duplicate collections from the |
| 70 |
list, so when traversing either namespace patterns supported by this class, |
| 71 |
it is possible to have the same collection located in multiple root paths, |
| 72 |
but precedence rules only use one. When iterating or traversing these |
| 73 |
package roots, there is the potential to see the same collection in |
| 74 |
multiple places without indication of which would be used. In such a |
| 75 |
circumstance, it is best to then call ``importlib.resources.files`` for an |
| 76 |
individual collection package rather than continuing to traverse from the |
| 77 |
namespace package. |
| 78 |
|
| 79 |
Several methods will raise ``NotImplementedError`` as they do not make |
| 80 |
sense for these namespace packages. |
| 81 |
""" |
| 82 |
def __init__(self, *paths): |
| 83 |
self._paths = [pathlib.Path(p) for p in paths] |
| 84 |
|
| 85 |
def __repr__(self): |
| 86 |
return "_AnsibleNSTraversable('%s')" % "', '".join(map(_to_text, self._paths)) |
| 87 |
|
| 88 |
def iterdir(self): |
| 89 |
return itertools.chain.from_iterable(p.iterdir() for p in self._paths if p.is_dir()) |
| 90 |
|
| 91 |
def is_dir(self): |
| 92 |
return any(p.is_dir() for p in self._paths) |
| 93 |
|
| 94 |
def is_file(self): |
| 95 |
return False |
| 96 |
|
| 97 |
def glob(self, pattern): |
| 98 |
return itertools.chain.from_iterable(p.glob(pattern) for p in self._paths if p.is_dir()) |
| 99 |
|
| 100 |
def _not_implemented(self, *args, **kwargs): |
| 101 |
raise NotImplementedError('not usable on namespaces') |
| 102 |
|
| 103 |
joinpath = __truediv__ = read_bytes = read_text = _not_implemented |
| 104 |
|
| 105 |
|
| 106 |
class _AnsibleTraversableResources(TraversableResources): |
| 107 |
"""Implements ``importlib.resources.abc.TraversableResources`` for the |
| 108 |
collection Python loaders. |
| 109 |
|
| 110 |
The result of ``files`` will depend on whether a particular collection, or |
| 111 |
a sub package of a collection was referenced, as opposed to |
| 112 |
``ansible_collections`` or a particular namespace. For a collection and |
| 113 |
its subpackages, a ``pathlib.Path`` instance will be returned, whereas |
| 114 |
for the higher level namespace packages, ``_AnsibleNSTraversable`` |
| 115 |
will be returned. |
| 116 |
""" |
| 117 |
def __init__(self, package, loader): |
| 118 |
self._package = package |
| 119 |
self._loader = loader |
| 120 |
|
| 121 |
def _get_name(self, package): |
| 122 |
try: |
| 123 |
# spec |
| 124 |
return package.name |
| 125 |
except AttributeError: |
| 126 |
# module |
| 127 |
return package.__name__ |
| 128 |
|
| 129 |
def _get_package(self, package): |
| 130 |
try: |
| 131 |
# spec |
| 132 |
return package.__parent__ |
| 133 |
except AttributeError: |
| 134 |
# module |
| 135 |
return package.__package__ |
| 136 |
|
| 137 |
def _get_path(self, package): |
| 138 |
try: |
| 139 |
# spec |
| 140 |
return package.origin |
| 141 |
except AttributeError: |
| 142 |
# module |
| 143 |
return package.__file__ |
| 144 |
|
| 145 |
def _is_ansible_ns_package(self, package): |
| 146 |
origin = getattr(package, 'origin', None) |
| 147 |
if not origin: |
| 148 |
return False |
| 149 |
|
| 150 |
if origin == SYNTHETIC_PACKAGE_NAME: |
| 151 |
return True |
| 152 |
|
| 153 |
module_filename = os.path.basename(origin) |
| 154 |
return module_filename in {'__synthetic__', '__init__.py'} |
| 155 |
|
| 156 |
def _ensure_package(self, package): |
| 157 |
if self._is_ansible_ns_package(package): |
| 158 |
# Short circuit our loaders |
| 159 |
return |
| 160 |
if self._get_package(package) != package.__name__: |
| 161 |
raise TypeError('%r is not a package' % package.__name__) |
| 162 |
|
| 163 |
def files(self): |
| 164 |
package = self._package |
| 165 |
parts = package.split('.') |
| 166 |
is_ns = parts[0] == 'ansible_collections' and len(parts) < 3 |
| 167 |
|
| 168 |
if isinstance(package, str): |
| 169 |
if is_ns: |
| 170 |
# Don't use ``spec_from_loader`` here, because that will point |
| 171 |
# to exactly 1 location for a namespace. Use ``find_spec`` |
| 172 |
# to get a list of all locations for the namespace |
| 173 |
package = find_spec(package) |
| 174 |
else: |
| 175 |
package = spec_from_loader(package, self._loader) |
| 176 |
elif not isinstance(package, ModuleType): |
| 177 |
raise TypeError('Expected string or module, got %r' % package.__class__.__name__) |
| 178 |
|
| 179 |
self._ensure_package(package) |
| 180 |
if is_ns: |
| 181 |
return _AnsibleNSTraversable(*package.submodule_search_locations) |
| 182 |
return pathlib.Path(self._get_path(package)).parent |
| 183 |
|
| 184 |
|
| 185 |
class _AnsibleCollectionFinder: |
| 186 |
def __init__(self, paths=None, scan_sys_paths=True, internal_collections=None): |
| 187 |
# TODO: accept metadata loader override |
| 188 |
self._ansible_pkg_path = _to_text(os.path.dirname(_to_bytes(sys.modules['ansible'].__file__))) |
| 189 |
|
| 190 |
if isinstance(paths, str): |
| 191 |
paths = [paths] |
| 192 |
elif paths is None: |
| 193 |
paths = [] |
| 194 |
|
| 195 |
# expand any placeholders in configured paths |
| 196 |
paths = [os.path.expanduser(_to_text(p)) for p in paths] |
| 197 |
|
| 198 |
# add syspaths if needed |
| 199 |
if scan_sys_paths: |
| 200 |
paths.extend(sys.path) |
| 201 |
|
| 202 |
good_paths = [] |
| 203 |
# expand any placeholders in configured paths |
| 204 |
for p in paths: |
| 205 |
|
| 206 |
# ensure we always have ansible_collections |
| 207 |
if os.path.basename(p) == 'ansible_collections': |
| 208 |
p = os.path.dirname(p) |
| 209 |
|
| 210 |
if p not in good_paths and os.path.isdir(_to_bytes(os.path.join(p, 'ansible_collections'))): |
| 211 |
good_paths.append(p) |
| 212 |
|
| 213 |
self._internal_collections = internal_collections |
| 214 |
self._n_configured_paths = good_paths |
| 215 |
self._n_cached_collection_paths = None |
| 216 |
self._n_cached_collection_qualified_paths = None |
| 217 |
|
| 218 |
self._n_playbook_paths = [] |
| 219 |
|
| 220 |
@classmethod |
| 221 |
def _find_existing_finder(cls) -> _AnsibleCollectionFinder | None: |
| 222 |
for finder in sys.meta_path: |
| 223 |
if isinstance(finder, _AnsibleCollectionFinder): |
| 224 |
return finder |
| 225 |
|
| 226 |
return None |
| 227 |
|
| 228 |
@classmethod |
| 229 |
def _remove(cls): |
| 230 |
for mps in sys.meta_path: |
| 231 |
if isinstance(mps, _AnsibleCollectionFinder): |
| 232 |
sys.meta_path.remove(mps) |
| 233 |
|
| 234 |
# remove any path hooks that look like ours |
| 235 |
for ph in sys.path_hooks: |
| 236 |
if hasattr(ph, '__self__') and isinstance(ph.__self__, _AnsibleCollectionFinder): |
| 237 |
sys.path_hooks.remove(ph) |
| 238 |
|
| 239 |
# zap any cached path importer cache entries that might refer to us |
| 240 |
sys.path_importer_cache.clear() |
| 241 |
|
| 242 |
AnsibleCollectionConfig._collection_finder = None |
| 243 |
|
| 244 |
# validate via the public property that we really killed it |
| 245 |
if AnsibleCollectionConfig.collection_finder is not None: |
| 246 |
raise AssertionError('_AnsibleCollectionFinder remove did not reset AnsibleCollectionConfig.collection_finder') |
| 247 |
|
| 248 |
def _install(self): |
| 249 |
self._remove() |
| 250 |
sys.meta_path.insert(0, self) |
| 251 |
|
| 252 |
sys.path_hooks.insert(0, self._ansible_collection_path_hook) |
| 253 |
|
| 254 |
AnsibleCollectionConfig.collection_finder = self |
| 255 |
|
| 256 |
def _ansible_collection_path_hook(self, path): |
| 257 |
path = _to_text(path) |
| 258 |
interesting_paths = self._n_cached_collection_qualified_paths |
| 259 |
if not interesting_paths: |
| 260 |
interesting_paths = [] |
| 261 |
for p in self._n_collection_paths: |
| 262 |
if os.path.basename(p) != 'ansible_collections': |
| 263 |
p = os.path.join(p, 'ansible_collections') |
| 264 |
|
| 265 |
if p not in interesting_paths: |
| 266 |
interesting_paths.append(p) |
| 267 |
|
| 268 |
interesting_paths.insert(0, self._ansible_pkg_path) |
| 269 |
self._n_cached_collection_qualified_paths = interesting_paths |
| 270 |
|
| 271 |
if any(path.startswith(p) for p in interesting_paths): |
| 272 |
return _AnsiblePathHookFinder(self, path) |
| 273 |
|
| 274 |
raise ImportError('not interested') |
| 275 |
|
| 276 |
@property |
| 277 |
def _n_collection_paths(self): |
| 278 |
paths = self._n_cached_collection_paths |
| 279 |
if not paths: |
| 280 |
self._n_cached_collection_paths = paths = self._n_playbook_paths + self._n_configured_paths |
| 281 |
return paths |
| 282 |
|
| 283 |
def set_playbook_paths(self, playbook_paths): |
| 284 |
if isinstance(playbook_paths, str): |
| 285 |
playbook_paths = [playbook_paths] |
| 286 |
|
| 287 |
# track visited paths; we have to preserve the dir order as-passed in case there are duplicate collections (first one wins) |
| 288 |
added_paths = set() |
| 289 |
|
| 290 |
# de-dupe |
| 291 |
self._n_playbook_paths = [os.path.join(_to_text(p), 'collections') for p in playbook_paths if not (p in added_paths or added_paths.add(p))] |
| 292 |
self._n_cached_collection_paths = None |
| 293 |
# HACK: playbook CLI sets this relatively late, so we've already loaded some packages whose paths might depend on this. Fix those up. |
| 294 |
# NB: this should NOT be used for late additions; ideally we'd fix the playbook dir setup earlier in Ansible init |
| 295 |
# to prevent this from occurring |
| 296 |
for pkg in ['ansible_collections', 'ansible_collections.ansible']: |
| 297 |
self._reload_hack(pkg) |
| 298 |
|
| 299 |
def _reload_hack(self, fullname): |
| 300 |
m = sys.modules.get(fullname) |
| 301 |
if not m: |
| 302 |
return |
| 303 |
reload_module(m) |
| 304 |
|
| 305 |
def _get_loader(self, fullname, path=None): |
| 306 |
split_name = fullname.split('.') |
| 307 |
toplevel_pkg = split_name[0] |
| 308 |
module_to_find = split_name[-1] |
| 309 |
part_count = len(split_name) |
| 310 |
|
| 311 |
if toplevel_pkg not in ['ansible', 'ansible_collections']: |
| 312 |
# not interested in anything other than ansible_collections (and limited cases under ansible) |
| 313 |
return None |
| 314 |
|
| 315 |
# sanity check what we're getting from import, canonicalize path values |
| 316 |
if part_count == 1: |
| 317 |
if path: |
| 318 |
raise ValueError('path should not be specified for top-level packages (trying to find {0})'.format(fullname)) |
| 319 |
else: |
| 320 |
# seed the path to the configured collection roots |
| 321 |
path = self._n_collection_paths |
| 322 |
|
| 323 |
if part_count > 1 and path is None: |
| 324 |
raise ValueError('path must be specified for subpackages (trying to find {0})'.format(fullname)) |
| 325 |
|
| 326 |
if toplevel_pkg == 'ansible': |
| 327 |
# something under the ansible package, delegate to our internal loader in case of redirections |
| 328 |
initialize_loader = _AnsibleInternalRedirectLoader |
| 329 |
elif part_count == 1: |
| 330 |
initialize_loader = _AnsibleCollectionRootPkgLoader |
| 331 |
elif part_count == 2: # ns pkg eg, ansible_collections, ansible_collections.somens |
| 332 |
initialize_loader = _AnsibleCollectionNSPkgLoader |
| 333 |
elif part_count == 3: # collection pkg eg, ansible_collections.somens.somecoll |
| 334 |
initialize_loader = _AnsibleCollectionPkgLoader |
| 335 |
else: |
| 336 |
# anything below the collection |
| 337 |
initialize_loader = _AnsibleCollectionLoader |
| 338 |
|
| 339 |
# NB: actual "find"ing is delegated to the constructors on the various loaders; they'll ImportError if not found |
| 340 |
try: |
| 341 |
return initialize_loader(fullname=fullname, path_list=path) |
| 342 |
except ImportError: |
| 343 |
# TODO: log attempt to load context |
| 344 |
return None |
| 345 |
|
| 346 |
def find_module(self, fullname, path=None): |
| 347 |
# Figure out what's being asked for, and delegate to a special-purpose loader |
| 348 |
return self._get_loader(fullname, path) |
| 349 |
|
| 350 |
def find_spec(self, fullname, path, target=None): |
| 351 |
loader = self._get_loader(fullname, path) |
| 352 |
|
| 353 |
if loader is None: |
| 354 |
return None |
| 355 |
|
| 356 |
spec = spec_from_loader(fullname, loader) |
| 357 |
if spec is not None and hasattr(loader, '_subpackage_search_paths'): |
| 358 |
spec.submodule_search_locations = loader._subpackage_search_paths |
| 359 |
return spec |
| 360 |
|
| 361 |
|
| 362 |
# Implements a path_hook finder for iter_modules (since it's only path based). This finder does not need to actually |
| 363 |
# function as a finder in most cases, since our meta_path finder is consulted first for *almost* everything, except |
| 364 |
# pkgutil.iter_modules, and under py2, pkgutil.get_data if the parent package passed has not been loaded yet. |
| 365 |
class _AnsiblePathHookFinder: |
| 366 |
def __init__(self, collection_finder, pathctx): |
| 367 |
# when called from a path_hook, find_module doesn't usually get the path arg, so this provides our context |
| 368 |
self._pathctx = _to_text(pathctx) |
| 369 |
self._collection_finder = collection_finder |
| 370 |
# cache the native FileFinder (take advantage of its filesystem cache for future find/load requests) |
| 371 |
self._file_finder = None |
| 372 |
|
| 373 |
# class init is fun- this method has a self arg that won't get used |
| 374 |
def _get_filefinder_path_hook(self=None): |
| 375 |
_file_finder_hook = None |
| 376 |
# try to find the FileFinder hook to call for fallback path-based imports in Py3 |
| 377 |
_file_finder_hook = [ph for ph in sys.path_hooks if 'FileFinder' in repr(ph)] |
| 378 |
if len(_file_finder_hook) != 1: |
| 379 |
raise Exception('need exactly one FileFinder import hook (found {0})'.format(len(_file_finder_hook))) |
| 380 |
_file_finder_hook = _file_finder_hook[0] |
| 381 |
|
| 382 |
return _file_finder_hook |
| 383 |
|
| 384 |
_filefinder_path_hook = _get_filefinder_path_hook() |
| 385 |
|
| 386 |
def _get_finder(self, fullname): |
| 387 |
split_name = fullname.split('.') |
| 388 |
toplevel_pkg = split_name[0] |
| 389 |
|
| 390 |
if toplevel_pkg == 'ansible_collections': |
| 391 |
# collections content? delegate to the collection finder |
| 392 |
return self._collection_finder |
| 393 |
else: |
| 394 |
# Something else; we'd normally restrict this to `ansible` descendent modules so that any weird loader |
| 395 |
# behavior that arbitrary Python modules have can be serviced by those loaders. In some dev/test |
| 396 |
# scenarios (eg a venv under a collection) our path_hook signs us up to load non-Ansible things, and |
| 397 |
# it's too late by the time we've reached this point, but also too expensive for the path_hook to figure |
| 398 |
# out what we *shouldn't* be loading with the limited info it has. So we'll just delegate to the |
| 399 |
# normal path-based loader as best we can to service it. This also allows us to take advantage of Python's |
| 400 |
# built-in FS caching and byte-compilation for most things. |
| 401 |
# create or consult our cached file finder for this path |
| 402 |
if not self._file_finder: |
| 403 |
try: |
| 404 |
self._file_finder = _AnsiblePathHookFinder._filefinder_path_hook(self._pathctx) |
| 405 |
except ImportError: |
| 406 |
# FUTURE: log at a high logging level? This is normal for things like python36.zip on the path, but |
| 407 |
# might not be in some other situation... |
| 408 |
return None |
| 409 |
|
| 410 |
return self._file_finder |
| 411 |
|
| 412 |
def find_module(self, fullname, path=None): |
| 413 |
# we ignore the passed in path here- use what we got from the path hook init |
| 414 |
finder = self._get_finder(fullname) |
| 415 |
|
| 416 |
if finder is None: |
| 417 |
return None |
| 418 |
elif isinstance(finder, FileFinder): |
| 419 |
# this codepath is erroneously used under some cases in py3, |
| 420 |
# and the find_module method on FileFinder does not accept the path arg |
| 421 |
# see https://github.com/pypa/setuptools/pull/2918 |
| 422 |
return finder.find_module(fullname) |
| 423 |
else: |
| 424 |
return finder.find_module(fullname, path=[self._pathctx]) |
| 425 |
|
| 426 |
def find_spec(self, fullname, target=None): |
| 427 |
split_name = fullname.split('.') |
| 428 |
toplevel_pkg = split_name[0] |
| 429 |
|
| 430 |
finder = self._get_finder(fullname) |
| 431 |
|
| 432 |
if finder is None: |
| 433 |
return None |
| 434 |
elif toplevel_pkg == 'ansible_collections': |
| 435 |
return finder.find_spec(fullname, path=[self._pathctx]) |
| 436 |
else: |
| 437 |
return finder.find_spec(fullname) |
| 438 |
|
| 439 |
def iter_modules(self, prefix): |
| 440 |
# NB: this currently represents only what's on disk, and does not handle package redirection |
| 441 |
return _iter_modules_impl([self._pathctx], prefix) |
| 442 |
|
| 443 |
def __repr__(self): |
| 444 |
return "{0}(path='{1}')".format(self.__class__.__name__, self._pathctx) |
| 445 |
|
| 446 |
|
| 447 |
class _AnsibleCollectionPkgLoaderBase: |
| 448 |
_allows_package_code = False |
| 449 |
|
| 450 |
def __init__(self, fullname, path_list=None): |
| 451 |
self._fullname = fullname |
| 452 |
self._redirect_module = None |
| 453 |
self._split_name = fullname.split('.') |
| 454 |
self._rpart_name = fullname.rpartition('.') |
| 455 |
self._parent_package_name = self._rpart_name[0] # eg ansible_collections for ansible_collections.somens, '' for toplevel |
| 456 |
self._package_to_load = self._rpart_name[2] # eg somens for ansible_collections.somens |
| 457 |
|
| 458 |
self._source_code_path = None |
| 459 |
self._decoded_source = None |
| 460 |
self._compiled_code = None |
| 461 |
|
| 462 |
self._validate_args() |
| 463 |
|
| 464 |
self._candidate_paths = self._get_candidate_paths([_to_text(p) for p in path_list]) |
| 465 |
self._subpackage_search_paths = self._get_subpackage_search_paths(self._candidate_paths) |
| 466 |
|
| 467 |
self._validate_final() |
| 468 |
|
| 469 |
# allow subclasses to validate args and sniff split values before we start digging around |
| 470 |
def _validate_args(self): |
| 471 |
if self._split_name[0] != 'ansible_collections': |
| 472 |
raise ImportError('this loader can only load packages from the ansible_collections package, not {0}'.format(self._fullname)) |
| 473 |
|
| 474 |
# allow subclasses to customize candidate path filtering |
| 475 |
def _get_candidate_paths(self, path_list): |
| 476 |
return [os.path.join(p, self._package_to_load) for p in path_list] |
| 477 |
|
| 478 |
# allow subclasses to customize finding paths |
| 479 |
def _get_subpackage_search_paths(self, candidate_paths): |
| 480 |
# filter candidate paths for existence (NB: silently ignoring package init code and same-named modules) |
| 481 |
return [p for p in candidate_paths if os.path.isdir(_to_bytes(p))] |
| 482 |
|
| 483 |
# allow subclasses to customize state validation/manipulation before we return the loader instance |
| 484 |
def _validate_final(self): |
| 485 |
return |
| 486 |
|
| 487 |
@staticmethod |
| 488 |
@contextmanager |
| 489 |
def _new_or_existing_module(name, **kwargs): |
| 490 |
# handle all-or-nothing sys.modules creation/use-existing/delete-on-exception-if-created behavior |
| 491 |
created_module = False |
| 492 |
module = sys.modules.get(name) |
| 493 |
try: |
| 494 |
if not module: |
| 495 |
module = ModuleType(name) |
| 496 |
created_module = True |
| 497 |
sys.modules[name] = module |
| 498 |
# always override the values passed, except name (allow reference aliasing) |
| 499 |
for attr, value in kwargs.items(): |
| 500 |
setattr(module, attr, value) |
| 501 |
yield module |
| 502 |
except Exception: |
| 503 |
if created_module: |
| 504 |
if sys.modules.get(name): |
| 505 |
sys.modules.pop(name) |
| 506 |
raise |
| 507 |
|
| 508 |
# basic module/package location support |
| 509 |
# NB: this does not support distributed packages! |
| 510 |
@staticmethod |
| 511 |
def _module_file_from_path(leaf_name, path): |
| 512 |
has_code = True |
| 513 |
package_path = os.path.join(_to_text(path), _to_text(leaf_name)) |
| 514 |
module_path = None |
| 515 |
|
| 516 |
# if the submodule is a package, assemble valid submodule paths, but stop looking for a module |
| 517 |
if os.path.isdir(_to_bytes(package_path)): |
| 518 |
# is there a package init? |
| 519 |
module_path = os.path.join(package_path, '__init__.py') |
| 520 |
if not os.path.isfile(_to_bytes(module_path)): |
| 521 |
module_path = os.path.join(package_path, '__synthetic__') |
| 522 |
has_code = False |
| 523 |
else: |
| 524 |
module_path = package_path + '.py' |
| 525 |
package_path = None |
| 526 |
if not os.path.isfile(_to_bytes(module_path)): |
| 527 |
raise ImportError('{0} not found at {1}'.format(leaf_name, path)) |
| 528 |
|
| 529 |
return module_path, has_code, package_path |
| 530 |
|
| 531 |
def get_resource_reader(self, fullname): |
| 532 |
return _AnsibleTraversableResources(fullname, self) |
| 533 |
|
| 534 |
def exec_module(self, module): |
| 535 |
# short-circuit redirect; avoid reinitializing existing modules |
| 536 |
if self._redirect_module: |
| 537 |
return |
| 538 |
|
| 539 |
# execute the module's code in its namespace |
| 540 |
code_obj = self.get_code(self._fullname) |
| 541 |
if code_obj is not None: # things like NS packages that can't have code on disk will return None |
| 542 |
exec(code_obj, module.__dict__) |
| 543 |
|
| 544 |
def create_module(self, spec): |
| 545 |
# short-circuit redirect; we've already imported the redirected module, so just alias it and return it |
| 546 |
if self._redirect_module: |
| 547 |
return self._redirect_module |
| 548 |
else: |
| 549 |
return None |
| 550 |
|
| 551 |
def load_module(self, fullname): |
| 552 |
# short-circuit redirect; we've already imported the redirected module, so just alias it and return it |
| 553 |
if self._redirect_module: |
| 554 |
sys.modules[self._fullname] = self._redirect_module |
| 555 |
return self._redirect_module |
| 556 |
|
| 557 |
# we're actually loading a module/package |
| 558 |
module_attrs = dict( |
| 559 |
__loader__=self, |
| 560 |
__file__=self.get_filename(fullname), |
| 561 |
__package__=self._parent_package_name # sane default for non-packages |
| 562 |
) |
| 563 |
|
| 564 |
# eg, I am a package |
| 565 |
if self._subpackage_search_paths is not None: # empty is legal |
| 566 |
module_attrs['__path__'] = self._subpackage_search_paths |
| 567 |
module_attrs['__package__'] = fullname # per PEP366 |
| 568 |
|
| 569 |
with self._new_or_existing_module(fullname, **module_attrs) as module: |
| 570 |
# execute the module's code in its namespace |
| 571 |
code_obj = self.get_code(fullname) |
| 572 |
if code_obj is not None: # things like NS packages that can't have code on disk will return None |
| 573 |
exec(code_obj, module.__dict__) |
| 574 |
|
| 575 |
return module |
| 576 |
|
| 577 |
def is_package(self, fullname): |
| 578 |
if fullname != self._fullname: |
| 579 |
raise ValueError('this loader cannot answer is_package for {0}, only {1}'.format(fullname, self._fullname)) |
| 580 |
return self._subpackage_search_paths is not None |
| 581 |
|
| 582 |
def get_source(self, fullname): |
| 583 |
if self._decoded_source: |
| 584 |
return self._decoded_source |
| 585 |
if fullname != self._fullname: |
| 586 |
raise ValueError('this loader cannot load source for {0}, only {1}'.format(fullname, self._fullname)) |
| 587 |
if not self._source_code_path: |
| 588 |
return None |
| 589 |
# FIXME: what do we want encoding/newline requirements to be? |
| 590 |
self._decoded_source = self.get_data(self._source_code_path) |
| 591 |
return self._decoded_source |
| 592 |
|
| 593 |
def get_data(self, path): |
| 594 |
if not path: |
| 595 |
raise ValueError('a path must be specified') |
| 596 |
|
| 597 |
# TODO: ensure we're being asked for a path below something we own |
| 598 |
# TODO: try to handle redirects internally? |
| 599 |
|
| 600 |
if not path[0] == '/': |
| 601 |
# relative to current package, search package paths if possible (this may not be necessary) |
| 602 |
# candidate_paths = [os.path.join(ssp, path) for ssp in self._subpackage_search_paths] |
| 603 |
raise ValueError('relative resource paths not supported') |
| 604 |
else: |
| 605 |
candidate_paths = [path] |
| 606 |
|
| 607 |
for p in candidate_paths: |
| 608 |
b_path = _to_bytes(p) |
| 609 |
if os.path.isfile(b_path): |
| 610 |
with open(b_path, 'rb') as fd: |
| 611 |
return fd.read() |
| 612 |
# HACK: if caller asks for __init__.py and the parent dir exists, return empty string (this keep consistency |
| 613 |
# with "collection subpackages don't require __init__.py" working everywhere with get_data |
| 614 |
elif b_path.endswith(b'__init__.py') and os.path.isdir(os.path.dirname(b_path)): |
| 615 |
return b'' |
| 616 |
|
| 617 |
return None |
| 618 |
|
| 619 |
def _synthetic_filename(self, fullname): |
| 620 |
return SYNTHETIC_PACKAGE_NAME |
| 621 |
|
| 622 |
def get_filename(self, fullname): |
| 623 |
if fullname != self._fullname: |
| 624 |
raise ValueError('this loader cannot find files for {0}, only {1}'.format(fullname, self._fullname)) |
| 625 |
|
| 626 |
filename = self._source_code_path |
| 627 |
|
| 628 |
if not filename and self.is_package(fullname): |
| 629 |
if len(self._subpackage_search_paths) == 1: |
| 630 |
filename = os.path.join(self._subpackage_search_paths[0], '__synthetic__') |
| 631 |
else: |
| 632 |
filename = self._synthetic_filename(fullname) |
| 633 |
|
| 634 |
return filename |
| 635 |
|
| 636 |
def get_code(self, fullname): |
| 637 |
if self._compiled_code: |
| 638 |
return self._compiled_code |
| 639 |
|
| 640 |
# this may or may not be an actual filename, but it's the value we'll use for __file__ |
| 641 |
filename = self.get_filename(fullname) |
| 642 |
if not filename: |
| 643 |
filename = '<string>' |
| 644 |
|
| 645 |
source_code = self.get_source(fullname) |
| 646 |
|
| 647 |
# for things like synthetic modules that really have no source on disk, don't return a code object at all |
| 648 |
# vs things like an empty package init (which has an empty string source on disk) |
| 649 |
if source_code is None: |
| 650 |
return None |
| 651 |
|
| 652 |
self._compiled_code = compile(source=source_code, filename=filename, mode='exec', flags=0, dont_inherit=True) |
| 653 |
|
| 654 |
return self._compiled_code |
| 655 |
|
| 656 |
def iter_modules(self, prefix): |
| 657 |
return _iter_modules_impl(self._subpackage_search_paths, prefix) |
| 658 |
|
| 659 |
def __repr__(self): |
| 660 |
return '{0}(path={1})'.format(self.__class__.__name__, self._subpackage_search_paths or self._source_code_path) |
| 661 |
|
| 662 |
|
| 663 |
class _AnsibleCollectionRootPkgLoader(_AnsibleCollectionPkgLoaderBase): |
| 664 |
def _validate_args(self): |
| 665 |
super(_AnsibleCollectionRootPkgLoader, self)._validate_args() |
| 666 |
if len(self._split_name) != 1: |
| 667 |
raise ImportError('this loader can only load the ansible_collections toplevel package, not {0}'.format(self._fullname)) |
| 668 |
|
| 669 |
|
| 670 |
# Implements Ansible's custom namespace package support. |
| 671 |
# The ansible_collections package and one level down (collections namespaces) are Python namespace packages |
| 672 |
# that search across all configured collection roots. The collection package (two levels down) is the first one found |
| 673 |
# on the configured collection root path, and Python namespace package aggregation is not allowed at or below |
| 674 |
# the collection. Implements implicit package (package dir) support for both Py2/3. Package init code is ignored |
| 675 |
# by this loader. |
| 676 |
class _AnsibleCollectionNSPkgLoader(_AnsibleCollectionPkgLoaderBase): |
| 677 |
def _validate_args(self): |
| 678 |
super(_AnsibleCollectionNSPkgLoader, self)._validate_args() |
| 679 |
if len(self._split_name) != 2: |
| 680 |
raise ImportError('this loader can only load collections namespace packages, not {0}'.format(self._fullname)) |
| 681 |
|
| 682 |
def _validate_final(self): |
| 683 |
# special-case the `ansible` namespace, since `ansible.builtin` is magical |
| 684 |
if not self._subpackage_search_paths and self._package_to_load != 'ansible': |
| 685 |
raise ImportError('no {0} found in {1}'.format(self._package_to_load, self._candidate_paths)) |
| 686 |
|
| 687 |
|
| 688 |
# handles locating the actual collection package and associated metadata |
| 689 |
class _AnsibleCollectionPkgLoader(_AnsibleCollectionPkgLoaderBase): |
| 690 |
def _validate_args(self): |
| 691 |
super(_AnsibleCollectionPkgLoader, self)._validate_args() |
| 692 |
if len(self._split_name) != 3: |
| 693 |
raise ImportError('this loader can only load collection packages, not {0}'.format(self._fullname)) |
| 694 |
|
| 695 |
def _validate_final(self): |
| 696 |
if self._split_name[1:3] == ['ansible', 'builtin']: |
| 697 |
# we don't want to allow this one to have on-disk search capability |
| 698 |
self._subpackage_search_paths = [] |
| 699 |
elif not self._subpackage_search_paths: |
| 700 |
raise ImportError('no {0} found in {1}'.format(self._package_to_load, self._candidate_paths)) |
| 701 |
else: |
| 702 |
# only search within the first collection we found |
| 703 |
self._subpackage_search_paths = [self._subpackage_search_paths[0]] |
| 704 |
|
| 705 |
def _load_module(self, module): |
| 706 |
if not _meta_yml_to_dict: |
| 707 |
raise ValueError('ansible.utils.collection_loader._meta_yml_to_dict is not set') |
| 708 |
|
| 709 |
module._collection_meta = {} |
| 710 |
# TODO: load collection metadata, cache in __loader__ state |
| 711 |
|
| 712 |
collection_name = '.'.join(self._split_name[1:3]) |
| 713 |
|
| 714 |
if collection_name == 'ansible.builtin': |
| 715 |
# ansible.builtin is a synthetic collection, get its routing config from the Ansible distro |
| 716 |
ansible_pkg_path = os.path.dirname(import_module('ansible').__file__) |
| 717 |
metadata_path = os.path.join(ansible_pkg_path, 'config/ansible_builtin_runtime.yml') |
| 718 |
with open(_to_bytes(metadata_path), 'rb') as fd: |
| 719 |
raw_routing = fd.read() |
| 720 |
else: |
| 721 |
b_routing_meta_path = _to_bytes(os.path.join(module.__path__[0], 'meta/runtime.yml')) |
| 722 |
if os.path.isfile(b_routing_meta_path): |
| 723 |
with open(b_routing_meta_path, 'rb') as fd: |
| 724 |
raw_routing = fd.read() |
| 725 |
else: |
| 726 |
raw_routing = '' |
| 727 |
try: |
| 728 |
if raw_routing: |
| 729 |
routing_dict = _meta_yml_to_dict(raw_routing, (collection_name, 'runtime.yml')) |
| 730 |
module._collection_meta = self._canonicalize_meta(routing_dict) |
| 731 |
except Exception as ex: |
| 732 |
raise ValueError(f'error parsing collection metadata: {ex}') |
| 733 |
|
| 734 |
AnsibleCollectionConfig.on_collection_load.fire(collection_name=collection_name, collection_path=os.path.dirname(module.__file__)) |
| 735 |
|
| 736 |
return module |
| 737 |
|
| 738 |
def exec_module(self, module): |
| 739 |
super(_AnsibleCollectionPkgLoader, self).exec_module(module) |
| 740 |
self._load_module(module) |
| 741 |
|
| 742 |
def create_module(self, spec): |
| 743 |
return None |
| 744 |
|
| 745 |
def load_module(self, fullname): |
| 746 |
module = super(_AnsibleCollectionPkgLoader, self).load_module(fullname) |
| 747 |
return self._load_module(module) |
| 748 |
|
| 749 |
def _canonicalize_meta(self, meta_dict): |
| 750 |
# TODO: rewrite import keys and all redirect targets that start with .. (current namespace) and . (current collection) |
| 751 |
# OR we could do it all on the fly? |
| 752 |
# if not meta_dict: |
| 753 |
# return {} |
| 754 |
# |
| 755 |
# ns_name = '.'.join(self._split_name[0:2]) |
| 756 |
# collection_name = '.'.join(self._split_name[0:3]) |
| 757 |
# |
| 758 |
# # |
| 759 |
# for routing_type, routing_type_dict in iteritems(meta_dict.get('plugin_routing', {})): |
| 760 |
# for plugin_key, plugin_dict in iteritems(routing_type_dict): |
| 761 |
# redirect = plugin_dict.get('redirect', '') |
| 762 |
# if redirect.startswith('..'): |
| 763 |
# redirect = redirect[2:] |
| 764 |
|
| 765 |
return meta_dict |
| 766 |
|
| 767 |
|
| 768 |
# loads everything under a collection, including handling redirections defined by the collection |
| 769 |
class _AnsibleCollectionLoader(_AnsibleCollectionPkgLoaderBase): |
| 770 |
# HACK: stash this in a better place |
| 771 |
_redirected_package_map = {} # type: dict[str, str] |
| 772 |
_allows_package_code = True |
| 773 |
|
| 774 |
def _validate_args(self): |
| 775 |
super(_AnsibleCollectionLoader, self)._validate_args() |
| 776 |
if len(self._split_name) < 4: |
| 777 |
raise ValueError('this loader is only for sub-collection modules/packages, not {0}'.format(self._fullname)) |
| 778 |
|
| 779 |
def _get_candidate_paths(self, path_list): |
| 780 |
if len(path_list) != 1 and self._split_name[1:3] != ['ansible', 'builtin']: |
| 781 |
raise ValueError('this loader requires exactly one path to search') |
| 782 |
|
| 783 |
return path_list |
| 784 |
|
| 785 |
def _get_subpackage_search_paths(self, candidate_paths): |
| 786 |
collection_name = '.'.join(self._split_name[1:3]) |
| 787 |
collection_meta = _get_collection_metadata(collection_name) |
| 788 |
|
| 789 |
# check for explicit redirection, as well as ancestor package-level redirection (only load the actual code once!) |
| 790 |
redirect = None |
| 791 |
explicit_redirect = False |
| 792 |
|
| 793 |
routing_entry = _nested_dict_get(collection_meta, ['import_redirection', self._fullname]) |
| 794 |
if routing_entry: |
| 795 |
redirect = routing_entry.get('redirect') |
| 796 |
|
| 797 |
if redirect: |
| 798 |
explicit_redirect = True |
| 799 |
else: |
| 800 |
redirect = _get_ancestor_redirect(self._redirected_package_map, self._fullname) |
| 801 |
|
| 802 |
# NB: package level redirection requires hooking all future imports beneath the redirected source package |
| 803 |
# in order to ensure sanity on future relative imports. We always import everything under its "real" name, |
| 804 |
# then add a sys.modules entry with the redirected name using the same module instance. If we naively imported |
| 805 |
# the source for each redirection, most submodules would import OK, but we'd have N runtime copies of the module |
| 806 |
# (one for each name), and relative imports that ascend above the redirected package would break (since they'd |
| 807 |
# see the redirected ancestor package contents instead of the package where they actually live). |
| 808 |
if redirect: |
| 809 |
# FIXME: wrap this so we can be explicit about a failed redirection |
| 810 |
self._redirect_module = import_module(redirect) |
| 811 |
if explicit_redirect and hasattr(self._redirect_module, '__path__') and self._redirect_module.__path__: |
| 812 |
# if the import target looks like a package, store its name so we can rewrite future descendent loads |
| 813 |
self._redirected_package_map[self._fullname] = redirect |
| 814 |
|
| 815 |
# if we redirected, don't do any further custom package logic |
| 816 |
return None |
| 817 |
|
| 818 |
# we're not doing a redirect- try to find what we need to actually load a module/package |
| 819 |
|
| 820 |
# this will raise ImportError if we can't find the requested module/package at all |
| 821 |
if not candidate_paths: |
| 822 |
# noplace to look, just ImportError |
| 823 |
raise ImportError('package has no paths') |
| 824 |
|
| 825 |
found_path, has_code, package_path = self._module_file_from_path(self._package_to_load, candidate_paths[0]) |
| 826 |
|
| 827 |
# still here? we found something to load... |
| 828 |
if has_code: |
| 829 |
self._source_code_path = found_path |
| 830 |
|
| 831 |
if package_path: |
| 832 |
return [package_path] # always needs to be a list |
| 833 |
|
| 834 |
return None |
| 835 |
|
| 836 |
|
| 837 |
# This loader only answers for intercepted Ansible Python modules. Normal imports will fail here and be picked up later |
| 838 |
# by our path_hook importer (which proxies the built-in import mechanisms, allowing normal caching etc to occur) |
| 839 |
class _AnsibleInternalRedirectLoader: |
| 840 |
def __init__(self, fullname, path_list): |
| 841 |
self._redirect = None |
| 842 |
|
| 843 |
split_name = fullname.split('.') |
| 844 |
toplevel_pkg = split_name[0] |
| 845 |
module_to_load = split_name[-1] |
| 846 |
|
| 847 |
if toplevel_pkg != 'ansible': |
| 848 |
raise ImportError('not interested') |
| 849 |
|
| 850 |
builtin_meta = _get_collection_metadata('ansible.builtin') |
| 851 |
|
| 852 |
routing_entry = _nested_dict_get(builtin_meta, ['import_redirection', fullname]) |
| 853 |
if routing_entry: |
| 854 |
self._redirect = routing_entry.get('redirect') |
| 855 |
|
| 856 |
if not self._redirect: |
| 857 |
raise ImportError('not redirected, go ask path_hook') |
| 858 |
|
| 859 |
def get_resource_reader(self, fullname): |
| 860 |
return _AnsibleTraversableResources(fullname, self) |
| 861 |
|
| 862 |
def exec_module(self, module): |
| 863 |
# should never see this |
| 864 |
if not self._redirect: |
| 865 |
raise ValueError('no redirect found for {0}'.format(module.__spec__.name)) |
| 866 |
|
| 867 |
# Replace the module with the redirect |
| 868 |
sys.modules[module.__spec__.name] = import_module(self._redirect) |
| 869 |
|
| 870 |
def create_module(self, spec): |
| 871 |
return None |
| 872 |
|
| 873 |
def load_module(self, fullname): |
| 874 |
# since we're delegating to other loaders, this should only be called for internal redirects where we answered |
| 875 |
# find_module with this loader, in which case we'll just directly import the redirection target, insert it into |
| 876 |
# sys.modules under the name it was requested by, and return the original module. |
| 877 |
|
| 878 |
# should never see this |
| 879 |
if not self._redirect: |
| 880 |
raise ValueError('no redirect found for {0}'.format(fullname)) |
| 881 |
|
| 882 |
# FIXME: smuggle redirection context, provide warning/error that we tried and failed to redirect |
| 883 |
mod = import_module(self._redirect) |
| 884 |
sys.modules[fullname] = mod |
| 885 |
return mod |
| 886 |
|
| 887 |
|
| 888 |
class AnsibleCollectionRef: |
| 889 |
# FUTURE: introspect plugin loaders to get these dynamically? |
| 890 |
VALID_REF_TYPES = frozenset(_to_text(r) for r in ['action', 'become', 'cache', 'callback', 'cliconf', 'connection', |
| 891 |
'doc_fragments', 'filter', 'httpapi', 'inventory', 'lookup', |
| 892 |
'module_utils', 'modules', 'netconf', 'role', 'shell', 'strategy', |
| 893 |
'terminal', 'test', 'vars', 'playbook']) |
| 894 |
|
| 895 |
# FIXME: tighten this up to match Python identifier reqs, etc |
| 896 |
VALID_SUBDIRS_RE = re.compile(_to_text(r'^\w+(\.\w+)*$')) |
| 897 |
VALID_FQCR_RE = re.compile(_to_text(r'^\w+(\.\w+){2,}$')) # can have 0-N included subdirs as well |
| 898 |
|
| 899 |
def __init__(self, collection_name, subdirs, resource, ref_type): |
| 900 |
""" |
| 901 |
Create an AnsibleCollectionRef from components |
| 902 |
:param collection_name: a collection name of the form 'namespace.collectionname' |
| 903 |
:param subdirs: optional subdir segments to be appended below the plugin type (eg, 'subdir1.subdir2') |
| 904 |
:param resource: the name of the resource being references (eg, 'mymodule', 'someaction', 'a_role') |
| 905 |
:param ref_type: the type of the reference, eg 'module', 'role', 'doc_fragment' |
| 906 |
""" |
| 907 |
collection_name = _to_text(collection_name, strict=True) |
| 908 |
if subdirs is not None: |
| 909 |
subdirs = _to_text(subdirs, strict=True) |
| 910 |
resource = _to_text(resource, strict=True) |
| 911 |
ref_type = _to_text(ref_type, strict=True) |
| 912 |
|
| 913 |
if not self.is_valid_collection_name(collection_name): |
| 914 |
raise ValueError('invalid collection name (must be of the form namespace.collection): {0}'.format(_to_text(collection_name))) |
| 915 |
|
| 916 |
if ref_type not in self.VALID_REF_TYPES: |
| 917 |
raise ValueError('invalid collection ref_type: {0}'.format(ref_type)) |
| 918 |
|
| 919 |
self.collection = collection_name |
| 920 |
if subdirs: |
| 921 |
if not re.match(self.VALID_SUBDIRS_RE, subdirs): |
| 922 |
raise ValueError('invalid subdirs entry: {0} (must be empty/None or of the form subdir1.subdir2)'.format(_to_text(subdirs))) |
| 923 |
self.subdirs = subdirs |
| 924 |
else: |
| 925 |
self.subdirs = u'' |
| 926 |
|
| 927 |
self.resource = resource |
| 928 |
self.ref_type = ref_type |
| 929 |
|
| 930 |
package_components = [u'ansible_collections', self.collection] |
| 931 |
fqcr_components = [self.collection] |
| 932 |
|
| 933 |
self.n_python_collection_package_name = _to_text('.'.join(package_components)) |
| 934 |
|
| 935 |
if self.ref_type == u'role': |
| 936 |
package_components.append(u'roles') |
| 937 |
elif self.ref_type == u'playbook': |
| 938 |
package_components.append(u'playbooks') |
| 939 |
else: |
| 940 |
# we assume it's a plugin |
| 941 |
package_components += [u'plugins', self.ref_type] |
| 942 |
|
| 943 |
if self.subdirs: |
| 944 |
package_components.append(self.subdirs) |
| 945 |
fqcr_components.append(self.subdirs) |
| 946 |
|
| 947 |
if self.ref_type in (u'role', u'playbook'): |
| 948 |
# playbooks and roles are their own resource |
| 949 |
package_components.append(self.resource) |
| 950 |
|
| 951 |
fqcr_components.append(self.resource) |
| 952 |
|
| 953 |
self.n_python_package_name = _to_text('.'.join(package_components)) |
| 954 |
self._fqcr = u'.'.join(fqcr_components) |
| 955 |
|
| 956 |
def __repr__(self): |
| 957 |
return 'AnsibleCollectionRef(collection={0!r}, subdirs={1!r}, resource={2!r})'.format(self.collection, self.subdirs, self.resource) |
| 958 |
|
| 959 |
@property |
| 960 |
def fqcr(self): |
| 961 |
return self._fqcr |
| 962 |
|
| 963 |
@staticmethod |
| 964 |
def from_fqcr(ref, ref_type): |
| 965 |
""" |
| 966 |
Parse a string as a fully-qualified collection reference, raises ValueError if invalid |
| 967 |
:param ref: collection reference to parse (a valid ref is of the form 'ns.coll.resource' or 'ns.coll.subdir1.subdir2.resource') |
| 968 |
:param ref_type: the type of the reference, eg 'module', 'role', 'doc_fragment' |
| 969 |
:return: a populated AnsibleCollectionRef object |
| 970 |
""" |
| 971 |
# assuming the fq_name is of the form (ns).(coll).(optional_subdir_N).(resource_name), |
| 972 |
# we split the resource name off the right, split ns and coll off the left, and we're left with any optional |
| 973 |
# subdirs that need to be added back below the plugin-specific subdir we'll add. So: |
| 974 |
# ns.coll.resource -> ansible_collections.ns.coll.plugins.(plugintype).resource |
| 975 |
# ns.coll.subdir1.resource -> ansible_collections.ns.coll.plugins.subdir1.(plugintype).resource |
| 976 |
# ns.coll.rolename -> ansible_collections.ns.coll.roles.rolename |
| 977 |
if not AnsibleCollectionRef.is_valid_fqcr(ref): |
| 978 |
raise ValueError('{0} is not a valid collection reference'.format(_to_text(ref))) |
| 979 |
|
| 980 |
ref = _to_text(ref, strict=True) |
| 981 |
ref_type = _to_text(ref_type, strict=True) |
| 982 |
ext = '' |
| 983 |
|
| 984 |
if ref_type == u'playbook' and ref.endswith(PB_EXTENSIONS): |
| 985 |
resource_splitname = ref.rsplit(u'.', 2) |
| 986 |
package_remnant = resource_splitname[0] |
| 987 |
resource = resource_splitname[1] |
| 988 |
ext = '.' + resource_splitname[2] |
| 989 |
else: |
| 990 |
resource_splitname = ref.rsplit(u'.', 1) |
| 991 |
package_remnant = resource_splitname[0] |
| 992 |
resource = resource_splitname[1] |
| 993 |
|
| 994 |
# split the left two components of the collection package name off, anything remaining is plugin-type |
| 995 |
# specific subdirs to be added back on below the plugin type |
| 996 |
package_splitname = package_remnant.split(u'.', 2) |
| 997 |
if len(package_splitname) == 3: |
| 998 |
subdirs = package_splitname[2] |
| 999 |
else: |
| 1000 |
subdirs = u'' |
| 1001 |
|
| 1002 |
collection_name = u'.'.join(package_splitname[0:2]) |
| 1003 |
|
| 1004 |
return AnsibleCollectionRef(collection_name, subdirs, resource + ext, ref_type) |
| 1005 |
|
| 1006 |
@staticmethod |
| 1007 |
def try_parse_fqcr(ref, ref_type): |
| 1008 |
""" |
| 1009 |
Attempt to parse a string as a fully-qualified collection reference, returning None on failure (instead of raising an error) |
| 1010 |
:param ref: collection reference to parse (a valid ref is of the form 'ns.coll.resource' or 'ns.coll.subdir1.subdir2.resource') |
| 1011 |
:param ref_type: the type of the reference, eg 'module', 'role', 'doc_fragment' |
| 1012 |
:return: a populated AnsibleCollectionRef object on successful parsing, else None |
| 1013 |
""" |
| 1014 |
try: |
| 1015 |
return AnsibleCollectionRef.from_fqcr(ref, ref_type) |
| 1016 |
except ValueError: |
| 1017 |
pass |
| 1018 |
|
| 1019 |
@staticmethod |
| 1020 |
def legacy_plugin_dir_to_plugin_type(legacy_plugin_dir_name): |
| 1021 |
""" |
| 1022 |
Utility method to convert from a PluginLoader dir name to a plugin ref_type |
| 1023 |
:param legacy_plugin_dir_name: PluginLoader dir name (eg, 'action_plugins', 'library') |
| 1024 |
:return: the corresponding plugin ref_type (eg, 'action', 'role') |
| 1025 |
""" |
| 1026 |
if legacy_plugin_dir_name is None: |
| 1027 |
plugin_type = None |
| 1028 |
else: |
| 1029 |
legacy_plugin_dir_name = _to_text(legacy_plugin_dir_name) |
| 1030 |
|
| 1031 |
plugin_type = legacy_plugin_dir_name.removesuffix(u'_plugins') |
| 1032 |
|
| 1033 |
if plugin_type == u'library': |
| 1034 |
plugin_type = u'modules' |
| 1035 |
|
| 1036 |
if plugin_type not in AnsibleCollectionRef.VALID_REF_TYPES: |
| 1037 |
raise ValueError(f'{legacy_plugin_dir_name!r} cannot be mapped to a valid collection ref type') |
| 1038 |
|
| 1039 |
return plugin_type |
| 1040 |
|
| 1041 |
@staticmethod |
| 1042 |
def is_valid_fqcr(ref, ref_type=None): |
| 1043 |
""" |
| 1044 |
Validates if is string is a well-formed fully-qualified collection reference (does not look up the collection itself) |
| 1045 |
:param ref: candidate collection reference to validate (a valid ref is of the form 'ns.coll.resource' or 'ns.coll.subdir1.subdir2.resource') |
| 1046 |
:param ref_type: optional reference type to enable deeper validation, eg 'module', 'role', 'doc_fragment' |
| 1047 |
:return: True if the collection ref passed is well-formed, False otherwise |
| 1048 |
""" |
| 1049 |
|
| 1050 |
ref = _to_text(ref) |
| 1051 |
|
| 1052 |
if not ref_type: |
| 1053 |
return bool(re.match(AnsibleCollectionRef.VALID_FQCR_RE, ref)) |
| 1054 |
|
| 1055 |
return bool(AnsibleCollectionRef.try_parse_fqcr(ref, ref_type)) |
| 1056 |
|
| 1057 |
@staticmethod |
| 1058 |
def is_valid_collection_name(collection_name): |
| 1059 |
""" |
| 1060 |
Validates if the given string is a well-formed collection name (does not look up the collection itself) |
| 1061 |
:param collection_name: candidate collection name to validate (a valid name is of the form 'ns.collname') |
| 1062 |
:return: True if the collection name passed is well-formed, False otherwise |
| 1063 |
""" |
| 1064 |
|
| 1065 |
collection_name = _to_text(collection_name) |
| 1066 |
|
| 1067 |
if collection_name.count(u'.') != 1: |
| 1068 |
return False |
| 1069 |
|
| 1070 |
return all( |
| 1071 |
# NOTE: keywords and identifiers are different in different Pythons |
| 1072 |
not iskeyword(ns_or_name) and ns_or_name.isidentifier() |
| 1073 |
for ns_or_name in collection_name.split(u'.') |
| 1074 |
) |
| 1075 |
|
| 1076 |
|
| 1077 |
def _get_collection_path(collection_name): |
| 1078 |
collection_name = _to_text(collection_name) |
| 1079 |
if not collection_name or not isinstance(collection_name, str) or len(collection_name.split('.')) != 2: |
| 1080 |
raise ValueError('collection_name must be a non-empty string of the form namespace.collection') |
| 1081 |
try: |
| 1082 |
collection_pkg = import_module('ansible_collections.' + collection_name) |
| 1083 |
except ImportError: |
| 1084 |
raise ValueError('unable to locate collection {0}'.format(collection_name)) |
| 1085 |
|
| 1086 |
return _to_text(os.path.dirname(_to_bytes(collection_pkg.__file__))) |
| 1087 |
|
| 1088 |
|
| 1089 |
def _get_collection_playbook_path(playbook): |
| 1090 |
|
| 1091 |
acr = AnsibleCollectionRef.try_parse_fqcr(playbook, u'playbook') |
| 1092 |
if acr: |
| 1093 |
try: |
| 1094 |
# get_collection_path |
| 1095 |
pkg = import_module(acr.n_python_collection_package_name) |
| 1096 |
except (OSError, ModuleNotFoundError) as ex: |
| 1097 |
# leaving ex as debug target, even though not used in normal code |
| 1098 |
pkg = None |
| 1099 |
|
| 1100 |
if pkg: |
| 1101 |
cpath = os.path.join(sys.modules[acr.n_python_collection_package_name].__file__.replace('__synthetic__', 'playbooks')) |
| 1102 |
|
| 1103 |
if acr.subdirs: |
| 1104 |
paths = [_to_text(x) for x in acr.subdirs.split(u'.')] |
| 1105 |
paths.insert(0, cpath) |
| 1106 |
cpath = os.path.join(*paths) |
| 1107 |
|
| 1108 |
path = os.path.join(cpath, _to_text(acr.resource)) |
| 1109 |
if os.path.exists(_to_bytes(path)): |
| 1110 |
return acr.resource, path, acr.collection |
| 1111 |
elif not acr.resource.endswith(PB_EXTENSIONS): |
| 1112 |
for ext in PB_EXTENSIONS: |
| 1113 |
path = os.path.join(cpath, _to_text(acr.resource + ext)) |
| 1114 |
if os.path.exists(_to_bytes(path)): |
| 1115 |
return acr.resource, path, acr.collection |
| 1116 |
return None |
| 1117 |
|
| 1118 |
|
| 1119 |
def _get_collection_role_path(role_name, collection_list=None): |
| 1120 |
return _get_collection_resource_path(role_name, u'role', collection_list) |
| 1121 |
|
| 1122 |
|
| 1123 |
def _get_collection_resource_path(name, ref_type, collection_list=None): |
| 1124 |
|
| 1125 |
if ref_type == u'playbook': |
| 1126 |
# they are handled a bit diff due to 'extension variance' and no collection_list |
| 1127 |
return _get_collection_playbook_path(name) |
| 1128 |
|
| 1129 |
acr = AnsibleCollectionRef.try_parse_fqcr(name, ref_type) |
| 1130 |
if acr: |
| 1131 |
# looks like a valid qualified collection ref; skip the collection_list |
| 1132 |
collection_list = [acr.collection] |
| 1133 |
subdirs = acr.subdirs |
| 1134 |
resource = acr.resource |
| 1135 |
elif not collection_list: |
| 1136 |
return None # not a FQ and no collection search list spec'd, nothing to do |
| 1137 |
else: |
| 1138 |
resource = name # treat as unqualified, loop through the collection search list to try and resolve |
| 1139 |
subdirs = '' |
| 1140 |
|
| 1141 |
for collection_name in collection_list: |
| 1142 |
try: |
| 1143 |
acr = AnsibleCollectionRef(collection_name=collection_name, subdirs=subdirs, resource=resource, ref_type=ref_type) |
| 1144 |
# FIXME: error handling/logging; need to catch any import failures and move along |
| 1145 |
pkg = import_module(acr.n_python_package_name) |
| 1146 |
|
| 1147 |
if pkg is not None: |
| 1148 |
# the package is now loaded, get the collection's package and ask where it lives |
| 1149 |
path = os.path.dirname(_to_bytes(sys.modules[acr.n_python_package_name].__file__)) |
| 1150 |
return resource, _to_text(path), collection_name |
| 1151 |
|
| 1152 |
except (OSError, ModuleNotFoundError) as ex: |
| 1153 |
continue |
| 1154 |
except Exception as ex: |
| 1155 |
# FIXME: pick out typical import errors first, then error logging |
| 1156 |
continue |
| 1157 |
|
| 1158 |
return None |
| 1159 |
|
| 1160 |
|
| 1161 |
def _get_collection_name_from_path(path): |
| 1162 |
""" |
| 1163 |
Return the containing collection name for a given path, or None if the path is not below a configured collection, or |
| 1164 |
the collection cannot be loaded (eg, the collection is masked by another of the same name higher in the configured |
| 1165 |
collection roots). |
| 1166 |
:param path: path to evaluate for collection containment |
| 1167 |
:return: collection name or None |
| 1168 |
""" |
| 1169 |
|
| 1170 |
# ensure we compare full paths since pkg path will be abspath |
| 1171 |
path = _to_text(os.path.abspath(_to_bytes(path))) |
| 1172 |
|
| 1173 |
path_parts = path.split('/') |
| 1174 |
if path_parts.count('ansible_collections') != 1: |
| 1175 |
return None |
| 1176 |
|
| 1177 |
ac_pos = path_parts.index('ansible_collections') |
| 1178 |
|
| 1179 |
# make sure it's followed by at least a namespace and collection name |
| 1180 |
if len(path_parts) < ac_pos + 3: |
| 1181 |
return None |
| 1182 |
|
| 1183 |
candidate_collection_name = '.'.join(path_parts[ac_pos + 1:ac_pos + 3]) |
| 1184 |
|
| 1185 |
try: |
| 1186 |
# we've got a name for it, now see if the path prefix matches what the loader sees |
| 1187 |
imported_pkg_path = _to_text(os.path.dirname(_to_bytes(import_module('ansible_collections.' + candidate_collection_name).__file__))) |
| 1188 |
except ImportError: |
| 1189 |
return None |
| 1190 |
|
| 1191 |
# reassemble the original path prefix up the collection name, and it should match what we just imported. If not |
| 1192 |
# this is probably a collection root that's not configured. |
| 1193 |
|
| 1194 |
original_path_prefix = os.path.join('/', *path_parts[0:ac_pos + 3]) |
| 1195 |
|
| 1196 |
imported_pkg_path = _to_text(os.path.abspath(_to_bytes(imported_pkg_path))) |
| 1197 |
if original_path_prefix != imported_pkg_path: |
| 1198 |
return None |
| 1199 |
|
| 1200 |
return candidate_collection_name |
| 1201 |
|
| 1202 |
|
| 1203 |
def _get_import_redirect(collection_meta_dict, fullname): |
| 1204 |
if not collection_meta_dict: |
| 1205 |
return None |
| 1206 |
|
| 1207 |
return _nested_dict_get(collection_meta_dict, ['import_redirection', fullname, 'redirect']) |
| 1208 |
|
| 1209 |
|
| 1210 |
def _get_ancestor_redirect(redirected_package_map, fullname): |
| 1211 |
# walk the requested module's ancestor packages to see if any have been previously redirected |
| 1212 |
cur_pkg = fullname |
| 1213 |
while cur_pkg: |
| 1214 |
cur_pkg = cur_pkg.rpartition('.')[0] |
| 1215 |
ancestor_redirect = redirected_package_map.get(cur_pkg) |
| 1216 |
if ancestor_redirect: |
| 1217 |
# rewrite the prefix on fullname so we import the target first, then alias it |
| 1218 |
redirect = ancestor_redirect + fullname[len(cur_pkg):] |
| 1219 |
return redirect |
| 1220 |
return None |
| 1221 |
|
| 1222 |
|
| 1223 |
def _nested_dict_get(root_dict, key_list): |
| 1224 |
cur_value = root_dict |
| 1225 |
for key in key_list: |
| 1226 |
cur_value = cur_value.get(key) |
| 1227 |
if not cur_value: |
| 1228 |
return None |
| 1229 |
|
| 1230 |
return cur_value |
| 1231 |
|
| 1232 |
|
| 1233 |
def _iter_modules_impl(paths, prefix=''): |
| 1234 |
# NB: this currently only iterates what's on disk- redirected modules are not considered |
| 1235 |
if not prefix: |
| 1236 |
prefix = '' |
| 1237 |
else: |
| 1238 |
prefix = _to_text(prefix) |
| 1239 |
# yield (module_loader, name, ispkg) for each module/pkg under path |
| 1240 |
# TODO: implement ignore/silent catch for unreadable? |
| 1241 |
# Mostly based off the logic in the builtin pkgutil.iter_modules importer. |
| 1242 |
# Only difference is we don't check if dirs contains __init__. |
| 1243 |
# https://github.com/python/cpython/blob/fda056e64bdfcac3dd3d13eebda0a24994d83cb8/Lib/pkgutil.py#L130-L168 |
| 1244 |
for path in paths: |
| 1245 |
if not os.path.isdir(path): |
| 1246 |
continue |
| 1247 |
|
| 1248 |
yielded = {'__init__'} |
| 1249 |
for basename in sorted(os.listdir(path)): |
| 1250 |
modname = inspect.getmodulename(basename) |
| 1251 |
if modname in yielded: |
| 1252 |
continue |
| 1253 |
|
| 1254 |
mod_path = os.path.join(path, basename) |
| 1255 |
ispkg = False |
| 1256 |
if not modname and os.path.isdir(mod_path) and '.' not in basename: |
| 1257 |
# exclude things that obviously aren't Python package dirs |
| 1258 |
# FIXME: this dir is adjustable in py3.8+, check for it |
| 1259 |
if basename == '__pycache__': |
| 1260 |
continue |
| 1261 |
|
| 1262 |
modname = basename |
| 1263 |
ispkg = True |
| 1264 |
|
| 1265 |
if modname and '.' not in modname: |
| 1266 |
yielded.add(modname) |
| 1267 |
yield prefix + modname, ispkg |
| 1268 |
|
| 1269 |
|
| 1270 |
def _get_collection_metadata(collection_name): |
| 1271 |
collection_name = _to_text(collection_name) |
| 1272 |
if not collection_name or not isinstance(collection_name, str) or len(collection_name.split('.')) != 2: |
| 1273 |
raise ValueError('collection_name must be a non-empty string of the form namespace.collection') |
| 1274 |
|
| 1275 |
try: |
| 1276 |
collection_pkg = import_module('ansible_collections.' + collection_name) |
| 1277 |
except ImportError as ex: |
| 1278 |
raise ValueError('unable to locate collection {0}'.format(collection_name)) from ex |
| 1279 |
|
| 1280 |
_collection_meta = getattr(collection_pkg, '_collection_meta', None) |
| 1281 |
|
| 1282 |
if _collection_meta is None: |
| 1283 |
raise ValueError('collection metadata was not loaded for collection {0}'.format(collection_name)) |
| 1284 |
|
| 1285 |
return _collection_meta |