Skip to content
1 change: 1 addition & 0 deletions changelog/58938.added
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Salt's versions report `salt --versions-report` now includes all installed salt extensions into its versions report.
1 change: 1 addition & 0 deletions changelog/58939.added
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Support loading entrypoints by passing a module instead of a function.
147 changes: 108 additions & 39 deletions salt/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import contextvars
import copy
import functools
import importlib
import importlib.machinery # pylint: disable=no-name-in-module,import-error
import importlib.util # pylint: disable=no-name-in-module,import-error
import inspect
Expand All @@ -20,6 +21,7 @@
import traceback
import types
from collections.abc import MutableMapping
from contextlib import contextmanager
from zipimport import zipimporter

import salt.config
Expand All @@ -39,18 +41,10 @@
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import LoaderError
from salt.ext import six
from salt.ext.six.moves import reload_module
from salt.template import check_render_pipe_str
from salt.utils import entrypoints
from salt.utils.decorators import Depends

try:
import pkg_resources

HAS_PKG_RESOURCES = True
except ImportError:
HAS_PKG_RESOURCES = False

log = logging.getLogger(__name__)

SALT_BASE_PATH = os.path.abspath(salt.syspaths.INSTALL_DIR)
Expand Down Expand Up @@ -120,18 +114,6 @@ def static_loader(
return ret


def _format_entrypoint_target(ep):
"""
Makes a string describing the target of an EntryPoint object.

Base strongly on EntryPoint.__str__().
"""
s = ep.module_name
if ep.attrs:
s += ":" + ".".join(ep.attrs)
return s


def _module_dirs(
opts,
ext_type,
Expand All @@ -152,23 +134,93 @@ def _module_dirs(
ext_type_dirs = "{}_dirs".format(tag)
if ext_type_dirs in opts:
ext_type_types.extend(opts[ext_type_dirs])
if HAS_PKG_RESOURCES and ext_type_dirs:
for entry_point in pkg_resources.iter_entry_points(
"salt.loader", ext_type_dirs
):
try:
if ext_type_dirs:
for entry_point in entrypoints.iter_entry_points("salt.loader"):
with catch_entry_points_exception(entry_point) as ctx:
loaded_entry_point = entry_point.load()
for path in loaded_entry_point():
if ctx.exception_caught:
continue

# Old way of defining loader entry points
Comment thread
s0undt3ch marked this conversation as resolved.
Resolved
# [options.entry_points]
# salt.loader=
# runner_dirs = thirpartypackage.loader:func_to_get_list_of_dirs
# module_dirs = thirpartypackage.loader:func_to_get_list_of_dirs
#
#
# New way of defining entrypoints
# [options.entry_points]
# salt.loader=
# <this-name-does-not-matter> = thirpartypackage
# <this-name-does-not-matter> = thirpartypackage:callable
#
# We try and see if the thirpartypackage has a `ext_type` sub module, and if so,
# we append it to loaded_entry_point_paths.
# If the entry-point is in the form of `thirpartypackage:callable`, the return of that
# callable must be a dictionary where the keys are the `ext_type`'s and the values must be
# lists of paths.
Comment thread
s0undt3ch marked this conversation as resolved.
Resolved

# We could feed the paths we load directly to `ext_type_types`, but we would not
# check for duplicates
loaded_entry_point_paths = set()

if isinstance(loaded_entry_point, types.FunctionType):
# If the entry point object is a function, we have two scenarios
# 1: It returns a list; This is an old style entry entry_point
# 2: It returns a dictionary; This is a new style entry point
with catch_entry_points_exception(entry_point) as ctx:
loaded_entry_point_value = loaded_entry_point()
if ctx.exception_caught:
continue

if isinstance(loaded_entry_point_value, list):
# This is old style entry-point, and, as such, the entry point name MUST
# match the value of `ext_type_dirs
if entry_point.name != ext_type_dirs:
continue
for path in loaded_entry_point_value:
loaded_entry_point_paths.add(path)
elif isinstance(loaded_entry_point_value, dict):
# This is new style entry-point and it returns a dictionary.
# It MUST contain `ext_type` in it's keys to be considered
if ext_type not in loaded_entry_point_value:
continue
with catch_entry_points_exception(entry_point) as ctx:
if isinstance(loaded_entry_point_value[ext_type], str):
# No strings please!
raise ValueError(
"The callable must return an iterable of strings. "
"A single string is not supported."
)
for path in loaded_entry_point_value[ext_type]:
loaded_entry_point_paths.add(path)
elif isinstance(loaded_entry_point, types.ModuleType):
# This is a new style entry points definition which just points us to a package
#
# We try and see if the thirpartypackage has a `ext_type` sub module, and if so,
# we append it to loaded_entry_point_paths.
for loaded_entry_point_path in loaded_entry_point.__path__:
with catch_entry_points_exception(entry_point) as ctx:
entry_point_ext_type_package_path = os.path.join(
loaded_entry_point_path, ext_type
)
if not os.path.exists(entry_point_ext_type_package_path):
continue
if ctx.exception_caught:
continue
loaded_entry_point_paths.add(entry_point_ext_type_package_path)
else:
with catch_entry_points_exception(entry_point):
raise ValueError(
"Don't know how to load a salt extension from {}".format(
loaded_entry_point
)
)

# Finally, we check all paths that we collected to see if they exist
for path in loaded_entry_point_paths:
if os.path.exists(path):
ext_type_types.append(path)
except Exception as exc: # pylint: disable=broad-except
log.error(
"Error getting module directories from %s: %s",
_format_entrypoint_target(entry_point),
exc,
)
log.debug(
"Full backtrace for module directories error", exc_info=True
)

cli_module_dirs = []
# The dirs can be any module dir, or a in-tree _{ext_type} dir
Expand Down Expand Up @@ -1524,7 +1576,7 @@ def _replace_pre_ext(obj):
self.file_mapping[f_noext][0],
)

if six.PY3 and ext == ".pyc" and curr_ext == ".pyc":
if ext == ".pyc" and curr_ext == ".pyc":
# Check the optimization level
if opt_index >= curr_opt_index:
# Module name match, but a higher-priority
Expand All @@ -1537,7 +1589,7 @@ def _replace_pre_ext(obj):
# exists, so skip this.
continue

if six.PY3 and not dirname and ext == ".pyc":
if not dirname and ext == ".pyc":
# On Python 3, we should only load .pyc files from the
# __pycache__ subdirectory (i.e. when dirname is not an
# empty string).
Expand Down Expand Up @@ -1625,7 +1677,7 @@ def _reload_submodules(self, mod):
for submodule in submodules:
# it is a submodule if the name is in a namespace under mod
if submodule.__name__.startswith(mod.__name__ + "."):
reload_module(submodule)
importlib.reload(submodule)
self._reload_submodules(submodule)

def __populate_sys_path(self):
Expand Down Expand Up @@ -2260,3 +2312,20 @@ def wrapper(*args, **kwargs):
return wrapper

return inner_decorator


@contextmanager
def catch_entry_points_exception(entry_point):
context = types.SimpleNamespace(exception_caught=False)
try:
yield context
except Exception as exc: # pylint: disable=broad-except
context.exception_caught = True
entry_point_details = entrypoints.name_and_version_from_entry_point(entry_point)
log.error(
"Error processing Salt Extension %s(version: %s): %s",
entry_point_details.name,
entry_point_details.version,
exc,
exc_info_on_loglevel=logging.DEBUG,
)
Comment thread
s0undt3ch marked this conversation as resolved.
Resolved
81 changes: 81 additions & 0 deletions salt/utils/entrypoints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import logging
import sys
import types

USE_IMPORTLIB_METADATA_STDLIB = USE_IMPORTLIB_METADATA = USE_PKG_RESOURCES = False

if sys.version_info >= (3, 10):
# Python 3.10 will include a fix in importlib.metadata which allows us to
# get the distribution of a loaded entry-point
import importlib.metadata # pylint: disable=no-member,no-name-in-module

USE_IMPORTLIB_METADATA_STDLIB = True
else:
if sys.version_info >= (3, 6):
# importlib_metadata available for python version lower than 3.6 do not
# include the functionality we need.
try:
import importlib_metadata

importlib_metadata_version = [
int(part)
for part in importlib_metadata.version("importlib_metadata").split(".")
if part.isdigit()
]
if tuple(importlib_metadata_version) >= (3, 3, 0):
# Version 3.3.0 of importlib_metadata includes a fix which allows us to
# get the distribution of a loaded entry-point
USE_IMPORTLIB_METADATA = True
except ImportError:
# We don't have importlib_metadata but USE_IMPORTLIB_METADATA is set to false by default
pass

if not USE_IMPORTLIB_METADATA_STDLIB and not USE_IMPORTLIB_METADATA:
# Try to use pkg_resources
try:
import pkg_resources

USE_PKG_RESOURCES = True
except ImportError:
# We don't have pkg_resources but USE_PKG_RESOURCES is set to false by default
pass


log = logging.getLogger(__name__)


def iter_entry_points(group, name=None):
entry_points_listing = []
if USE_IMPORTLIB_METADATA_STDLIB:
log.debug("Using importlib.metadata to load entry points")
entry_points = importlib.metadata.entry_points()
elif USE_IMPORTLIB_METADATA:
log.debug("Using importlib_metadata to load entry points")
entry_points = importlib_metadata.entry_points()
elif USE_PKG_RESOURCES:
log.debug("Using pkg_resources to load entry points")
entry_points_listing = list(pkg_resources.iter_entry_points(group, name=name))
else:
return entry_points_listing

if USE_IMPORTLIB_METADATA_STDLIB or USE_IMPORTLIB_METADATA:
for entry_point_group, entry_points_list in entry_points.items():
if entry_point_group != group:
continue
for entry_point in entry_points_list:
if name is not None and entry_point.name != name:
continue
entry_points_listing.append(entry_point)

return entry_points_listing


def name_and_version_from_entry_point(entry_point):
if USE_IMPORTLIB_METADATA_STDLIB or USE_IMPORTLIB_METADATA:
return types.SimpleNamespace(
name=entry_point.dist.metadata["name"], version=entry_point.dist.version,
)
elif USE_PKG_RESOURCES:
return types.SimpleNamespace(
name=entry_point.dist.key, version=entry_point.dist.version
)
48 changes: 42 additions & 6 deletions salt/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import re
import sys

import salt.utils.entrypoints

MAX_SIZE = sys.maxsize
VERSION_LIMIT = MAX_SIZE - 200

Expand Down Expand Up @@ -757,35 +759,69 @@ def system_version():
continue


def versions_information(include_salt_cloud=False):
def extensions_information():
"""
Gather infomation about any installed salt extensions
"""
extensions = {}
for entry_point in salt.utils.entrypoints.iter_entry_points("salt.loader"):
dist_nv = salt.utils.entrypoints.name_and_version_from_entry_point(entry_point)
if not dist_nv:
continue
if dist_nv.name in extensions:
continue
extensions[dist_nv.name] = dist_nv.version
return extensions


def versions_information(include_salt_cloud=False, include_extensions=True):
"""
Report the versions of dependent software.
"""
salt_info = list(salt_information())
lib_info = list(dependency_information(include_salt_cloud))
sys_info = list(system_information())

return {
info = {
"Salt Version": dict(salt_info),
"Dependency Versions": dict(lib_info),
"System Versions": dict(sys_info),
}
if include_extensions:
extensions_info = extensions_information()
if extensions_info:
info["Salt Extensions"] = extensions_info
return info


def versions_report(include_salt_cloud=False):
def versions_report(include_salt_cloud=False, include_extensions=True):
"""
Yield each version properly formatted for console output.
"""
ver_info = versions_information(include_salt_cloud)
ver_info = versions_information(
include_salt_cloud=include_salt_cloud, include_extensions=include_extensions
)
not_installed = "Not Installed"
ns_pad = len(not_installed)
lib_pad = max(len(name) for name in ver_info["Dependency Versions"])
sys_pad = max(len(name) for name in ver_info["System Versions"])
padding = max(lib_pad, sys_pad, ns_pad) + 1
if include_extensions and "Salt Extensions" in ver_info:
ext_pad = max(len(name) for name in ver_info["Salt Extensions"])
else:
ext_pad = 1
padding = max(lib_pad, sys_pad, ns_pad, ext_pad) + 1

fmt = "{0:>{pad}}: {1}"
info = []
for ver_type in ("Salt Version", "Dependency Versions", "System Versions"):
for ver_type in (
"Salt Version",
"Dependency Versions",
"Salt Extensions",
"System Versions",
):
if ver_type == "Salt Extensions" and ver_type not in ver_info:
# No salt Extensions to report
continue
info.append("{}:".format(ver_type))
# List dependencies in alphabetical, case insensitive order
for name in sorted(ver_info[ver_type], key=lambda x: x.lower()):
Expand Down
Loading