| 1 |
# (c) Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
|
| 7 |
import dataclasses |
| 8 |
import os |
| 9 |
|
| 10 |
from ansible import context |
| 11 |
from ansible import constants as C |
| 12 |
from ansible.collections.list import list_collections |
| 13 |
from ansible.errors import AnsibleError |
| 14 |
from ansible.module_utils.common.text.converters import to_native, to_bytes |
| 15 |
from ansible.plugins import loader |
| 16 |
from ansible.utils.display import Display |
| 17 |
from ansible.utils.collection_loader._collection_finder import _get_collection_path |
| 18 |
from ansible._internal._templating._jinja_plugins import get_jinja_builtin_plugin_descriptions |
| 19 |
|
| 20 |
display = Display() |
| 21 |
|
| 22 |
# not real plugins |
| 23 |
IGNORE = { |
| 24 |
# ptype: names |
| 25 |
'module': ('async_wrapper', ), |
| 26 |
'cache': ('base', ), |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True) |
| 31 |
class _PluginDocMetadata: |
| 32 |
"""Information about a plugin.""" |
| 33 |
|
| 34 |
name: str |
| 35 |
"""The fully qualified name of the plugin.""" |
| 36 |
path: bytes | None = None |
| 37 |
"""The path to the plugin file, or None if not available.""" |
| 38 |
plugin_obj: object | None = None |
| 39 |
"""The loaded plugin object, or None if not loaded.""" |
| 40 |
jinja_builtin_short_description: str | None = None |
| 41 |
"""The short description of the plugin if it is a Jinja builtin, otherwise None.""" |
| 42 |
|
| 43 |
|
| 44 |
def get_composite_name(collection, name, path, depth): |
| 45 |
resolved_collection = collection |
| 46 |
if '.' not in name: |
| 47 |
resource_name = name |
| 48 |
else: |
| 49 |
if collection == 'ansible.legacy' and name.startswith('ansible.builtin.'): |
| 50 |
resolved_collection = 'ansible.builtin' |
| 51 |
resource_name = '.'.join(name.split(f"{resolved_collection}.")[1:]) |
| 52 |
|
| 53 |
# create FQCN |
| 54 |
composite = [resolved_collection] |
| 55 |
if depth: |
| 56 |
composite.extend(path.split(os.path.sep)[depth * -1:]) |
| 57 |
composite.append(to_native(resource_name)) |
| 58 |
return '.'.join(composite) |
| 59 |
|
| 60 |
|
| 61 |
def _list_plugins_from_paths(ptype, dirs, collection, depth=0, docs=False): |
| 62 |
# TODO: update to use importlib.resources |
| 63 |
|
| 64 |
plugins = {} |
| 65 |
|
| 66 |
for path in dirs: |
| 67 |
display.debug("Searching '{0}'s '{1}' for {2} plugins".format(collection, path, ptype)) |
| 68 |
b_path = to_bytes(path) |
| 69 |
|
| 70 |
if os.path.basename(b_path).startswith((b'.', b'__')): |
| 71 |
# skip hidden/special dirs |
| 72 |
continue |
| 73 |
|
| 74 |
if os.path.exists(b_path): |
| 75 |
if os.path.isdir(b_path): |
| 76 |
bkey = ptype.lower() |
| 77 |
for plugin_file in os.listdir(b_path): |
| 78 |
|
| 79 |
if plugin_file.startswith((b'.', b'__')): |
| 80 |
# hidden or python internal file/dir |
| 81 |
continue |
| 82 |
|
| 83 |
display.debug("Found possible plugin: '{0}'".format(plugin_file)) |
| 84 |
b_plugin, b_ext = os.path.splitext(plugin_file) |
| 85 |
plugin = to_native(b_plugin) |
| 86 |
full_path = os.path.join(b_path, plugin_file) |
| 87 |
|
| 88 |
if os.path.isdir(full_path): |
| 89 |
# its a dir, recurse |
| 90 |
if collection in C.SYNTHETIC_COLLECTIONS: |
| 91 |
if not os.path.exists(os.path.join(full_path, b'__init__.py')): |
| 92 |
# dont recurse for synthetic unless init.py present |
| 93 |
continue |
| 94 |
|
| 95 |
# actually recurse dirs |
| 96 |
plugins.update(_list_plugins_from_paths(ptype, [to_native(full_path)], collection, depth=depth + 1, docs=docs)) |
| 97 |
else: |
| 98 |
if any([ |
| 99 |
plugin in C.IGNORE_FILES, # general files to ignore |
| 100 |
to_native(b_ext) in C.REJECT_EXTS, # general extensions to ignore |
| 101 |
b_ext in (b'.yml', b'.yaml', b'.json'), # ignore docs files |
| 102 |
plugin in IGNORE.get(bkey, ()), # plugin in reject list |
| 103 |
os.path.islink(full_path), # skip aliases, author should document in 'aliases' field |
| 104 |
not docs and b_ext in (b''), # ignore no ext when looking for docs files |
| 105 |
]): |
| 106 |
continue |
| 107 |
|
| 108 |
resource_dir = to_native(os.path.dirname(full_path)) |
| 109 |
resource_name = get_composite_name(collection, plugin, resource_dir, depth) |
| 110 |
|
| 111 |
if ptype in ('test', 'filter'): |
| 112 |
# NOTE: pass the composite resource to ensure any relative |
| 113 |
# imports it contains are interpreted in the correct context |
| 114 |
if collection: |
| 115 |
resource_name = '.'.join(resource_name.split('.')[2:]) |
| 116 |
try: |
| 117 |
file_plugins = _list_j2_plugins_from_file(collection, full_path, ptype, resource_name) |
| 118 |
except KeyError as e: |
| 119 |
display.warning('Skipping file %s: %s' % (full_path, to_native(e))) |
| 120 |
continue |
| 121 |
|
| 122 |
for plugin in file_plugins: |
| 123 |
plugin_name = get_composite_name(collection, plugin.ansible_name, resource_dir, depth) |
| 124 |
plugins[plugin_name] = full_path |
| 125 |
else: |
| 126 |
plugin_name = resource_name |
| 127 |
plugins[plugin_name] = full_path |
| 128 |
else: |
| 129 |
display.debug("Skip listing plugins in '{0}' as it is not a directory".format(path)) |
| 130 |
else: |
| 131 |
display.debug("Skip listing plugins in '{0}' as it does not exist".format(path)) |
| 132 |
|
| 133 |
return plugins |
| 134 |
|
| 135 |
|
| 136 |
def _list_j2_plugins_from_file(collection, plugin_path, ptype, plugin_name): |
| 137 |
|
| 138 |
ploader = getattr(loader, '{0}_loader'.format(ptype)) |
| 139 |
file_plugins = ploader.get_contained_plugins(collection, plugin_path, plugin_name) |
| 140 |
return file_plugins |
| 141 |
|
| 142 |
|
| 143 |
def list_collection_plugins(ptype: str, collections: dict[str, bytes], search_paths: list[str] | None = None) -> dict[str, tuple[bytes, object | None]]: |
| 144 |
# Kept for backwards compatibility. |
| 145 |
return { |
| 146 |
name: (info.path, info.plugin_obj) |
| 147 |
for name, info in _list_collection_plugins_with_info(ptype, collections).items() |
| 148 |
} |
| 149 |
|
| 150 |
|
| 151 |
def _list_collection_plugins_with_info( |
| 152 |
ptype: str, |
| 153 |
collections: dict[str, bytes], |
| 154 |
) -> dict[str, _PluginDocMetadata]: |
| 155 |
# TODO: update to use importlib.resources |
| 156 |
|
| 157 |
try: |
| 158 |
ploader = getattr(loader, '{0}_loader'.format(ptype)) |
| 159 |
except AttributeError: |
| 160 |
raise AnsibleError(f"Cannot list plugins, incorrect plugin type {ptype!r} supplied.") from None |
| 161 |
|
| 162 |
builtin_jinja_plugins = {} |
| 163 |
plugin_paths = {} |
| 164 |
|
| 165 |
# get plugins for each collection |
| 166 |
for collection, path in collections.items(): |
| 167 |
if collection == 'ansible.builtin': |
| 168 |
# dirs from ansible install, but not configured paths |
| 169 |
dirs = [d.path for d in ploader._get_paths_with_context() if d.internal] |
| 170 |
|
| 171 |
if ptype in ('filter', 'test'): |
| 172 |
builtin_jinja_plugins = get_jinja_builtin_plugin_descriptions(ptype) |
| 173 |
|
| 174 |
elif collection == 'ansible.legacy': |
| 175 |
# configured paths + search paths (should include basedirs/-M) |
| 176 |
dirs = [d.path for d in ploader._get_paths_with_context() if not d.internal] |
| 177 |
if context.CLIARGS.get('module_path', None): |
| 178 |
dirs.extend(context.CLIARGS['module_path']) |
| 179 |
else: |
| 180 |
# search path in this case is for locating collection itselfA |
| 181 |
b_ptype = to_bytes(C.COLLECTION_PTYPE_COMPAT.get(ptype, ptype)) |
| 182 |
dirs = [to_native(os.path.join(path, b'plugins', b_ptype))] |
| 183 |
# acr = AnsibleCollectionRef.try_parse_fqcr(collection, ptype) |
| 184 |
# if acr: |
| 185 |
# dirs = acr.subdirs |
| 186 |
# else: |
| 187 |
|
| 188 |
# raise Exception('bad acr for %s, %s' % (collection, ptype)) |
| 189 |
|
| 190 |
plugin_paths.update(_list_plugins_from_paths(ptype, dirs, collection, docs=True)) |
| 191 |
|
| 192 |
plugins = {} |
| 193 |
if ptype in ('module',): |
| 194 |
# no 'invalid' tests for modules |
| 195 |
for plugin, plugin_path in plugin_paths.items(): |
| 196 |
plugins[plugin] = _PluginDocMetadata(name=plugin, path=plugin_path) |
| 197 |
else: |
| 198 |
# detect invalid plugin candidates AND add loaded object to return data |
| 199 |
for plugin, plugin_path in plugin_paths.items(): |
| 200 |
pobj = None |
| 201 |
try: |
| 202 |
pobj = ploader.get(plugin, class_only=True) |
| 203 |
except Exception as e: |
| 204 |
display.vvv("The '{0}' {1} plugin could not be loaded from '{2}': {3}".format(plugin, ptype, plugin_path, to_native(e))) |
| 205 |
|
| 206 |
plugins[plugin] = _PluginDocMetadata( |
| 207 |
name=plugin, |
| 208 |
path=plugin_path, |
| 209 |
plugin_obj=pobj, |
| 210 |
jinja_builtin_short_description=builtin_jinja_plugins.get(plugin), |
| 211 |
) |
| 212 |
|
| 213 |
# Add in any builtin Jinja2 plugins that have not been shadowed in Ansible. |
| 214 |
plugins.update( |
| 215 |
(plugin_name, _PluginDocMetadata(name=plugin_name, jinja_builtin_short_description=plugin_description)) |
| 216 |
for plugin_name, plugin_description in builtin_jinja_plugins.items() if plugin_name not in plugins |
| 217 |
) |
| 218 |
|
| 219 |
return plugins |
| 220 |
|
| 221 |
|
| 222 |
def list_plugins(ptype: str, collections: list[str] | None = None, search_paths: list[str] | None = None) -> dict[str, tuple[bytes, object | None]]: |
| 223 |
# Kept for backwards compatibility. |
| 224 |
return { |
| 225 |
name: (info.path, info.plugin_obj) |
| 226 |
for name, info in _list_plugins_with_info(ptype, collections, search_paths).items() |
| 227 |
} |
| 228 |
|
| 229 |
|
| 230 |
def _list_plugins_with_info( |
| 231 |
ptype: str, |
| 232 |
collections: list[str] = None, |
| 233 |
search_paths: list[str] | None = None, |
| 234 |
) -> dict[str, _PluginDocMetadata]: |
| 235 |
if isinstance(collections, str): |
| 236 |
collections = [collections] |
| 237 |
|
| 238 |
# {plugin_name: (filepath, class), ...} |
| 239 |
plugins = {} |
| 240 |
plugin_collections = {} |
| 241 |
if collections is None: |
| 242 |
# list all collections, add synthetic ones |
| 243 |
plugin_collections['ansible.builtin'] = b'' |
| 244 |
plugin_collections['ansible.legacy'] = b'' |
| 245 |
plugin_collections.update(list_collections(search_paths=search_paths, dedupe=True)) |
| 246 |
else: |
| 247 |
for collection in collections: |
| 248 |
if collection == 'ansible.legacy': |
| 249 |
# add builtin, since legacy also resolves to these |
| 250 |
plugin_collections[collection] = b'' |
| 251 |
plugin_collections['ansible.builtin'] = b'' |
| 252 |
else: |
| 253 |
try: |
| 254 |
plugin_collections[collection] = to_bytes(_get_collection_path(collection)) |
| 255 |
except ValueError as ex: |
| 256 |
raise AnsibleError(f"Cannot use supplied collection {collection!r}.") from ex |
| 257 |
|
| 258 |
if plugin_collections: |
| 259 |
plugins.update(_list_collection_plugins_with_info(ptype, plugin_collections)) |
| 260 |
|
| 261 |
return plugins |
| 262 |
|
| 263 |
|
| 264 |
# wrappers |
| 265 |
def list_plugin_names(ptype, collection=None): |
| 266 |
return [plugin.ansible_name for plugin in list_plugins(ptype, collection)] |
| 267 |
|
| 268 |
|
| 269 |
def list_plugin_files(ptype, collection=None): |
| 270 |
plugins = list_plugins(ptype, collection) |
| 271 |
return [plugins[k][0] for k in plugins.keys()] |
| 272 |
|
| 273 |
|
| 274 |
def list_plugin_classes(ptype, collection=None): |
| 275 |
plugins = list_plugins(ptype, collection) |
| 276 |
return [plugins[k][1] for k in plugins.keys()] |