diff --git a/docs/api/facts.md b/docs/api/facts.md index bce2da807..a260ed769 100644 --- a/docs/api/facts.md +++ b/docs/api/facts.md @@ -1,26 +1,27 @@ # Writing Facts -[Facts](../facts) are written as Python classes. They provide a ``command`` (as either a string or method) +[Facts](../facts) can be written as Python classes. They provide a ``command`` (as either a string or method) and a ``process`` function. The command is executed on the target host and the output passed (as a ``list`` of lines) to the ``process`` handler to generate fact data. Facts can output anything, normally a ``list`` or ``dict``. +For simpler facts implemented in Python, use the ``@fact()`` decorator instead. Fact classes may provide a ``default`` function that takes no arguments (except ``self``). The return value of this function is used if an error occurs during fact collection. -## `FactBase` vs `ShortFactBase` +## `ShellFact` vs `ShortcutFact` There are two base classes for facts and they solve different problems: -- **`FactBase`** — defines a *new* fact that runs a shell command on the host and parses the output. Use this whenever you need information that isn't already available from an existing fact. -- **`ShortFactBase`** — defines a *derived* view over an existing fact. It does not define a command of its own; instead it points at another fact via a `fact` class attribute and post-processes that fact's result. Use this when you want a simpler or different shape of an existing fact (e.g. just one field from a dict). Fact results are not cached, so requesting a `ShortFactBase` runs the underlying fact's command, costing the same as requesting that fact directly. +- **`ShellFact`** — defines a *new* fact that runs a shell command on the host and parses the output. Use this whenever you need information that isn't already available from an existing fact. +- **`ShortcutFact`** — defines a *derived* view over an existing fact. It does not define a command of its own; instead it points at another fact via a `fact` class attribute and post-processes that fact's result. Use this when you want a simpler or different shape of an existing fact (e.g. just one field from a dict). Fact results are not cached, so requesting a `ShortcutFact` runs the underlying fact's command, costing the same as requesting that fact directly. -For example, `LinuxName` is a `ShortFactBase` that extracts the `name` field from the larger `LinuxDistribution` fact: +For example, `LinuxName` is a `ShortcutFact` that extracts the `name` field from the larger `LinuxDistribution` fact: ```py from typing_extensions import override -from pyinfra.api import ShortFactBase +from pyinfra.api import ShortcutFact -class LinuxName(ShortFactBase[str]): +class LinuxName(ShortcutFact[str]): """ Returns the name of the Linux distribution. Shortcut for ``host.get_fact(LinuxDistribution)['name']``. @@ -33,7 +34,35 @@ class LinuxName(ShortFactBase[str]): return data["name"] ``` -The rest of this page covers `FactBase`. +The rest of this page covers `ShellFact` and function facts. + +## Writing function facts with `@fact()` + +Use ``@fact()`` to turn a Python function into a fact when it can get its data from other facts +or compute it directly, without defining a remote shell command or output parser. The decorated +function is called when the fact is requested, and its return value is the fact data: + +```py +from pyinfra import host +from pyinfra.api import fact +from pyinfra.facts.server import LinuxDistribution + +@fact() +def linux_name(host): + return host.get_fact(LinuxDistribution)["name"] + +name = host.get_fact(linux_name) +``` + +Parameters named ``host`` and ``state`` are supplied automatically by pyinfra; do not pass either +as an argument to ``host.get_fact``. Other function parameters are fact arguments and are passed +as usual, either positionally or by keyword, for example ``host.get_fact(my_fact, path="/etc")``. +The function runs as Python code on the controller, not as a command on the target host. Facts are +not cached, so each call to ``host.get_fact`` calls the function again. + +You can provide ``default_value`` to set the value returned by the fact's ``default()`` method; +if omitted, it defaults to ``None``. It is not a fallback for an empty return value and does not +catch exceptions raised by the function. ## Guarding against missing binaries: `requires_command` @@ -42,9 +71,9 @@ the fact command is run. When the binary is absent pyinfra emits a unique sentin executing the command, then raises `MissingCommandError` internally: ```py -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class ZfsPools(FactBase): +class ZfsPools(ShellFact): def requires_command(self) -> str: return "zpool" @@ -68,9 +97,9 @@ Some facts require more than just a binary — they need a specific runtime stat module loaded, a service running). Override `check_preconditions` to express these checks: ```py -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class ZfsDatasets(FactBase): +class ZfsDatasets(ShellFact): def requires_command(self) -> str: return "zfs" @@ -124,9 +153,9 @@ host.get_fact(Which, command='htop') This fact returns a boolean indicating whether swap is enabled. For this fact the ``command`` is declared as a class attribute. ```py -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class SwapEnabled(FactBase): +class SwapEnabled(ShellFact): ''' Returns a boolean indicating whether swap is enabled. ''' @@ -148,9 +177,9 @@ is_swap_enabled = host.get_fact(SwapEnabled) This fact returns a list of files found in a given directory. For this fact the ``command`` is declared as a class method, indicating the fact takes arguments. ```py -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class FindFiles(FactBase): +class FindFiles(ShellFact): ''' Returns a list of files from a start point, recursively using find. ''' @@ -174,9 +203,9 @@ list_of_files = host.get_fact(FindFiles, path='/somewhere') This fact returns the raw output of any command. For this fact the ``command`` is declared as a class method, indicating the fact takes arguments. ```py -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class RawCommandOutput(FactBase): +class RawCommandOutput(ShellFact): ''' Returns the raw output of a command. ''' diff --git a/scripts/generate_facts_docs.py b/scripts/generate_facts_docs.py index 1439d380d..ae933b2bf 100755 --- a/scripts/generate_facts_docs.py +++ b/scripts/generate_facts_docs.py @@ -7,7 +7,7 @@ from pathlib import Path from types import FunctionType, MethodType -from pyinfra.api.facts import FactBase, ShortFactBase +from pyinfra.api.facts import FactCore from pyinfra.api.metadata import ALLOWED_TAGS, parse_plugins sys.path.append(path.dirname(path.realpath(__file__))) @@ -125,10 +125,10 @@ def build_facts_docs(): for key, value in getmembers(m) if ( isclass(value) - and (issubclass(value, FactBase) or issubclass(value, ShortFactBase)) + and issubclass(value, FactCore) and value.__module__.startswith(m.__name__) - and value is not FactBase - and not value.__name__.endswith("Base") # hacky! + # Hack to check `abstract` is coming from `value` class itself, not from a parent + and not ("abstract" in value.__dict__ and value.abstract) ) ] diff --git a/scripts/generate_llms_txt.py b/scripts/generate_llms_txt.py index a64fb8e97..2449cf297 100644 --- a/scripts/generate_llms_txt.py +++ b/scripts/generate_llms_txt.py @@ -19,7 +19,7 @@ from pyinfra.api import metadata from pyinfra.api.connectors import get_all_connectors -from pyinfra.api.facts import FactBase, ShortFactBase +from pyinfra.api.facts import FactCore sys.path.append(path.dirname(path.realpath(__file__))) from docs_utils import including_sub_modules, prepare_docstring, remove_dups # noqa: E402 @@ -224,11 +224,10 @@ def _extract_fact_classes(module: ModuleType) -> list[tuple[str, type]]: for key, value in getmembers(m) if ( isclass(value) - and (issubclass(value, FactBase) or issubclass(value, ShortFactBase)) + and issubclass(value, FactCore) and value.__module__.startswith(m.__name__) - and value is not FactBase - and value is not ShortFactBase - and not value.__name__.endswith("Base") + # Hack to check `abstract` is coming from `value` class itself, not from a parent + and not ("abstract" in value.__dict__ and value.abstract) ) ] return remove_dups(classes) diff --git a/scripts/generate_operations_docs.py b/scripts/generate_operations_docs.py index 853932a54..de35a5769 100755 --- a/scripts/generate_operations_docs.py +++ b/scripts/generate_operations_docs.py @@ -7,7 +7,7 @@ from pathlib import Path from types import FunctionType -from pyinfra.api.facts import FactBase +from pyinfra.api.facts import FactCore from pyinfra.api.metadata import ALLOWED_TAGS, parse_plugins sys.path.append(path.dirname(path.realpath(__file__))) @@ -122,7 +122,7 @@ def build_operations_docs(): (key, value) for m in including_sub_modules(module) for key, value in getmembers(m) - if (isclass(value) and issubclass(value, FactBase)) + if (isclass(value) and issubclass(value, FactCore)) ] unique_facts = remove_dups(operation_facts) diff --git a/src/pyinfra/api/__init__.py b/src/pyinfra/api/__init__.py index fde541dcd..265e87dce 100644 --- a/src/pyinfra/api/__init__.py +++ b/src/pyinfra/api/__init__.py @@ -24,7 +24,7 @@ OperationTypeError, OperationValueError, ) -from .facts import FactBase, ShortFactBase +from .facts import fact, FactBase, FactCore, ShellFact, ShortcutFact, ShortFactBase from .host import Host from .inventory import Inventory from .operation import operation @@ -35,6 +35,7 @@ "Config", "DeployError", "FactBase", + "FactCore", "FactError", "FactNotCollected", "FactPreconditionError", @@ -55,9 +56,12 @@ "OperationValueError", "QuoteString", "RsyncCommand", + "ShellFact", + "ShortcutFact", "ShortFactBase", "State", "StringCommand", "deploy", + "fact", "operation", ] diff --git a/src/pyinfra/api/facts.py b/src/pyinfra/api/facts.py index a661452b3..3ca5005c7 100644 --- a/src/pyinfra/api/facts.py +++ b/src/pyinfra/api/facts.py @@ -12,12 +12,13 @@ import inspect import re +from collections.abc import Callable, Sequence from inspect import getcallargs from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast import gevent from paramiko import SSHException -from typing_extensions import override +from typing_extensions import ParamSpec, override from pyinfra import logger from pyinfra.api.output import format_text @@ -34,7 +35,7 @@ from pyinfra.context import ctx_host, ctx_state from pyinfra.progress import progress_spinner -from .arguments import CONNECTOR_ARGUMENT_KEYS +from .arguments import CONNECTOR_ARGUMENT_KEYS, AllArguments if TYPE_CHECKING: from pyinfra.api import Host, State @@ -53,11 +54,151 @@ T = TypeVar("T", covariant=True) -class FactBase(Generic[T]): +class FactCore(Generic[T]): + """ + This is the base class for all facts, whatever the underlying technique is used to collect it. + It defines the interface that every fact must implement, with basic default implementations + where relevant. + It should really be called FactBase, but this would cause backwards compatibility issues as this + name was used for the ShellFact class in the past. + """ + name: str abstract: bool = True + @staticmethod + def default() -> T: + """ + Set the default attribute to be a type (eg list/dict). + """ + return cast(T, None) + + @classmethod + def get( + cls, + state: State, + host: Host, + args: Sequence | None = None, + kwargs: dict | None = None, + apply_failed_hosts: bool = True, + ) -> T: + raise NotImplementedError + + @override + def __init_subclass__(cls) -> None: + super().__init_subclass__() + module_name = cls.__module__.replace("pyinfra.facts.", "") + cls.name = f"{module_name}.{cls.__name__}" + + +P = ParamSpec("P") + + +class DefaultMarker: + pass + + +_DEFAULT_MARKER = DefaultMarker() + + +def fact( + default_value: T | DefaultMarker = _DEFAULT_MARKER, +) -> Callable[[Callable[P, T]], type[FactCore[T]]]: + """ + Decorator that takes a simple module function and turn it into the internal + fact representation that consists of an object implementing FactCore interface. + """ + + def decorator(fact_func: Callable[P, T]) -> type[FactCore[T]]: + class DecoratedFact(FactCore[T]): + abstract = False + + @override + @staticmethod + def default() -> T: + if isinstance(default_value, DefaultMarker): + return FactCore[T].default() + else: + return default_value + + @override + @classmethod + def get( + cls, + state: State, + host: Host, + args: Sequence | None = None, + kwargs: dict | None = None, + apply_failed_hosts: bool = True, + ) -> T: + sig = inspect.signature(fact_func) + parameters = sig.parameters + + if args is None: + call_args = [] + else: + call_args = list(args) + + if kwargs is None: + call_kwargs = {} + else: + call_kwargs = kwargs.copy() + + if "state" in call_kwargs: + raise TypeError("state cannot be provided as a keyword argument") + if "host" in call_kwargs: + raise TypeError("host cannot be provided as a keyword argument") + + positional_parameters = [ + name + for name, candidate in parameters.items() + if candidate.kind + in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ) + ] + + to_insert: list[tuple[int, str, object]] = [] + for name, obj in [ + ("state", state), + ("host", host), + ]: + if name in parameters: + if name in positional_parameters: + position = positional_parameters.index(name) + to_insert.append((position, name, obj)) + else: + call_kwargs[name] = obj + + no_skip = True + for index, name, obj in sorted(to_insert): + if no_skip and index <= len(call_args): + call_args.insert(index, obj) + else: + no_skip = False + call_kwargs[name] = obj + + bound_arguments = sig.bind(*call_args, **call_kwargs) + return fact_func(*bound_arguments.args, **bound_arguments.kwargs) + + module_name = fact_func.__module__.replace("pyinfra.facts.", "") + DecoratedFact.name = f"{module_name}.{fact_func.__name__}" + DecoratedFact.__name__ = fact_func.__name__ + DecoratedFact.__module__ = module_name + DecoratedFact.__doc__ = fact_func.__doc__ + + return DecoratedFact + + return decorator + + +class ShellFact(FactCore[T]): + """ + Base class for all shell-commands-based facts. + """ + shell_executable: str | None = None def command(self, *args, **kwargs) -> str | StringCommand: @@ -98,8 +239,6 @@ def check_preconditions(self, state: State, host: Host, *args, **kwargs) -> str @override def __init_subclass__(cls) -> None: super().__init_subclass__() - module_name = cls.__module__.replace("pyinfra.facts.", "") - cls.name = f"{module_name}.{cls.__name__}" # Check that fact's `command` method does not inadvertently take a global # argument, most commonly `name`. @@ -112,14 +251,6 @@ def __init_subclass__(cls) -> None: names = ", ".join(command_global_args) raise TypeError(f"{cls.name}'s arguments {names} are reserved for global arguments") - @staticmethod - def default() -> T: - """ - Set the default attribute to be a type (eg list/dict). - """ - - return cast(T, None) - def process(self, output: list[str]) -> T: # NOTE: TypeVar does not support a default, so we have to cast this str -> T return cast(T, "\n".join(output)) @@ -127,24 +258,275 @@ def process(self, output: list[str]) -> T: def process_pipeline(self, args, output): return {arg: self.process([output[i]]) for i, arg in enumerate(args)} + def execute( + self, + fact_kwargs: dict[Any, Any] | dict[str, Any], + global_kwargs: AllArguments, + host: Host, + name: str, + state: State, + ) -> tuple[CommandOutput, bool]: + command = _make_command(self.command, fact_kwargs) + requires_command = _make_command(self.requires_command, fact_kwargs) + if requires_command: + command = StringCommand( + # If binary exists → run the fact command; otherwise emit the sentinel so + # pyinfra can distinguish "binary absent" from "no output". + "if", + "command", + "-v", + requires_command, + ">/dev/null", + "2>&1;", + "then", + "(", + command, + ");", + "else", + "echo", + f"'{_MISSING_COMMAND_MARKER}';", + "fi", + ) + + status = False + output = CommandOutput([]) -class ShortFactBase(Generic[T]): - name: str - fact: type[FactBase] + executor_kwargs = { + key: value for key, value in global_kwargs.items() if key in CONNECTOR_ARGUMENT_KEYS + } + + if executor_kwargs.get("_su_user"): + command = StringCommand("printf", QuoteString(_SU_OUTPUT_MARKER), "&&", command) + + try: + status, output = host.run_shell_command( + command, + print_output=state.print_fact_output, + print_input=state.print_fact_input, + **executor_kwargs, + ) + except (TimeoutError, OSError, SSHException) as e: + log_host_command_error( + host, + e, + timeout=global_kwargs.get("_timeout"), + ) + + if executor_kwargs.get("_su_user"): + for index, line in enumerate(output.combined_lines): + if _SU_OUTPUT_MARKER in line.line and line.buffer_name == "stdout": + before_lines = [ + line + for line in output.combined_lines[:index] + if line.buffer_name != "stdout" + ] + line.line = line.line.split(_SU_OUTPUT_MARKER, 1)[1] + after_lines = output.combined_lines[index + 1 :].copy() + + output.combined_lines = [ + *before_lines, + line, + *after_lines, + ] + break + + # Detect the "binary absent" sentinel from the if/then/else shell guard. + if status and output.stdout_lines == [_MISSING_COMMAND_MARKER]: + cmd_str = str(requires_command) if requires_command else "" + logger.debug( + "Skipping fact %s on %s: command not found: %s", + name, + host.print_prefix, + cmd_str, + ) + raise MissingCommandError(cmd_str) + + if not status and output.stderr_lines: + # If we have error output and that error is sudo or su stating the user + # does not exist, do not fail but instead return the default fact value. + # This allows for users that don't currently but may be created during + # other operations. + first_line = output.stderr_lines[0] + if executor_kwargs.get("_sudo_user") and re.match(SUDO_REGEX, first_line): + status = True + if executor_kwargs.get("_su_user") and any( + re.match(regex, first_line) for regex in SU_REGEXES + ): + status = True + + return output, status @override - def __init_subclass__(cls) -> None: - super().__init_subclass__() - module_name = cls.__module__.replace("pyinfra.facts.", "") - cls.name = f"{module_name}.{cls.__name__}" + @classmethod + def get( + cls, + state: State, + host: Host, + args: Sequence | None = None, + kwargs: dict | None = None, + apply_failed_hosts: bool = True, + ) -> T: + try: + return cls._get_fact( + state, + host, + args, + kwargs, + apply_failed_hosts, + ) + except MissingCommandError as e: + # During the prepare phase the binary might not yet be installed (a prior + # operation will install it). Silently return the default so change + # detection can proceed normally. + if not state.is_executing: + logger.debug( + "Fact %s skipped on %s during prepare: %s", + cls.__name__, + host.print_prefix, + e, + ) + return cls().default() + # During the execute phase the binary should already be present. If it + # isn't, the deploy is incorrectly ordered (missing an install step?). + # TODO(v4): remove this compat shim and let the exception propagate. + logger.warning( + "Fact %s skipped on %s: command not found: %s (this will raise an exception in v4)", + cls.__name__, + host.print_prefix, + e, + ) + return cls().default() + except FactPreconditionError as e: + # Same phase-aware logic: a precondition not satisfied during prepare + # is normal (e.g. kernel module not yet loaded); during execute it is an + # ordering error in the deploy. + if not state.is_executing: + logger.debug( + "Fact %s skipped on %s during prepare: %s", + cls.__name__, + host.print_prefix, + e, + ) + return cls().default() + raise + + @classmethod + def _get_fact( + cls, + state: State, + host: Host, + args: Sequence | None = None, + kwargs: dict | None = None, + apply_failed_hosts: bool = True, + ) -> T: + fact = cls() + name = fact.name + + fact_kwargs, global_kwargs = _handle_fact_kwargs(state, host, cls, args, kwargs) + + kwargs_str = get_kwargs_str(fact_kwargs) + logger.debug( + "Getting fact: %s (%s)", + name, + kwargs_str, + ) + + if not host.connected: + host.connect( + reason=f"to load fact: {name} ({kwargs_str})", + raise_exceptions=True, + ) + + # Facts can override the shell (winrm powershell vs cmd support) + if fact.shell_executable: + global_kwargs["_shell_executable"] = fact.shell_executable + + # Check preconditions before running this fact's command. The fact's own arguments go + # with it, minus the `self` that `getcallargs` collected alongside them — `_make_command` + # drops it the same way before calling `command`. + precondition_kwargs = {key: value for key, value in fact_kwargs.items() if key != "self"} + if reason := fact.check_preconditions(state, host, **precondition_kwargs): + raise FactPreconditionError(cls, reason) + + output, status = fact.execute( + fact_kwargs, + global_kwargs, + host, + name, + state, + ) + + data = fact.default() + + if status: + if output.stdout_lines: + try: + data = fact.process(output.stdout_lines) + except FactProcessError as e: + log_error_or_warning( + host, + global_kwargs["_ignore_errors"], + description=( + f"could not process fact: {name} {get_kwargs_str(fact_kwargs)}" + ), + exception=e, + ) + + # Check we've not failed + if apply_failed_hosts and not global_kwargs["_ignore_errors"]: + state.fail_hosts({host}) + + if status: + log_message = "{}{}".format( + host.print_prefix, + f"Loaded fact {format_text(name, bold=True)}{f' ({get_kwargs_str(kwargs)})' if kwargs else ''}", + ) + if state.print_fact_info: + logger.info(log_message) + else: + logger.debug(log_message) + else: + if not state.print_fact_output: + print_host_combined_output(host, output) + + log_error_or_warning( + host, + global_kwargs["_ignore_errors"], + description=(f"could not load fact: {name} {get_kwargs_str(fact_kwargs)}"), + ) + + # Check we've not failed + if apply_failed_hosts and not status and not global_kwargs["_ignore_errors"]: + state.fail_hosts({host}) - def process_data(self, data): return data -def get_short_facts(state: State, host: Host, short_fact, **kwargs): - fact_data = get_fact(state, host, short_fact.fact, **kwargs) - return short_fact().process_data(fact_data) +class ShortcutFact(FactCore[T]): + """Base class for short(cut) facts. + + Short facts re-process the data returned by their fact. + For example this can be used to return a specific value from a complex fact. + """ + + name: str + fact: type[FactCore] + + @override + @classmethod + def get( + cls, + state: State, + host: Host, + args: Sequence | None = None, + kwargs: dict | None = None, + apply_failed_hosts: bool = True, + ) -> T: + fact_data = cls.fact.get(state, host, args, kwargs, apply_failed_hosts) + return cls().process_data(fact_data) + + def process_data(self, data): + return data def _make_command(command_attribute, host_args): @@ -178,9 +560,9 @@ def _handle_fact_kwargs(state: State, host: Host, cls, args, kwargs): def get_facts(state, *args, **kwargs): - def get_host_fact(host, *args, **kwargs): + def get_host_fact(host, fact_cls, *args, **kwargs): with ctx_host.use(host): - return get_fact(state, host, *args, **kwargs) + return fact_cls.get(state, host, *args, **kwargs) with ctx_state.use(state): greenlet_to_host = { @@ -199,229 +581,19 @@ def get_host_fact(host, *args, **kwargs): return results +# Backwards compatibility aliases +FactBase = ShellFact +ShortFactBase = ShortcutFact + def get_fact( state: State, host: Host, - cls: type[FactBase], + cls: type[FactCore], args: Any | None = None, kwargs: Any | None = None, - ensure_hosts: Any | None = None, apply_failed_hosts: bool = True, ) -> Any: - if issubclass(cls, ShortFactBase): - return get_short_facts( - state, - host, - cls, - args=args, - kwargs=kwargs, - ensure_hosts=ensure_hosts, - apply_failed_hosts=apply_failed_hosts, - ) - - try: - return _get_fact( - state, - host, - cls, - args, - kwargs, - ensure_hosts, - apply_failed_hosts, - ) - except MissingCommandError as e: - # During the prepare phase the binary might not yet be installed (a prior - # operation will install it). Silently return the default so change - # detection can proceed normally. - if not state.is_executing: - logger.debug( - "Fact %s skipped on %s during prepare: %s", - cls.__name__, - host.print_prefix, - e, - ) - return cls().default() - # During the execute phase the binary should already be present. If it - # isn't, the deploy is incorrectly ordered (missing an install step?). - # TODO(v4): remove this compat shim and let the exception propagate. - logger.warning( - "Fact %s skipped on %s: command not found: %s (this will raise an exception in v4)", - cls.__name__, - host.print_prefix, - e, - ) - return cls().default() - except FactPreconditionError as e: - # Same phase-aware logic: a precondition not satisfied during prepare - # is normal (e.g. kernel module not yet loaded); during execute it is an - # ordering error in the deploy. - if not state.is_executing: - logger.debug( - "Fact %s skipped on %s during prepare: %s", - cls.__name__, - host.print_prefix, - e, - ) - return cls().default() - raise - - -def _get_fact( - state: State, - host: Host, - cls: type[FactBase], - args: list | None = None, - kwargs: dict | None = None, - ensure_hosts: Any | None = None, - apply_failed_hosts: bool = True, -) -> Any: - fact = cls() - name = fact.name - - fact_kwargs, global_kwargs = _handle_fact_kwargs(state, host, cls, args, kwargs) - - kwargs_str = get_kwargs_str(fact_kwargs) - logger.debug( - "Getting fact: %s (%s) (ensure_hosts: %r)", - name, - kwargs_str, - ensure_hosts, - ) - - if not host.connected: - host.connect( - reason=f"to load fact: {name} ({kwargs_str})", - raise_exceptions=True, - ) - - # Facts can override the shell (winrm powershell vs cmd support) - if fact.shell_executable: - global_kwargs["_shell_executable"] = fact.shell_executable - - # Check preconditions before running this fact's command. The fact's own arguments go - # with it, minus the `self` that `getcallargs` collected alongside them — `_make_command` - # drops it the same way before calling `command`. - precondition_kwargs = {key: value for key, value in fact_kwargs.items() if key != "self"} - if reason := fact.check_preconditions(state, host, **precondition_kwargs): - raise FactPreconditionError(cls, reason) - - command = _make_command(fact.command, fact_kwargs) - requires_command = _make_command(fact.requires_command, fact_kwargs) - if requires_command: - command = StringCommand( - # If binary exists → run the fact command; otherwise emit the sentinel so - # pyinfra can distinguish "binary absent" from "no output". - "if", - "command", - "-v", - requires_command, - ">/dev/null", - "2>&1;", - "then", - "(", - command, - ");", - "else", - "echo", - f"'{_MISSING_COMMAND_MARKER}';", - "fi", - ) - - status = False - output = CommandOutput([]) - - executor_kwargs = { - key: value for key, value in global_kwargs.items() if key in CONNECTOR_ARGUMENT_KEYS - } - - if executor_kwargs.get("_su_user"): - command = StringCommand("printf", QuoteString(_SU_OUTPUT_MARKER), "&&", command) - - try: - status, output = host.run_shell_command( - command, - print_output=state.print_fact_output, - print_input=state.print_fact_input, - **executor_kwargs, - ) - except (TimeoutError, OSError, SSHException) as e: - log_host_command_error( - host, - e, - timeout=global_kwargs.get("_timeout"), - ) - - stdout_lines, stderr_lines = output.stdout_lines, output.stderr_lines - if executor_kwargs.get("_su_user"): - for index, line in enumerate(stdout_lines): - if _SU_OUTPUT_MARKER in line: - stdout_lines = stdout_lines[index:].copy() - stdout_lines[0] = line.split(_SU_OUTPUT_MARKER, 1)[1] - break - - # Detect the "binary absent" sentinel from the if/then/else shell guard. - if status and stdout_lines == [_MISSING_COMMAND_MARKER]: - cmd_str = str(requires_command) if requires_command else "" - logger.debug( - "Skipping fact %s on %s: command not found: %s", - name, - host.print_prefix, - cmd_str, - ) - raise MissingCommandError(cmd_str) - - data = fact.default() - - if status: - if stdout_lines: - try: - data = fact.process(stdout_lines) - except FactProcessError as e: - log_error_or_warning( - host, - global_kwargs["_ignore_errors"], - description=(f"could not process fact: {name} {get_kwargs_str(fact_kwargs)}"), - exception=e, - ) - - # Check we've not failed - if apply_failed_hosts and not global_kwargs["_ignore_errors"]: - state.fail_hosts({host}) - - elif stderr_lines: - # If we have error output and that error is sudo or su stating the user - # does not exist, do not fail but instead return the default fact value. - # This allows for users that don't currently but may be created during - # other operations. - first_line = stderr_lines[0] - if executor_kwargs.get("_sudo_user") and re.match(SUDO_REGEX, first_line): - status = True - if executor_kwargs.get("_su_user") and any( - re.match(regex, first_line) for regex in SU_REGEXES - ): - status = True - - if status: - log_message = "{}{}".format( - host.print_prefix, - f"Loaded fact {format_text(name, bold=True)}{f' ({get_kwargs_str(kwargs)})' if kwargs else ''}", - ) - if state.print_fact_info: - logger.info(log_message) - else: - logger.debug(log_message) - else: - if not state.print_fact_output: - print_host_combined_output(host, output) - - log_error_or_warning( - host, - global_kwargs["_ignore_errors"], - description=(f"could not load fact: {name} {get_kwargs_str(fact_kwargs)}"), - ) - - # Check we've not failed - if apply_failed_hosts and not status and not global_kwargs["_ignore_errors"]: - state.fail_hosts({host}) + return cls.get(state, host, args, kwargs, apply_failed_hosts) - return data +def get_short_facts(state: State, host: Host, short_fact: type[ShortcutFact], **kwargs): + return short_fact.get(state, host, **kwargs) diff --git a/src/pyinfra/api/host.py b/src/pyinfra/api/host.py index 7c8287b3b..3fa9f6acc 100644 --- a/src/pyinfra/api/host.py +++ b/src/pyinfra/api/host.py @@ -7,7 +7,6 @@ Any, TypeVar, cast, - overload, ) from collections.abc import Callable, Generator from uuid import uuid4 @@ -22,7 +21,7 @@ from .connectors import get_execution_connector from .exceptions import ConnectError -from .facts import FactBase, ShortFactBase, get_fact +from .facts import FactCore from .util import memoize, sha1_hash if TYPE_CHECKING: @@ -361,18 +360,12 @@ def get_temp_filename( T = TypeVar("T") - @overload - def get_fact(self, name_or_cls: type[FactBase[T]], *args, **kwargs) -> T: ... - - @overload - def get_fact(self, name_or_cls: type[ShortFactBase[T]], *args, **kwargs) -> T: ... - - def get_fact(self, name_or_cls, *args, **kwargs): + def get_fact(self, name_or_cls: type[FactCore[T]], *args, **kwargs) -> T: """ Get a fact for this host. Facts are not cached, so the fact's command runs on the host each time this is called. """ - return get_fact(self.state, self, name_or_cls, args=args, kwargs=kwargs) + return name_or_cls.get(self.state, self, args=args, kwargs=kwargs) # Connector proxy # diff --git a/src/pyinfra/api/operation.py b/src/pyinfra/api/operation.py index 01ec1458c..702e16f09 100644 --- a/src/pyinfra/api/operation.py +++ b/src/pyinfra/api/operation.py @@ -24,7 +24,7 @@ from .arguments_typed import PyinfraOperation from .command import PyinfraCommand, StringCommand from .exceptions import ArgumentTypeError, NestedOperationError, OperationValueError, PyinfraError -from .facts import FactBase, ShortFactBase +from .facts import FactCore from .host import Host from .operations import run_host_op from .state import State, StateOperationHostData, StateOperationMeta, StateStage @@ -305,7 +305,7 @@ def decorated_func(*args: P.args, **kwargs: P.kwargs) -> OperationMeta: conditions = global_arguments.get("_if") for condition in conditions if isinstance(conditions, list) else (conditions,): - if isinstance(condition, type) and issubclass(condition, (FactBase, ShortFactBase)): + if isinstance(condition, type) and issubclass(condition, FactCore): raise ArgumentTypeError( "Invalid argument `_if`: bare fact classes are not conditions. " "Use any_fact(MyFact), all_fact(MyFact), or " diff --git a/src/pyinfra/facts/apk.py b/src/pyinfra/facts/apk.py index 10ebec116..dbc32d2f8 100644 --- a/src/pyinfra/facts/apk.py +++ b/src/pyinfra/facts/apk.py @@ -2,7 +2,7 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages @@ -11,7 +11,7 @@ APK_REGEX = r"(.+)-([^-]+-r[^-]+) \S+ \{\S+\} \(.+?\)" -class ApkPackages(FactBase): +class ApkPackages(ShellFact): """ Returns a dict of installed apk packages: diff --git a/src/pyinfra/facts/apt.py b/src/pyinfra/facts/apt.py index 198d0bdc5..73fc698d0 100644 --- a/src/pyinfra/facts/apt.py +++ b/src/pyinfra/facts/apt.py @@ -5,7 +5,7 @@ from typing_extensions import TypedDict, override -from pyinfra.api import FactBase, QuoteString, StringCommand +from pyinfra.api import ShellFact, QuoteString, StringCommand from .gpg import GpgKeyrings from .util.packaging import parse_packages @@ -333,7 +333,7 @@ def parse_apt_list_file(lines: list[str]) -> list[AptRepo]: return repos -class AptSources(FactBase): +class AptSources(ShellFact): """Returns a list of installed apt sources (legacy .list + deb822 .sources). Returns a list of AptRepo instances that behave like dicts for backward compatibility: @@ -397,7 +397,7 @@ def flush(): return repos -class AptPackages(FactBase): +class AptPackages(ShellFact): """ Returns a dict of installed apt packages, keyed by name with a list of versions as the value: @@ -438,7 +438,7 @@ def process(self, output): return parse_packages(self.regex, output) -class AptPackageProvides(FactBase): +class AptPackageProvides(ShellFact): """ Returns a list of packages that provide the specified (virtual) package name: @@ -476,7 +476,7 @@ def process(self, output: list[str]) -> list[list[str]]: return packages -class AptHeldPackages(FactBase[list[str]]): +class AptHeldPackages(ShellFact[list[str]]): """ Returns a list of apt packages marked as held (``apt-mark showhold``). Held packages are not automatically upgraded, removed or changed by ``apt``. @@ -555,7 +555,7 @@ class AptSimulationDict(TypedDict): not_upgraded: int -class SimulateOperationWillChange(FactBase[AptSimulationDict]): +class SimulateOperationWillChange(ShellFact[AptSimulationDict]): """ Simulate an 'apt-get' operation and try to detect if any changes would be performed. """ diff --git a/src/pyinfra/facts/brew.py b/src/pyinfra/facts/brew.py index 06b5fcdbf..5fba7863d 100644 --- a/src/pyinfra/facts/brew.py +++ b/src/pyinfra/facts/brew.py @@ -9,7 +9,7 @@ from typing_extensions import override from pyinfra import logger -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages @@ -40,7 +40,7 @@ def _new_cask_cli(version: Sequence[int]) -> bool: BrewVersionType = list[int] -class BrewVersion(FactBase[Sequence[int]]): +class BrewVersion(ShellFact[Sequence[int]]): """ Returns the version of brew installed as a semantic versioning list: @@ -74,7 +74,7 @@ def process(self, output: list[str]) -> BrewVersionType: BrewPackingMapping = dict[str, set[str]] -class BrewPackages(FactBase[BrewPackingMapping]): +class BrewPackages(ShellFact[BrewPackingMapping]): """ Returns a dict of installed brew packages: @@ -167,7 +167,7 @@ def requires_command(self) -> str: BrewTapList = Iterable[str] -class BrewTaps(FactBase[BrewTapList]): +class BrewTaps(ShellFact[BrewTapList]): """ Returns a list of brew taps. @@ -199,7 +199,7 @@ def process(self, output: list[str]) -> BrewTapList: BrewTrustMapping = Mapping[str, Sequence[str]] -class BrewTrusted(FactBase[BrewTrustMapping]): +class BrewTrusted(ShellFact[BrewTrustMapping]): """ Returns a dict with lists of the casks, commands, formulae and taps that have been marked as trusted diff --git a/src/pyinfra/facts/bsdinit.py b/src/pyinfra/facts/bsdinit.py index 25c6b7fe5..afc00ad67 100644 --- a/src/pyinfra/facts/bsdinit.py +++ b/src/pyinfra/facts/bsdinit.py @@ -2,7 +2,7 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .sysvinit import InitdStatus @@ -25,7 +25,7 @@ def command(self) -> str: default = dict -class RcdEnabled(FactBase): +class RcdEnabled(ShellFact): """ Returns a dict of OpenBSD rc.d services enabled at boot. """ @@ -45,7 +45,7 @@ def process(self, output: list[str]) -> dict[str, bool]: return {line: True for line in output} -class ServiceEnabled(FactBase[dict[str, bool]]): +class ServiceEnabled(ShellFact[dict[str, bool]]): """ Returns a dict of FreeBSD rc.d services enabled at boot. """ diff --git a/src/pyinfra/facts/cargo.py b/src/pyinfra/facts/cargo.py index 2b40ae687..153a28222 100644 --- a/src/pyinfra/facts/cargo.py +++ b/src/pyinfra/facts/cargo.py @@ -2,14 +2,14 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages CARGO_REGEX = r"^([a-zA-Z0-9\-]+)\sv([0-9\.]+)" -class CargoPackages(FactBase): +class CargoPackages(ShellFact): """ Returns a dict of installed cargo packages globally: diff --git a/src/pyinfra/facts/choco.py b/src/pyinfra/facts/choco.py index 0c252ea76..62fe521a8 100644 --- a/src/pyinfra/facts/choco.py +++ b/src/pyinfra/facts/choco.py @@ -2,14 +2,14 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages CHOCO_REGEX = r"^([a-zA-Z0-9\.\-\+\_]+)\s([0-9\.]+)$" -class ChocoPackages(FactBase): +class ChocoPackages(ShellFact): """ Returns a dict of installed choco (Chocolatey) packages: @@ -35,7 +35,7 @@ def process(self, output): return parse_packages(CHOCO_REGEX, output) -class ChocoVersion(FactBase): +class ChocoVersion(ShellFact): """ Returns the choco (Chocolatey) version. """ diff --git a/src/pyinfra/facts/crontab.py b/src/pyinfra/facts/crontab.py index 8a24e902a..3aa3bb942 100644 --- a/src/pyinfra/facts/crontab.py +++ b/src/pyinfra/facts/crontab.py @@ -3,7 +3,7 @@ from typing_extensions import NotRequired, override -from pyinfra.api import FactBase, QuoteString, StringCommand +from pyinfra.api import ShellFact, QuoteString, StringCommand from pyinfra.api.util import try_int @@ -119,7 +119,7 @@ def to_json(self): ) -class Crontab(FactBase[CrontabFile]): +class Crontab(ShellFact[CrontabFile]): """ Returns a dictionary of CrontabFile. diff --git a/src/pyinfra/facts/deb.py b/src/pyinfra/facts/deb.py index 9a37cf16a..b8b649457 100644 --- a/src/pyinfra/facts/deb.py +++ b/src/pyinfra/facts/deb.py @@ -4,7 +4,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, QuoteString +from pyinfra.api import ShellFact, QuoteString from pyinfra.api.command import make_formatted_string_command from .util.packaging import parse_packages @@ -13,7 +13,7 @@ DEB_PACKAGE_VERSION_REGEX = r"[a-zA-Z0-9:~\.\-\+]+" -class DebArch(FactBase): +class DebArch(ShellFact): """ Returns the architecture string used in apt repository sources, eg ``amd64``. """ @@ -27,7 +27,7 @@ def requires_command(self) -> str: return "dpkg" -class DebPackages(FactBase): +class DebPackages(ShellFact): """ Returns a dict of installed dpkg packages: @@ -57,7 +57,7 @@ def process(self, output): return parse_packages(self.regex, output) -class DebPackage(FactBase): +class DebPackage(ShellFact): """ Returns information on a .deb archive or installed package. diff --git a/src/pyinfra/facts/dnf.py b/src/pyinfra/facts/dnf.py index bc6961e00..09c6d4028 100644 --- a/src/pyinfra/facts/dnf.py +++ b/src/pyinfra/facts/dnf.py @@ -4,13 +4,13 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util import make_cat_files_command_with_markers from .util.packaging import REPO_FILENAME_MARKER, parse_yum_repositories -class DnfRepositories(FactBase): +class DnfRepositories(ShellFact): """ Returns a list of installed dnf repositories: @@ -52,7 +52,7 @@ def process(self, output): return parse_yum_repositories(output) -class DnfEnabledModules(FactBase): +class DnfEnabledModules(ShellFact): """ Returns a dict mapping enabled dnf module names to their enabled stream: @@ -90,7 +90,7 @@ def process(self, output): return result -class DnfDisabledModules(FactBase): +class DnfDisabledModules(ShellFact): """ Returns a sorted list of dnf module names that have been explicitly disabled: diff --git a/src/pyinfra/facts/docker.py b/src/pyinfra/facts/docker.py index dac503a71..387a79a82 100644 --- a/src/pyinfra/facts/docker.py +++ b/src/pyinfra/facts/docker.py @@ -10,10 +10,10 @@ from typing_extensions import override -from pyinfra.api import FactBase, ShortFactBase +from pyinfra.api import ShellFact, ShortcutFact -class DockerFactBase(FactBase): +class DockerFactBase(ShellFact): abstract = True docker_type: str @@ -28,7 +28,7 @@ def process(self, output): return json.loads(output) -class _DockerJsonLinesFactBase(FactBase): +class _DockerJsonLinesFactBase(ShellFact): abstract = True @override @@ -50,7 +50,7 @@ def command(self) -> str: return 'docker system info --format="{{json .}}"' -class DockerVersion(FactBase[str]): +class DockerVersion(ShellFact[str]): """ Returns the Docker version. """ @@ -182,7 +182,7 @@ class DockerPlugin(DockerSingleMixin): # -class DockerContainerEnvs(ShortFactBase): +class DockerContainerEnvs(ShortcutFact): """ Returns environment variables for all Docker containers, keyed by container ID. """ @@ -203,7 +203,7 @@ def process_data(self, data): return result -class DockerContainerLabels(ShortFactBase): +class DockerContainerLabels(ShortcutFact): """ Returns labels for all Docker containers, keyed by container ID. """ @@ -218,7 +218,7 @@ def process_data(self, data): } -class DockerContainerMounts(ShortFactBase): +class DockerContainerMounts(ShortcutFact): """ Returns mounts for all Docker containers, keyed by container ID. """ @@ -230,7 +230,7 @@ def process_data(self, data): return {container.get("Id"): container.get("Mounts") or [] for container in data or []} -class DockerContainerNetworks(ShortFactBase): +class DockerContainerNetworks(ShortcutFact): """ Returns networks for all Docker containers, keyed by container ID. """ @@ -245,7 +245,7 @@ def process_data(self, data): } -class DockerContainerPorts(ShortFactBase): +class DockerContainerPorts(ShortcutFact): """ Returns published port bindings for all Docker containers, keyed by container ID. """ @@ -260,7 +260,7 @@ def process_data(self, data): } -class DockerImageLabels(ShortFactBase): +class DockerImageLabels(ShortcutFact): """ Returns labels for all Docker images, keyed by image ID. """ @@ -279,7 +279,7 @@ def process_data(self, data): } -class DockerImageLayers(ShortFactBase): +class DockerImageLayers(ShortcutFact): """ Returns layer digests for all Docker images, keyed by image ID. """ @@ -293,7 +293,7 @@ def process_data(self, data): } -class DockerNetworkLabels(ShortFactBase): +class DockerNetworkLabels(ShortcutFact): """ Returns labels for all Docker networks, keyed by network ID. """ @@ -305,7 +305,7 @@ def process_data(self, data): return {network.get("Id"): network.get("Labels") or {} for network in data or []} -class DockerVolumeLabels(ShortFactBase): +class DockerVolumeLabels(ShortcutFact): """ Returns labels for all Docker volumes, keyed by volume name. """ @@ -389,7 +389,7 @@ def command(self, image_id) -> str: return f"docker image history --no-trunc --format '{{{{json .}}}}' {image_id} 2>&- || true" -class DockerAuths(FactBase[list[str]]): +class DockerAuths(ShellFact[list[str]]): """ Returns the list of registry servers the current user is authenticated against, read from ``${DOCKER_CONFIG:-$HOME/.docker}/config.json``. diff --git a/src/pyinfra/facts/efibootmgr.py b/src/pyinfra/facts/efibootmgr.py index b2e8072f9..a676c0ccb 100644 --- a/src/pyinfra/facts/efibootmgr.py +++ b/src/pyinfra/facts/efibootmgr.py @@ -5,7 +5,7 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact BootEntry = tuple[bool, str] @@ -18,7 +18,7 @@ class EFIBootMgrInfoDict(TypedDict): Entries: dict[int, BootEntry] -class EFIBootMgr(FactBase[EFIBootMgrInfoDict | None]): +class EFIBootMgr(ShellFact[EFIBootMgrInfoDict | None]): """ Returns information about the UEFI boot variables: diff --git a/src/pyinfra/facts/files.py b/src/pyinfra/facts/files.py index 891113de7..4c0ebaaab 100644 --- a/src/pyinfra/facts/files.py +++ b/src/pyinfra/facts/files.py @@ -20,7 +20,7 @@ from pyinfra.api import StringCommand from pyinfra.api.command import QuoteString, make_formatted_string_command -from pyinfra.api.facts import FactBase +from pyinfra.api.facts import ShellFact from pyinfra.api.util import try_int from pyinfra.facts.util.units import parse_size @@ -220,7 +220,7 @@ class FileDict(TypedDict): link_target: NotRequired[str] -class File(FactBase[FileDict | Literal[False] | None]): +class File(ShellFact[FileDict | Literal[False] | None]): """ Returns information about a file on the remote system: @@ -369,7 +369,7 @@ class Socket(File): type = "socket" -class SameFile(FactBase[bool]): +class SameFile(ShellFact[bool]): """ Returns ``True`` if ``path`` and ``target`` refer to the same file (same device and inode, ie one is a hard link to the other), otherwise ``False``. @@ -389,15 +389,17 @@ def process(self, output: list[str]) -> bool: if TYPE_CHECKING: - FactBaseOptionalStr = FactBase[str | None] + FactBaseOptionalStr = ShellFact[str | None] else: - FactBaseOptionalStr = FactBase + FactBaseOptionalStr = ShellFact class HashFileFactBase(FactBaseOptionalStr): _raw_cmd: str _regexes: tuple[str, str] + abstract = True + @override def __init_subclass__(cls, digits: int, cmds: list[str], **kwargs) -> None: super().__init_subclass__(**kwargs) @@ -454,7 +456,7 @@ class Md5File(HashFileFactBase, digits=32, cmds=["md5sum", "md5"]): """ -class FindInFile(FactBase): +class FindInFile(ShellFact): """ Checks for the existence of text in a file using grep. Returns a list of matching lines if the file exists, and ``None`` if the file does not. @@ -488,7 +490,7 @@ def process(self, output): return output -class FindFilesBase(FactBase): +class FindFilesBase(ShellFact): abstract = True default = list type_flag: str @@ -619,7 +621,7 @@ class FindDirectories(FindFilesBase): type_flag = "d" -class Flags(FactBase): +class Flags(ShellFact): """ Returns a list of the file flags set for the specified file or directory. """ @@ -647,7 +649,7 @@ def process(self, output): MISSING = "__pyinfra_missing_" -class Block(FactBase): +class Block(ShellFact): """ Returns a (possibly empty) list of the lines found between the markers. @@ -704,7 +706,7 @@ def process(self, output): return output -class FileContents(FactBase[list[str] | None]): +class FileContents(ShellFact[list[str] | None]): """ Returns the contents of a file as a list of lines, or ``None`` if the file does not exist. """ diff --git a/src/pyinfra/facts/flatpak.py b/src/pyinfra/facts/flatpak.py index c36361c3c..1360ca9e6 100644 --- a/src/pyinfra/facts/flatpak.py +++ b/src/pyinfra/facts/flatpak.py @@ -4,10 +4,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class FlatpakBaseFact(FactBase): +class FlatpakBaseFact(ShellFact): abstract = True @override diff --git a/src/pyinfra/facts/freebsd.py b/src/pyinfra/facts/freebsd.py index 41e0e7727..65d4578c1 100644 --- a/src/pyinfra/facts/freebsd.py +++ b/src/pyinfra/facts/freebsd.py @@ -2,11 +2,11 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from pyinfra.api.command import QuoteString, StringCommand, make_formatted_string_command -class ServiceScript(FactBase): +class ServiceScript(ShellFact): @override def command(self, srvname: str, jail: str | None = None) -> StringCommand: if jail is None: @@ -25,7 +25,7 @@ def command(self, srvname: str, jail: str | None = None) -> StringCommand: ) -class ServiceStatus(FactBase): +class ServiceStatus(ShellFact): @override def command(self, srvname: str, jail: str | None = None) -> StringCommand: if jail is None: @@ -38,7 +38,7 @@ def command(self, srvname: str, jail: str | None = None) -> StringCommand: ) -class Sysrc(FactBase): +class Sysrc(ShellFact): @override def command(self, parameter: str, jail: str | None = None) -> StringCommand: if jail is None: @@ -53,7 +53,7 @@ def command(self, parameter: str, jail: str | None = None) -> StringCommand: return command -class PkgPackage(FactBase): +class PkgPackage(ShellFact): @override def command(self, package: str, jail: str | None = None) -> StringCommand: if jail is None: diff --git a/src/pyinfra/facts/gem.py b/src/pyinfra/facts/gem.py index cad67a6f4..f86606fad 100644 --- a/src/pyinfra/facts/gem.py +++ b/src/pyinfra/facts/gem.py @@ -2,14 +2,14 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages GEM_REGEX = r"^([a-zA-Z0-9\-\+\_]+)\s\(([0-9\.]+)\)$" -class GemPackages(FactBase): +class GemPackages(ShellFact): """ Returns a dict of installed gem packages: diff --git a/src/pyinfra/facts/git.py b/src/pyinfra/facts/git.py index a8051f713..065f1fd22 100644 --- a/src/pyinfra/facts/git.py +++ b/src/pyinfra/facts/git.py @@ -4,10 +4,12 @@ from typing_extensions import override -from pyinfra.api.facts import FactBase +from pyinfra.api.facts import ShellFact -class GitFactBase(FactBase): +class GitFactBase(ShellFact): + abstract = True + @override def requires_command(self, *args, **kwargs) -> str: return "git" diff --git a/src/pyinfra/facts/go.py b/src/pyinfra/facts/go.py index 68f094a02..e46d38020 100644 --- a/src/pyinfra/facts/go.py +++ b/src/pyinfra/facts/go.py @@ -2,10 +2,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class GoPackages(FactBase): +class GoPackages(ShellFact): """ Returns a dict of installed Go binary packages (those installed via ``go install``) keyed by their import path: diff --git a/src/pyinfra/facts/gpg.py b/src/pyinfra/facts/gpg.py index 51a154ef9..894a139b8 100644 --- a/src/pyinfra/facts/gpg.py +++ b/src/pyinfra/facts/gpg.py @@ -4,10 +4,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class GpgFactBase(FactBase): +class GpgFactBase(ShellFact): abstract = True @override diff --git a/src/pyinfra/facts/hardware.py b/src/pyinfra/facts/hardware.py index 34843244b..de9c063c4 100644 --- a/src/pyinfra/facts/hardware.py +++ b/src/pyinfra/facts/hardware.py @@ -8,10 +8,10 @@ from typing_extensions import NotRequired, TypedDict, override from pyinfra import logger -from pyinfra.api import FactBase, ShortFactBase +from pyinfra.api import ShellFact, ShortcutFact -class CpuInfo(FactBase): +class CpuInfo(ShellFact): """ Returns dict of information returned by lscpu command. @@ -132,7 +132,7 @@ def process(self, output): return None -class Cpus(FactBase[int]): +class Cpus(ShellFact[int]): """ Returns the number of CPUs on this server. """ @@ -149,7 +149,7 @@ def process(self, output): pass -class Memory(FactBase): +class Memory(ShellFact): """ Returns the memory installed in this server, in MB. """ @@ -205,7 +205,7 @@ def process(self, output): return int(round(total_memory / 1024)) -class BlockDevices(FactBase): +class BlockDevices(ShellFact): """ Returns a dict of (mounted) block devices: @@ -272,7 +272,7 @@ class DevInfoType(TypedDict): NtwkDevMapType = dict[str, DevInfoType] -class NetworkDevices(FactBase[NtwkDevMapType]): +class NetworkDevices(ShellFact[NtwkDevMapType]): """ Gets & returns a dict of network devices. See the ``ipv4_addresses`` and ``ipv6_addresses`` facts for easier-to-use shortcuts to get device addresses. @@ -573,7 +573,7 @@ def process(self, output: Sequence[str]) -> NtwkDevMapType: return all_devices -class Ipv4Addrs(ShortFactBase): +class Ipv4Addrs(ShortcutFact): """ Gets & returns a dictionary of network interface -> list of IPv4 addresses. @@ -632,7 +632,7 @@ class Ipv6Addrs(Ipv4Addrs): # -class Ipv4Addresses(ShortFactBase): +class Ipv4Addresses(ShortcutFact): """ Gets & returns a dictionary of network interface -> IPv4 address. diff --git a/src/pyinfra/facts/iptables.py b/src/pyinfra/facts/iptables.py index 2d71d1407..f89e8875b 100644 --- a/src/pyinfra/facts/iptables.py +++ b/src/pyinfra/facts/iptables.py @@ -4,7 +4,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, QuoteString, StringCommand +from pyinfra.api import ShellFact, QuoteString, StringCommand # Mapping for iptables code arguments to variable names IPTABLES_ARGS = { @@ -104,7 +104,7 @@ def add_args() -> None: return definition -class IptablesRules(FactBase): +class IptablesRules(ShellFact): """ Returns a list of iptables rules for a specific table: @@ -162,7 +162,7 @@ def command(self, table: str = "filter") -> StringCommand: return StringCommand("ip6tables-save", "-t", QuoteString(table)) -class IptablesChains(FactBase): +class IptablesChains(ShellFact): """ Returns a dict of iptables chains & policies: diff --git a/src/pyinfra/facts/launchd.py b/src/pyinfra/facts/launchd.py index 643e7a179..f25bf0bb6 100644 --- a/src/pyinfra/facts/launchd.py +++ b/src/pyinfra/facts/launchd.py @@ -2,10 +2,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class LaunchdStatus(FactBase): +class LaunchdStatus(ShellFact): """ Returns a dict of name -> status for launchd managed services. """ diff --git a/src/pyinfra/facts/lxd.py b/src/pyinfra/facts/lxd.py index 4b46b264c..64fbb6157 100644 --- a/src/pyinfra/facts/lxd.py +++ b/src/pyinfra/facts/lxd.py @@ -4,10 +4,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class LxdContainers(FactBase): +class LxdContainers(ShellFact): """ Returns a list of running LXD containers """ diff --git a/src/pyinfra/facts/mysql.py b/src/pyinfra/facts/mysql.py index d422f5f55..967d16a0f 100644 --- a/src/pyinfra/facts/mysql.py +++ b/src/pyinfra/facts/mysql.py @@ -5,7 +5,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, HiddenValue, QuoteString, StringCommand +from pyinfra.api import ShellFact, HiddenValue, QuoteString, StringCommand from pyinfra.api.util import try_int from .util.databases import parse_columns_and_rows @@ -58,7 +58,7 @@ def make_execute_mysql_command( return StringCommand(*commands_bits) -class MysqlFactBase(FactBase): +class MysqlFactBase(ShellFact): abstract = True mysql_command: str diff --git a/src/pyinfra/facts/npm.py b/src/pyinfra/facts/npm.py index 3f826496a..d2d74dda0 100644 --- a/src/pyinfra/facts/npm.py +++ b/src/pyinfra/facts/npm.py @@ -2,14 +2,14 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages NPM_REGEX = r"^[└├]\─\─\s([a-zA-Z0-9\-]+)@([0-9\.]+)$" -class NpmPackages(FactBase): +class NpmPackages(ShellFact): """ Returns a dict of installed npm packages globally or in a given directory: diff --git a/src/pyinfra/facts/openrc.py b/src/pyinfra/facts/openrc.py index 7edbf71e9..9da30aee1 100644 --- a/src/pyinfra/facts/openrc.py +++ b/src/pyinfra/facts/openrc.py @@ -4,10 +4,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class OpenrcStatus(FactBase): +class OpenrcStatus(ShellFact): """ Returns a dict of name -> status for OpenRC services for a given runlevel. """ @@ -42,7 +42,7 @@ def process(self, output): return services -class OpenrcEnabled(FactBase): +class OpenrcEnabled(ShellFact): """ Returns a dict of name -> whether enabled for OpenRC services for a given runlevel. """ diff --git a/src/pyinfra/facts/opkg.py b/src/pyinfra/facts/opkg.py index d4b71174d..dd8f619c0 100644 --- a/src/pyinfra/facts/opkg.py +++ b/src/pyinfra/facts/opkg.py @@ -18,7 +18,7 @@ from typing_extensions import override from pyinfra import logger -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from pyinfra.facts.util.packaging import parse_packages # TODO - change NamedTuple to dataclass Opkgbut need to figure out how to get json serialization @@ -43,7 +43,7 @@ class OpkgFeedInfo(NamedTuple): kind: str # whether it comes from the 'distribution' or is 'custom' -class OpkgConf(FactBase): +class OpkgConf(ShellFact): """ Returns a NamedTuple with the current configuration: @@ -115,7 +115,7 @@ def process(self, output): return OpkgConfInfo(dest, lists_dir, options, arch_cfg) -class OpkgFeeds(FactBase): +class OpkgFeeds(ShellFact): """ Returns a dictionary containing the information for the distribution-provided and custom opkg feeds: @@ -163,7 +163,7 @@ def process(self, output): return feeds -class OpkgInstallableArchitectures(FactBase): +class OpkgInstallableArchitectures(ShellFact): """ Returns a dictionary containing the currently installable architectures for this system along with their priority: @@ -202,7 +202,7 @@ def process(self, output): return arch_list -class OpkgPackages(FactBase): +class OpkgPackages(ShellFact): """ Returns a dict of installed opkg packages: @@ -230,7 +230,7 @@ def process(self, output): return parse_packages(self.regex, sorted(output)) -class OpkgUpgradeablePackages(FactBase): +class OpkgUpgradeablePackages(ShellFact): """ Returns a dict of installed and upgradable opkg packages: diff --git a/src/pyinfra/facts/pacman.py b/src/pyinfra/facts/pacman.py index 9643faf0d..18bf4ad40 100644 --- a/src/pyinfra/facts/pacman.py +++ b/src/pyinfra/facts/pacman.py @@ -2,7 +2,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, QuoteString +from pyinfra.api import ShellFact, QuoteString from pyinfra.api.command import make_formatted_string_command from .util.packaging import parse_packages @@ -11,7 +11,7 @@ PACMAN_REGEX = r"^(\S+)\s(\S+)" -class PacmanUnpackGroup(FactBase): +class PacmanUnpackGroup(ShellFact): """ Returns a list of actual packages belonging to the provided package name, expanding groups or virtual packages. @@ -41,7 +41,7 @@ def process(self, output): return output -class PacmanPackages(FactBase): +class PacmanPackages(ShellFact): """ Returns a dict of installed pacman packages: diff --git a/src/pyinfra/facts/pip.py b/src/pyinfra/facts/pip.py index fbf1a209a..2df727f27 100644 --- a/src/pyinfra/facts/pip.py +++ b/src/pyinfra/facts/pip.py @@ -2,14 +2,14 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages PIP_REGEX = r"^([a-zA-Z0-9_\-\+\.]+)==([0-9\.]+[a-z0-9\-]*)$" -class PipPackages(FactBase): +class PipPackages(ShellFact): """ Returns a dict of installed pip packages: diff --git a/src/pyinfra/facts/pipx.py b/src/pyinfra/facts/pipx.py index 33be1ec4c..f421ee9e4 100644 --- a/src/pyinfra/facts/pipx.py +++ b/src/pyinfra/facts/pipx.py @@ -2,7 +2,7 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages @@ -24,7 +24,7 @@ def parse_environment(output): PIPX_REGEX = r"^([a-zA-Z0-9_\-\+\.]+)\s+([0-9\.]+[a-z0-9\-]*)$" -class PipxPackages(FactBase): +class PipxPackages(ShellFact): """ Returns a dict of installed pipx packages: @@ -50,7 +50,7 @@ def process(self, output): return parse_packages(PIPX_REGEX, output) -class PipxEnvironment(FactBase): +class PipxEnvironment(ShellFact): """ Returns a dict of pipx environment variables: diff --git a/src/pyinfra/facts/pkg.py b/src/pyinfra/facts/pkg.py index 04aa21551..0f880db99 100644 --- a/src/pyinfra/facts/pkg.py +++ b/src/pyinfra/facts/pkg.py @@ -2,12 +2,12 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages -class PkgPackages(FactBase): +class PkgPackages(ShellFact): """ Returns a dict of installed pkg packages: diff --git a/src/pyinfra/facts/pkgin.py b/src/pyinfra/facts/pkgin.py index 2cd84786d..99d859398 100644 --- a/src/pyinfra/facts/pkgin.py +++ b/src/pyinfra/facts/pkgin.py @@ -2,14 +2,14 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages PKGIN_REGEX = r"^([a-zA-Z\-0-9]+)-([0-9\.]+\-?[a-z0-9]*)\s" -class PkginPackages(FactBase): +class PkginPackages(ShellFact): """ Returns a dict of installed pkgin packages: diff --git a/src/pyinfra/facts/pnpm.py b/src/pyinfra/facts/pnpm.py index fd246ff04..8345044ee 100644 --- a/src/pyinfra/facts/pnpm.py +++ b/src/pyinfra/facts/pnpm.py @@ -15,7 +15,7 @@ from typing_extensions import override from pyinfra import logger -from pyinfra.api import FactBase, QuoteString, StringCommand +from pyinfra.api import ShellFact, QuoteString, StringCommand from .util.packaging import PackageVersionDict @@ -33,7 +33,7 @@ UP_TO_DATE_MARKER = "up_to_date" -class PnpmPackages(FactBase[PackageVersionDict]): +class PnpmPackages(ShellFact[PackageVersionDict]): """ Returns a dict of installed pnpm packages, globally or in a given directory: @@ -103,7 +103,7 @@ def process(self, output: list[str]) -> PackageVersionDict: return packages -class PnpmModulesUpToDate(FactBase[bool]): +class PnpmModulesUpToDate(ShellFact[bool]): """ Returns whether a project's ``node_modules`` was installed from the ``pnpm-lock.yaml`` now in the directory. @@ -141,7 +141,7 @@ def process(self, output: list[str]) -> bool: return output[0].strip() == UP_TO_DATE_MARKER -class PnpmVersion(FactBase[str]): +class PnpmVersion(ShellFact[str]): """ Returns the version of pnpm installed: diff --git a/src/pyinfra/facts/podman.py b/src/pyinfra/facts/podman.py index abc505c21..f6a04af56 100644 --- a/src/pyinfra/facts/podman.py +++ b/src/pyinfra/facts/podman.py @@ -5,7 +5,7 @@ from collections.abc import Iterable from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from pyinfra.api.exceptions import FactProcessError @@ -30,7 +30,7 @@ def _parse_podman_json(value: Iterable[str], expected: type[PodmanJsonT]) -> Pod return output -class PodmanFactBase(FactBase[T]): +class PodmanFactBase(ShellFact[T]): """ Base for facts using `podman` to retrieve """ diff --git a/src/pyinfra/facts/postgres.py b/src/pyinfra/facts/postgres.py index 552e8230b..b3c88cb17 100644 --- a/src/pyinfra/facts/postgres.py +++ b/src/pyinfra/facts/postgres.py @@ -2,7 +2,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, HiddenValue, QuoteString, StringCommand +from pyinfra.api import ShellFact, HiddenValue, QuoteString, StringCommand from pyinfra.api.util import try_int from .util.databases import parse_columns_and_rows @@ -52,7 +52,7 @@ def make_execute_psql_command(command, **psql_kwargs): ) -class PostgresFactBase(FactBase): +class PostgresFactBase(ShellFact): abstract = True psql_command: str diff --git a/src/pyinfra/facts/rpm.py b/src/pyinfra/facts/rpm.py index 4aedf2eda..e4ed478bd 100644 --- a/src/pyinfra/facts/rpm.py +++ b/src/pyinfra/facts/rpm.py @@ -4,7 +4,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, QuoteString +from pyinfra.api import ShellFact, QuoteString from pyinfra.api.command import make_formatted_string_command from .util.packaging import parse_packages @@ -13,7 +13,7 @@ rpm_query_format = "%{NAME} %{VERSION}-%{RELEASE}\\n" -class RpmPackages(FactBase): +class RpmPackages(ShellFact): """ Returns a dict of installed rpm packages: @@ -41,7 +41,7 @@ def process(self, output): return parse_packages(rpm_regex, output) -class RpmPackage(FactBase): +class RpmPackage(ShellFact): """ Returns information on a .rpm file: @@ -78,7 +78,7 @@ def process(self, output): } -class RpmPackageProvides(FactBase): +class RpmPackageProvides(ShellFact): """ Returns a list of packages that provide the specified capability (command, file, etc). """ diff --git a/src/pyinfra/facts/runit.py b/src/pyinfra/facts/runit.py index f718d3b91..c3f97a185 100644 --- a/src/pyinfra/facts/runit.py +++ b/src/pyinfra/facts/runit.py @@ -1,9 +1,9 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class RunitStatus(FactBase): +class RunitStatus(ShellFact): """ Returns a dict of name -> status for runit services. @@ -55,7 +55,7 @@ def process(self, output): return services -class RunitManaged(FactBase): +class RunitManaged(ShellFact): """ Returns a set of all services managed by runit diff --git a/src/pyinfra/facts/selinux.py b/src/pyinfra/facts/selinux.py index 78e88de6d..7268832ed 100644 --- a/src/pyinfra/facts/selinux.py +++ b/src/pyinfra/facts/selinux.py @@ -5,12 +5,12 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact FIELDS = ["user", "role", "type", "level"] # order is significant, do not change -class SEBoolean(FactBase): +class SEBoolean(ShellFact): """ Returns the status of a SELinux Boolean as a string (``on`` or ``off``). If ``boolean`` does not exist, ``SEBoolean`` returns the empty string. @@ -32,7 +32,7 @@ def process(self, output): return components[1] -class FileContext(FactBase): +class FileContext(ShellFact): """ Returns structured SELinux file context data for a specified file or ``None`` if the file does not exist. @@ -64,7 +64,7 @@ def process(self, output): } -class FileContextMapping(FactBase): +class FileContextMapping(ShellFact): """ Returns structured SELinux file context data for the specified target path prefix using the same format as :ref:`facts:selinux.FileContext`. @@ -92,7 +92,7 @@ def process(self, output): return {k: m.group(i) for i, k in enumerate(FIELDS, 1)} if m is not None else self.default() -class SEPorts(FactBase): +class SEPorts(ShellFact): """ Returns the SELinux 'type' definitions for ``(tcp|udp|dccp|sctp)`` ports. Note: This fact requires root privileges. @@ -138,7 +138,7 @@ def process(self, output): return labels -class SEPort(FactBase): +class SEPort(ShellFact): """ Returns the SELinux 'type' for the specified protocol ``(tcp|udp|dccp|sctp)`` and port number. If no type has been set, ``SEPort`` returns the empty string. diff --git a/src/pyinfra/facts/server.py b/src/pyinfra/facts/server.py index 844cca6e7..ecfdb799a 100644 --- a/src/pyinfra/facts/server.py +++ b/src/pyinfra/facts/server.py @@ -14,7 +14,7 @@ from typing_extensions import TypedDict, override from pyinfra import host -from pyinfra.api import FactBase, ShortFactBase, StringCommand +from pyinfra.api import ShellFact, ShortcutFact, StringCommand from pyinfra.api.command import QuoteString, make_formatted_string_command from pyinfra.api.util import try_int from pyinfra.facts import crontab @@ -39,7 +39,7 @@ def _check_tilde_username(user: str) -> None: raise ValueError(f"Unsafe username for shell tilde expansion: {user!r}") -class User(FactBase): +class User(ShellFact): """ Returns the name of the current user. """ @@ -49,7 +49,7 @@ def command(self): return "echo $USER" -class Home(FactBase[str | None]): +class Home(ShellFact[str | None]): """ Returns the home directory of the given user, or the current user if no user is given. """ @@ -62,7 +62,7 @@ def command(self, user="") -> StringCommand: return StringCommand(f"echo ~{user}") -class Path(FactBase): +class Path(ShellFact): """ Returns the path environment variable of the current user. """ @@ -72,7 +72,7 @@ def command(self): return "echo $PATH" -class TmpDir(FactBase): +class TmpDir(ShellFact): """ Returns the temporary directory of the current server. @@ -98,7 +98,7 @@ def command(self): """.strip() -class Hostname(FactBase): +class Hostname(ShellFact): """ Returns the current hostname of the server. """ @@ -108,7 +108,7 @@ def command(self): return "uname -n" -class Kernel(FactBase): +class Kernel(ShellFact): """ Returns the kernel name according to ``uname``. """ @@ -118,7 +118,7 @@ def command(self): return "uname -s" -class KernelVersion(FactBase): +class KernelVersion(ShellFact): """ Returns the kernel version according to ``uname``. """ @@ -128,7 +128,7 @@ def command(self): return "uname -r" -class Uptime(FactBase[int]): +class Uptime(ShellFact[int]): """ Returns the number of seconds the system has been up. """ @@ -150,7 +150,7 @@ def process(self, output: list[str]) -> int: # Deprecated/renamed -> Kernel -class Os(FactBase[str]): +class Os(ShellFact[str]): """ Returns the OS name according to ``uname``. @@ -164,7 +164,7 @@ def command(self): # Deprecated/renamed -> KernelVersion -class OsVersion(FactBase[str]): +class OsVersion(ShellFact[str]): """ Returns the OS version according to ``uname``. @@ -177,7 +177,7 @@ def command(self): return "uname -r" -class Arch(FactBase[str]): +class Arch(ShellFact[str]): """ Returns the system architecture according to ``uname``. """ @@ -189,7 +189,7 @@ def command(self): return "uname -m" -class Command(FactBase[str]): +class Command(ShellFact[str]): """ Returns the raw output lines of a given command. """ @@ -199,7 +199,7 @@ def command(self, command): return command -class Timezone(FactBase[str]): +class Timezone(ShellFact[str]): """ Returns the current system timezone (e.g. ``Europe/Amsterdam``). """ @@ -213,7 +213,7 @@ def process(self, output: list[str]) -> str: return output[0] -class Which(FactBase[str | None]): +class Which(ShellFact[str | None]): """ Returns the path of a given command according to `command -v`, if available. """ @@ -223,7 +223,7 @@ def command(self, command) -> StringCommand: return StringCommand("command -v", QuoteString(command), "|| true") -class Date(FactBase[datetime]): +class Date(ShellFact[datetime]): """ Returns the current datetime on the server. """ @@ -239,7 +239,7 @@ def process(self, output) -> datetime: return datetime.strptime(list(output)[0], ISO_DATE_FORMAT) -class MacosVersion(FactBase[str]): +class MacosVersion(ShellFact[str]): """ Returns the installed MacOS version. """ @@ -268,7 +268,7 @@ class MountsDict(TypedDict): options: list[str] -class Mounts(FactBase[dict[str, MountsDict]]): +class Mounts(ShellFact[dict[str, MountsDict]]): """ Returns a dictionary of mounted filesystems and information. @@ -376,7 +376,7 @@ def replace_octal(s: str) -> str: return devices -class Port(FactBase[tuple[str, int] | tuple[None, None]]): +class Port(ShellFact[tuple[str, int] | tuple[None, None]]): """ Returns the process occupying a port and its PID. @@ -458,7 +458,7 @@ def _process_sockstat(self, output: Iterable[str]) -> tuple[str, int] | tuple[No return None, None -class Ports(FactBase[list[dict[str, int | str]]]): +class Ports(ShellFact[list[dict[str, int | str]]]): """ Returns a list of all listening ports with their processes and PIDs. @@ -588,7 +588,7 @@ def _process_sockstat(self, output: Iterable[str]) -> list[dict[str, int | str]] return results -class KernelModules(FactBase): +class KernelModules(ShellFact): """ Returns a dictionary of kernel module name -> info. @@ -648,7 +648,7 @@ def process(self, output): return modules -class LsbRelease(FactBase): +class LsbRelease(ShellFact): """ Returns a dictionary of release information using ``lsb_release``. @@ -694,7 +694,7 @@ def process(self, output): return items -class OsRelease(FactBase): +class OsRelease(ShellFact): """ Returns a dictionary of release information stored in ``/etc/os-release``. @@ -726,7 +726,7 @@ def process(self, output): return items -class Sysctl(FactBase): +class Sysctl(ShellFact): """ Returns a dictionary of sysctl settings and values. @@ -778,7 +778,7 @@ def process(self, output): return sysctls -class Groups(FactBase[list[str]]): +class Groups(ShellFact[list[str]]): """ Returns a list of groups on the system. """ @@ -805,7 +805,7 @@ def process(self, output) -> list[str]: Crontab = crontab.Crontab -class Users(FactBase): +class Users(ShellFact): """ Returns a dictionary of users -> details. @@ -888,7 +888,7 @@ def process(self, output): return users -class AuthorizedKeys(FactBase[list[str]]): +class AuthorizedKeys(ShellFact[list[str]]): """ Returns the SSH public keys listed in a user's ``~/.ssh/authorized_keys`` file as a list of full key strings. Empty lines and lines starting with ``#`` are skipped; the @@ -931,7 +931,7 @@ class LinuxDistributionDict(TypedDict): release_meta: dict -class LinuxDistribution(FactBase[LinuxDistributionDict]): +class LinuxDistribution(ShellFact[LinuxDistributionDict]): """ Returns a dict of the Linux distribution version. Ubuntu, Debian, CentOS, Fedora & Gentoo currently. Also contains any key/value items located in @@ -1042,7 +1042,7 @@ def process(self, output) -> LinuxDistributionDict: return release_info -class LinuxName(ShortFactBase[str]): +class LinuxName(ShortcutFact[str]): """ Returns the name of the Linux distribution. Shortcut for ``host.get_fact(LinuxDistribution)['name']``. @@ -1059,7 +1059,7 @@ class SelinuxDict(TypedDict): mode: str | None -class Selinux(FactBase[SelinuxDict]): +class Selinux(ShellFact[SelinuxDict]): """ Discovers the SELinux related facts on the target host. @@ -1099,7 +1099,7 @@ def process(self, output) -> SelinuxDict: return selinux_info -class LinuxGui(FactBase[list[str]]): +class LinuxGui(ShellFact[list[str]]): """ Returns a list of available Linux GUIs. """ @@ -1130,7 +1130,7 @@ def process(self, output) -> list[str]: return gui_names -class HasGui(ShortFactBase[bool]): +class HasGui(ShortcutFact[bool]): """ Returns a boolean indicating the remote side has GUI capabilities. Linux only. """ @@ -1142,7 +1142,7 @@ def process_data(self, data) -> bool: return len(data) > 0 -class Locales(FactBase[list[str]]): +class Locales(ShellFact[list[str]]): """ Returns installed locales on the target host. @@ -1168,7 +1168,7 @@ def process(self, output) -> list[str]: return [line.replace("utf8", "UTF-8") for line in output] -class SecurityLimits(FactBase): +class SecurityLimits(ShellFact): """ Returns a list of security limits on the target host. @@ -1254,7 +1254,7 @@ def process(self, output): return limits -class RebootRequired(FactBase[bool]): +class RebootRequired(ShellFact[bool]): """ Returns a boolean indicating whether the system requires a reboot. @@ -1309,7 +1309,7 @@ def process(self, output) -> bool: _DARWIN_COMM_MARKER = "===PYINFRA-PROCESSES-COMM===" -class Processes(FactBase[dict[int, ProcessDict]]): +class Processes(ShellFact[dict[int, ProcessDict]]): """ Returns a dictionary of running processes keyed by PID. @@ -1496,7 +1496,7 @@ def process(self, output: Iterable[str]) -> dict[int, ProcessDict]: return processes -class EtcHosts(FactBase[dict[str, list[str]]]): +class EtcHosts(ShellFact[dict[str, list[str]]]): """ Returns ``/etc/hosts`` (or the file at ``path``) parsed as a mapping of IP address to the list of hostnames declared on the matching lines. Comments and empty lines @@ -1543,7 +1543,7 @@ class LastRecordDict(TypedDict): time: str -class Last(FactBase[list[LastRecordDict]]): +class Last(ShellFact[list[LastRecordDict]]): """ Returns login records parsed from ``last`` as a list of dicts. @@ -1633,7 +1633,7 @@ def process(self, output: Iterable[str]) -> list[LastRecordDict]: return records -class LoadAverage(FactBase[dict[str, float]]): +class LoadAverage(ShellFact[dict[str, float]]): """ Returns the system load average keyed by window (1, 5 and 15 minutes). diff --git a/src/pyinfra/facts/snap.py b/src/pyinfra/facts/snap.py index 56b7846ca..59b82783a 100644 --- a/src/pyinfra/facts/snap.py +++ b/src/pyinfra/facts/snap.py @@ -4,10 +4,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class SnapBaseFact(FactBase): +class SnapBaseFact(ShellFact): abstract = True @override diff --git a/src/pyinfra/facts/supervisorctl.py b/src/pyinfra/facts/supervisorctl.py index f290b5581..c030afd3e 100644 --- a/src/pyinfra/facts/supervisorctl.py +++ b/src/pyinfra/facts/supervisorctl.py @@ -2,7 +2,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, HiddenValue, QuoteString, StringCommand +from pyinfra.api import ShellFact, HiddenValue, QuoteString, StringCommand RUNNING_STATES = ("RUNNING", "STARTING") STOPPED_STATES = ("STOPPED", "STOPPING", "EXITED") @@ -32,7 +32,7 @@ def _make_supervisorctl_command( return StringCommand(*command_bits) -class SupervisorctlStatus(FactBase[dict[str, "bool | None"]]): +class SupervisorctlStatus(ShellFact[dict[str, "bool | None"]]): """ Returns a dict of supervisor process names to their running state. @@ -99,7 +99,7 @@ def process(self, output: list[str]) -> dict[str, bool | None]: return processes -class SupervisorctlPid(FactBase["int | None"]): +class SupervisorctlPid(ShellFact["int | None"]): """ Returns the PID of supervisord itself, or of a single supervisor managed process when ``process`` is given. @@ -152,7 +152,7 @@ def process(self, output: list[str]) -> int | None: return None -class SupervisorctlPids(FactBase[list[int]]): +class SupervisorctlPids(ShellFact[list[int]]): """ Returns a list of the PIDs of all supervisor managed processes (``supervisorctl pid all``). A PID of ``0`` means a process is not diff --git a/src/pyinfra/facts/systemd.py b/src/pyinfra/facts/systemd.py index 60c34d01e..937d92bf0 100644 --- a/src/pyinfra/facts/systemd.py +++ b/src/pyinfra/facts/systemd.py @@ -5,7 +5,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, QuoteString, StringCommand +from pyinfra.api import ShellFact, QuoteString, StringCommand # Valid unit names consist of a "name prefix" and a dot and a suffix specifying the unit type. # The "unit prefix" must consist of one or more valid characters @@ -41,7 +41,7 @@ def _make_systemctl_cmd(user_mode=False, machine=None, user_name=None): return StringCommand(*systemctl_cmd) -class SystemdStatus(FactBase[dict[str, bool]]): +class SystemdStatus(ShellFact[dict[str, bool]]): """ Returns a dictionary map of systemd units to booleans indicating whether they are active. diff --git a/src/pyinfra/facts/sysvinit.py b/src/pyinfra/facts/sysvinit.py index e632770c0..51ce3dbbc 100644 --- a/src/pyinfra/facts/sysvinit.py +++ b/src/pyinfra/facts/sysvinit.py @@ -4,10 +4,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class InitdStatus(FactBase): +class InitdStatus(ShellFact): """ Low level check for every /etc/init.d/* script. Unfortunately many of these misbehave and return exit status 0 while also displaying the help info/not diff --git a/src/pyinfra/facts/upstart.py b/src/pyinfra/facts/upstart.py index 98f22ac50..3a1a961a2 100644 --- a/src/pyinfra/facts/upstart.py +++ b/src/pyinfra/facts/upstart.py @@ -4,10 +4,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class UpstartStatus(FactBase): +class UpstartStatus(ShellFact): """ Returns a dict of name -> status for upstart managed services. """ diff --git a/src/pyinfra/facts/uv.py b/src/pyinfra/facts/uv.py index bd30dae24..f0ca05803 100644 --- a/src/pyinfra/facts/uv.py +++ b/src/pyinfra/facts/uv.py @@ -19,7 +19,7 @@ from pyinfra import logger from pyinfra.api import StringCommand -from pyinfra.api.facts import FactBase +from pyinfra.api.facts import ShellFact from pyinfra.facts.util.packaging import PackageVersionDict UV_CMD = "uv" @@ -40,7 +40,7 @@ def process_json(command: str, output: Iterable[str], key: str, value: str) -> P return {v[key]: {v[value]} for v in sorted(info, key=itemgetter(key))} -class UvPipPackages(FactBase[PackageVersionDict]): +class UvPipPackages(ShellFact[PackageVersionDict]): """ Provides the installed Python packages and their version. @@ -71,7 +71,7 @@ def process(self, output: Iterable[str]) -> PackageVersionDict: return process_json(str(self.command()), output, "name", "version") -class UvAvailablePythonsByImplementation(FactBase[PackageVersionDict]): +class UvAvailablePythonsByImplementation(ShellFact[PackageVersionDict]): """ Provides the implementation(s) of Python available for installation along with the versions(s) of the implementation(s). @@ -175,7 +175,7 @@ def process(self, output: Iterable[str]) -> PackageVersionDict: return process_json(str(self.cmd), output, "version", "key") -class UvPythonDir(FactBase[str]): +class UvPythonDir(ShellFact[str]): """ Provides the directory in which uv installs Python implementations. @@ -225,7 +225,7 @@ def command(self) -> StringCommand | str: return f"{UV_CMD} tool dir 2>/dev/null" -class UvTools(FactBase[PackageVersionDict]): +class UvTools(ShellFact[PackageVersionDict]): """ Provides the tool(s) currently installed along with their version(s). @@ -269,7 +269,7 @@ def process(self, output: Iterable[str]) -> PackageVersionDict: return result -class UvVersion(FactBase[str]): +class UvVersion(ShellFact[str]): """ Provides the version of uv installed. diff --git a/src/pyinfra/facts/vzctl.py b/src/pyinfra/facts/vzctl.py index 2d5d0b70f..4f74c2e51 100644 --- a/src/pyinfra/facts/vzctl.py +++ b/src/pyinfra/facts/vzctl.py @@ -4,10 +4,10 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class OpenvzContainers(FactBase): +class OpenvzContainers(ShellFact): """ Returns a dict of running OpenVZ containers by CTID: diff --git a/src/pyinfra/facts/xbps.py b/src/pyinfra/facts/xbps.py index 8c1f0786f..9adab90ab 100644 --- a/src/pyinfra/facts/xbps.py +++ b/src/pyinfra/facts/xbps.py @@ -4,12 +4,12 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util.packaging import parse_packages -class XbpsPackages(FactBase): +class XbpsPackages(ShellFact): """ Returns a dict of installed XBPS packages: @@ -37,7 +37,7 @@ def process(self, output): return parse_packages(self.regex, output) -class XbpsSelfUpdate(FactBase[list[str]]): +class XbpsSelfUpdate(ShellFact[list[str]]): """ Returns the packages XBPS would update to update itself, empty if ``xbps`` is up to date: diff --git a/src/pyinfra/facts/yum.py b/src/pyinfra/facts/yum.py index dd5b681bd..f4253d000 100644 --- a/src/pyinfra/facts/yum.py +++ b/src/pyinfra/facts/yum.py @@ -2,13 +2,13 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util import make_cat_files_command_with_markers from .util.packaging import REPO_FILENAME_MARKER, parse_yum_repositories -class YumRepositories(FactBase): +class YumRepositories(ShellFact): """ Returns a list of installed yum repositories: diff --git a/src/pyinfra/facts/zfs.py b/src/pyinfra/facts/zfs.py index a5be3747d..6e14e1057 100644 --- a/src/pyinfra/facts/zfs.py +++ b/src/pyinfra/facts/zfs.py @@ -4,7 +4,7 @@ from typing_extensions import override -from pyinfra.api import FactBase, ShortFactBase +from pyinfra.api import ShellFact, ShortcutFact def _process_zfs_props_table(output): @@ -17,7 +17,7 @@ def _process_zfs_props_table(output): return datasets -class ZfsPools(FactBase): +class ZfsPools(ShellFact): @override def command(self) -> str: return "zpool get -H all" @@ -33,7 +33,7 @@ def process(self, output): return _process_zfs_props_table(output) -class ZfsDatasets(FactBase): +class ZfsDatasets(ShellFact): @override def requires_command(self) -> str: return "zfs" @@ -57,7 +57,7 @@ def process(self, output): return _process_zfs_props_table(output) -class ZfsFilesystems(ShortFactBase): +class ZfsFilesystems(ShortcutFact): fact = ZfsDatasets @override @@ -65,7 +65,7 @@ def process_data(self, data): return {name: props for name, props in data.items() if props.get("type") == "filesystem"} -class ZfsSnapshots(ShortFactBase): +class ZfsSnapshots(ShortcutFact): fact = ZfsDatasets @override @@ -73,7 +73,7 @@ def process_data(self, data): return {name: props for name, props in data.items() if props.get("type") == "snapshot"} -class ZfsVolumes(ShortFactBase): +class ZfsVolumes(ShortcutFact): fact = ZfsDatasets @override diff --git a/src/pyinfra/facts/zypper.py b/src/pyinfra/facts/zypper.py index f0ede9097..a7189b4cf 100644 --- a/src/pyinfra/facts/zypper.py +++ b/src/pyinfra/facts/zypper.py @@ -2,13 +2,13 @@ from typing_extensions import override -from pyinfra.api import FactBase +from pyinfra.api import ShellFact from .util import make_cat_files_command_with_markers from .util.packaging import REPO_FILENAME_MARKER, parse_zypper_repositories -class ZypperRepositories(FactBase): +class ZypperRepositories(ShellFact): """ Returns a list of installed zypper repositories: diff --git a/src/pyinfra/operations/util/__init__.py b/src/pyinfra/operations/util/__init__.py index a7c3aef0b..fa92d8807 100644 --- a/src/pyinfra/operations/util/__init__.py +++ b/src/pyinfra/operations/util/__init__.py @@ -4,7 +4,7 @@ from pyinfra.context import host if TYPE_CHECKING: - from pyinfra.api.facts import FactBase, ShortFactBase + from pyinfra.api.facts import FactCore from pyinfra.api.operation import OperationMeta @@ -16,11 +16,11 @@ def all_changed(*args: "OperationMeta") -> Callable[[], bool]: return lambda: all(meta.did_change() for meta in args) -def any_fact(*facts: type["FactBase"] | type["ShortFactBase"]) -> Callable[[], bool]: +def any_fact(*facts: type["FactCore"]) -> Callable[[], bool]: """Return a condition that is true when any zero-argument fact is truthy.""" return lambda: any(host.get_fact(fact) for fact in facts) -def all_fact(*facts: type["FactBase"] | type["ShortFactBase"]) -> Callable[[], bool]: +def all_fact(*facts: type["FactCore"]) -> Callable[[], bool]: """Return a condition that is true when all zero-argument facts are truthy.""" return lambda: all(host.get_fact(fact) for fact in facts) diff --git a/src/pyinfra_cli/commands.py b/src/pyinfra_cli/commands.py index cb541f654..582f34e04 100644 --- a/src/pyinfra_cli/commands.py +++ b/src/pyinfra_cli/commands.py @@ -2,7 +2,7 @@ import json -from pyinfra.api.facts import FactBase +from pyinfra.api.facts import FactCore from .exceptions import CliError from .util import parse_cli_arg, try_import_module_attribute @@ -36,9 +36,9 @@ def get_func_and_args(commands): def get_facts_and_args(commands): - facts: list[tuple[FactBase, tuple, dict]] = [] + facts: list[tuple[FactCore, tuple, dict]] = [] - current_fact = None + current_fact: tuple[FactCore, tuple, dict] | None = None for command in commands: if "=" in command: diff --git a/tests/test_api/test_api_facts.py b/tests/test_api/test_api_facts.py index 552052cd6..5d7514224 100644 --- a/tests/test_api/test_api_facts.py +++ b/tests/test_api/test_api_facts.py @@ -1,11 +1,11 @@ -from typing import cast +from typing import cast, Any from unittest.mock import MagicMock, patch -from pyinfra.api import Config, State +from pyinfra.api import Config, Host, State, FactCore from pyinfra.api.arguments import CONNECTOR_ARGUMENT_KEYS, AllArguments, pop_global_arguments from pyinfra.api.connect import connect_all from pyinfra.api.exceptions import PyinfraError -from pyinfra.api.facts import get_facts +from pyinfra.api.facts import fact, get_facts from pyinfra.connectors.util import CommandOutput, OutputLine from pyinfra.context import ctx_host, ctx_state from pyinfra.facts.server import Arch, Command @@ -421,3 +421,219 @@ def test_get_host_fact_sudo_no_args(self): print_output=False, **defaults, ) + + +class TestHostDecoratorFactsApi(PatchSSHTestCase): + def test_simple_fact(self): + fake_value = MagicMock(name="fake_value") + + @fact() + def simple_fact(): + return fake_value + + assert _host_get_fact(simple_fact) is fake_value + + def test_fact_with_arg(self): + fake_arg = MagicMock(name="fake_arg") + + @fact() + def fact_with_arg(arg1): + return arg1 + + assert _host_get_fact(fact_with_arg, fake_arg) is fake_arg + assert _host_get_fact(fact_with_arg, arg1=fake_arg) is fake_arg + + @fact() + def fact_with_positional_arg(arg1, /): + return arg1 + + assert _host_get_fact(fact_with_positional_arg, fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_positional_arg, arg1=fake_arg) + + @fact() + def fact_with_keyword_arg(*, arg1): + return arg1 + + assert _host_get_fact(fact_with_keyword_arg, arg1=fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_keyword_arg, fake_arg) + + def test_decorator_fact_with_host(self): + fake_arg = MagicMock(name="fake_arg") + + @fact() + def simple_fact(host): + assert isinstance(host, Host) + return fake_arg + + assert _host_get_fact(simple_fact) is fake_arg + + @fact() + def fact_with_arg(host, arg1): + assert isinstance(host, Host) + return arg1 + + assert _host_get_fact(fact_with_arg, fake_arg) is fake_arg + assert _host_get_fact(fact_with_arg, arg1=fake_arg) is fake_arg + + @fact() + def fact_with_positional_arg(host, arg1, /): + assert isinstance(host, Host) + return arg1 + + assert _host_get_fact(fact_with_positional_arg, fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_positional_arg, arg1=fake_arg) + + @fact() + def fact_with_keyword_arg(host, *, arg1): + assert isinstance(host, Host) + return arg1 + + assert _host_get_fact(fact_with_keyword_arg, arg1=fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_keyword_arg, fake_arg) + + @fact() + def fact_with_positional_arg_not_first(arg1, host, /): + assert isinstance(host, Host) + return arg1 + + assert _host_get_fact(fact_with_positional_arg_not_first, fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_positional_arg_not_first, arg1=fake_arg) + + @fact() + def fact_with_keyword_host(*, arg1, host): + assert isinstance(host, Host) + return arg1 + + assert _host_get_fact(fact_with_keyword_host, arg1=fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_keyword_host, fake_arg) + + def test_decorator_fact_with_state(self): + fake_arg = MagicMock(name="fake_arg") + + @fact() + def simple_fact(state): + assert isinstance(state, State) + return fake_arg + + assert _host_get_fact(simple_fact) is fake_arg + + @fact() + def fact_with_arg(state, arg1): + assert isinstance(state, State) + return arg1 + + assert _host_get_fact(fact_with_arg, fake_arg) is fake_arg + assert _host_get_fact(fact_with_arg, arg1=fake_arg) is fake_arg + + @fact() + def fact_with_positional_arg(state, arg1, /): + assert isinstance(state, State) + return arg1 + + assert _host_get_fact(fact_with_positional_arg, fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_positional_arg, arg1=fake_arg) + + @fact() + def fact_with_keyword_arg(state, *, arg1): + assert isinstance(state, State) + return arg1 + + assert _host_get_fact(fact_with_keyword_arg, arg1=fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_keyword_arg, fake_arg) + + @fact() + def fact_with_positional_state_not_first(arg1, state, /): + assert isinstance(state, State) + return arg1 + + assert _host_get_fact(fact_with_positional_state_not_first, fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_positional_state_not_first, arg1=fake_arg) + + @fact() + def fact_with_keyword_state(*, arg1, state): + assert isinstance(state, State) + return arg1 + + assert _host_get_fact(fact_with_keyword_state, arg1=fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_keyword_state, fake_arg) + + def test_decorator_fact_with_state_and_host(self): + fake_arg = MagicMock(name="fake_arg") + + @fact() + def simple_fact(state, host): + assert isinstance(state, State) + assert isinstance(host, Host) + return fake_arg + + assert _host_get_fact(simple_fact) is fake_arg + + @fact() + def simple_fact_swapped(host, state): + assert isinstance(state, State) + assert isinstance(host, Host) + return fake_arg + + assert _host_get_fact(simple_fact_swapped) is fake_arg + + @fact() + def simple_fact_positional(state, host, /): + assert isinstance(state, State) + assert isinstance(host, Host) + return fake_arg + + assert _host_get_fact(simple_fact_positional) is fake_arg + + @fact() + def simple_fact_positional_swapped(host, state, /): + assert isinstance(state, State) + assert isinstance(host, Host) + return fake_arg + + assert _host_get_fact(simple_fact_positional_swapped) is fake_arg + + @fact() + def simple_fact_keyword(*, state, host): + assert isinstance(state, State) + assert isinstance(host, Host) + return fake_arg + + assert _host_get_fact(simple_fact_keyword) is fake_arg + + @fact() + def fact_with_arg_mixed(host, arg1, state): + assert isinstance(state, State) + assert isinstance(host, Host) + return arg1 + + assert _host_get_fact(fact_with_arg_mixed, fake_arg) is fake_arg + assert _host_get_fact(fact_with_arg_mixed, arg1=fake_arg) is fake_arg + + @fact() + def fact_with_arg_mixed_positional(host, arg1, state, /): + assert isinstance(state, State) + assert isinstance(host, Host) + return arg1 + + assert _host_get_fact(fact_with_arg_mixed_positional, fake_arg) is fake_arg + with self.assertRaises(TypeError): + _host_get_fact(fact_with_arg_mixed_positional, arg1=fake_arg) + + +def _host_get_fact(simple_fact: FactCore[Any], *args, **kwargs) -> Any: + inventory = make_inventory(hosts=("host-1",)) + state = State(inventory, Config()) + connect_all(state) + host_1 = inventory.get_host("host-1") + + return host_1.get_fact(simple_fact, *args, **kwargs) diff --git a/tests/test_api/test_api_facts_decorator.py b/tests/test_api/test_api_facts_decorator.py new file mode 100644 index 000000000..338cc12cb --- /dev/null +++ b/tests/test_api/test_api_facts_decorator.py @@ -0,0 +1,175 @@ +from inspect import isclass +from unittest import mock +import unittest + +from pyinfra.api.facts import FactCore, fact + + +class TestFactDecorator(unittest.TestCase): + def test_fact_metadata(self): + @fact() + def basic_fact() -> str: + """A simple test fact""" + return "hello" + + assert "abstract" in basic_fact.__dict__ + assert basic_fact.abstract is False + assert basic_fact.name == f"{self.__module__}.basic_fact" + assert basic_fact.__name__ == "basic_fact" + assert basic_fact.__module__ == self.__module__ + assert basic_fact.__doc__ == "A simple test fact" + assert isclass(basic_fact) + assert issubclass(basic_fact, FactCore) + + def test_default_default_is_None(self): + @fact() + def fact_without_default() -> str: + return "hello" + + assert fact_without_default.default() is None + + def test_default_value(self): + @fact(default_value="world") + def fact_with_default() -> str: + return "hello" + + assert fact_with_default.default() == "world" + + def test_function_is_called_with_host_and_state(self): + fake_state = mock.MagicMock(name="fake_state") + fake_host = mock.MagicMock(name="fake_host") + + @fact() + def fact_with_host_and_state(host, state) -> str: + assert host is fake_host + assert state is fake_state + return "hello" + + assert fact_with_host_and_state.get(state=fake_state, host=fake_host) == "hello" + assert ( + fact_with_host_and_state.get( + fake_state, + fake_host, + ) + == "hello" + ) + with self.assertRaises(TypeError): + fact_with_host_and_state.get(fake_state, fake_host, ["ignored_positional_arg"]) + with self.assertRaises(TypeError): + fact_with_host_and_state.get( + fake_state, fake_host, [], {"ignored_keyword_arg": "ignored_value"} + ) + + def test_function_is_passed_args(self): + fake_state = mock.MagicMock(name="fake_state") + fake_host = mock.MagicMock(name="fake_host") + fake_arg = mock.MagicMock(name="fake_arg") + + @fact() + def fact_with_positional_arg(test_arg) -> str: + assert test_arg is fake_arg + return "hello" + + assert fact_with_positional_arg.get(fake_state, fake_host, [fake_arg]) == "hello" + with self.assertRaises(TypeError): + assert ( + fact_with_positional_arg.get( + fake_state, + fake_host, + ) + == "hello" + ) + with self.assertRaises(TypeError): + assert ( + fact_with_positional_arg.get(fake_state, fake_host, [fake_arg, fake_arg]) == "hello" + ) + + def test_function_is_passed_kwargs(self): + fake_state = mock.MagicMock(name="fake_state") + fake_host = mock.MagicMock(name="fake_host") + fake_arg = mock.MagicMock(name="fake_arg") + + @fact() + def fact_with_keyword_arg(*, test_arg) -> str: + assert test_arg is fake_arg + return "hello" + + assert ( + fact_with_keyword_arg.get(fake_state, fake_host, kwargs={"test_arg": fake_arg}) + == "hello" + ) + with self.assertRaises(TypeError): + assert ( + fact_with_keyword_arg.get( + fake_state, + fake_host, + ) + == "hello" + ) + with self.assertRaises(TypeError): + assert ( + fact_with_keyword_arg.get(fake_state, fake_host, kwargs={"unknown_arg": fake_arg}) + == "hello" + ) + with self.assertRaises(TypeError): + assert ( + fact_with_keyword_arg.get( + fake_state, fake_host, kwargs={"test_arg": fake_arg, "unknown_arg": fake_arg} + ) + == "hello" + ) + + def test_function_returns_none(self): + fake_state = mock.MagicMock(name="fake_state") + fake_host = mock.MagicMock(name="fake_host") + + @fact() + def fact_that_returns_none() -> None: + return None + + result = fact_that_returns_none.get(fake_state, fake_host) + assert result is None + + def test_function_raises_exception(self): + fake_state = mock.MagicMock(name="fake_state") + fake_host = mock.MagicMock(name="fake_host") + + @fact() + def fact_that_raises() -> None: + raise Exception("test") + + try: + fact_that_raises.get(fake_state, fake_host) + assert False, "Exception was not raised" + except Exception as e: + assert str(e) == "test" + + def test_result_is_not_cached(self): + fake_state = mock.MagicMock(name="fake_state") + fake_host = mock.MagicMock(name="fake_host") + + current_result = 0 + + @fact() + def fact_that_returns_changing_value() -> int: + nonlocal current_result + current_result += 1 + return current_result + + assert 1 == fact_that_returns_changing_value.get(fake_state, fake_host) + assert 2 == fact_that_returns_changing_value.get(fake_state, fake_host) + + def test_client_cannot_provide_state_or_host_arg(self): + fake_state = mock.MagicMock(name="fake_state") + fake_host = mock.MagicMock(name="fake_host") + fake_arg = mock.MagicMock(name="fake_arg") + + @fact() + def fact_with_state_and_host(state, host): + assert state is fake_state + assert host is fake_host + + with self.assertRaises(TypeError): + fact_with_state_and_host.get(fake_state, fake_host, kwargs={"state": fake_arg}) + with self.assertRaises(TypeError): + fact_with_state_and_host.get(fake_state, fake_host, kwargs={"host": fake_arg}) diff --git a/tests/test_api/test_api_facts_missing_command.py b/tests/test_api/test_api_facts_missing_command.py index 3ee8070aa..f3ede652d 100644 --- a/tests/test_api/test_api_facts_missing_command.py +++ b/tests/test_api/test_api_facts_missing_command.py @@ -13,7 +13,7 @@ from unittest.mock import MagicMock, patch from pyinfra.api.exceptions import FactError, FactNotCollected, MissingCommandError -from pyinfra.api.facts import _MISSING_COMMAND_MARKER, get_fact +from pyinfra.api.facts import _MISSING_COMMAND_MARKER from pyinfra.facts.zfs import ZfsPools @@ -31,8 +31,10 @@ def test_prepare_phase_returns_default(self): state = _make_state(is_executing=False) host = MagicMock() - with patch("pyinfra.api.facts._get_fact", side_effect=MissingCommandError("zpool")): - result = get_fact(state, host, ZfsPools) + with patch( + "pyinfra.api.facts.ShellFact._get_fact", side_effect=MissingCommandError("zpool") + ): + result = ZfsPools.get(state, host) assert result == ZfsPools().default() @@ -42,8 +44,10 @@ def test_execute_phase_returns_default_with_warning(self): state = _make_state(is_executing=True) host = MagicMock() - with patch("pyinfra.api.facts._get_fact", side_effect=MissingCommandError("zpool")): - result = get_fact(state, host, ZfsPools) + with patch( + "pyinfra.api.facts.ShellFact._get_fact", side_effect=MissingCommandError("zpool") + ): + result = ZfsPools.get(state, host) assert result == ZfsPools().default() diff --git a/tests/test_api/test_api_facts_preconditions.py b/tests/test_api/test_api_facts_preconditions.py index e7f233f21..59fdef303 100644 --- a/tests/test_api/test_api_facts_preconditions.py +++ b/tests/test_api/test_api_facts_preconditions.py @@ -14,7 +14,7 @@ from unittest.mock import MagicMock, patch from pyinfra.api.exceptions import FactError, FactNotCollected, FactPreconditionError -from pyinfra.api.facts import FactBase, get_fact +from pyinfra.api.facts import ShellFact from pyinfra.connectors.util import CommandOutput, OutputLine from pyinfra.facts.zfs import ZfsPools @@ -34,10 +34,10 @@ def test_prepare_phase_returns_default(self): host = MagicMock() with patch( - "pyinfra.api.facts._get_fact", + "pyinfra.api.facts.ShellFact._get_fact", side_effect=FactPreconditionError(ZfsPools, "zfs module not loaded"), ): - result = get_fact(state, host, ZfsPools) + result = ZfsPools.get(state, host) assert result == ZfsPools().default() @@ -47,11 +47,11 @@ def test_execute_phase_raises(self): host = MagicMock() with patch( - "pyinfra.api.facts._get_fact", + "pyinfra.api.facts.ShellFact._get_fact", side_effect=FactPreconditionError(ZfsPools, "zfs module not loaded"), ): with self.assertRaises(FactPreconditionError) as ctx: - get_fact(state, host, ZfsPools) + ZfsPools.get(state, host) assert ctx.exception.fact_cls is ZfsPools assert "zfs module not loaded" in ctx.exception.reason @@ -69,7 +69,7 @@ def test_precondition_error_inherits_fact_not_collected(self): assert isinstance(exc, FactError) -class _AsksAboutAProject(FactBase): +class _AsksAboutAProject(ShellFact): """ A fact whose precondition needs the argument the fact was asked about. @@ -90,7 +90,7 @@ def process(self, output): return {} -class _Parameterless(FactBase): +class _Parameterless(ShellFact): """A fact written the old way, with a precondition that takes nothing.""" default = str @@ -120,7 +120,7 @@ def _run(self, fact_cls, fact_kwargs): host.run_shell_command.return_value = (True, CommandOutput([OutputLine("stdout", "[]")])) with patch("pyinfra.api.facts._handle_fact_kwargs", return_value=(fact_kwargs, {})): - return get_fact(state, host, fact_cls) + return fact_cls.get(state, host) def test_a_fact_is_told_which_arguments_it_was_asked_about(self): _AsksAboutAProject.seen = {} diff --git a/tests/typing/invalid/fact_command_return.py b/tests/typing/invalid/fact_command_return.py index 0fd9c7a31..ac9bd3ea0 100644 --- a/tests/typing/invalid/fact_command_return.py +++ b/tests/typing/invalid/fact_command_return.py @@ -1,11 +1,11 @@ -from pyinfra.api import FactBase +from pyinfra.api import ShellFact -class ReturnsInt(FactBase[str]): +class ReturnsInt(ShellFact[str]): def command(self) -> int: return 1 -class ReturnsOptional(FactBase[str]): +class ReturnsOptional(ShellFact[str]): def command(self, path: str) -> str | None: return None diff --git a/tests/typing/valid/fact_command.py b/tests/typing/valid/fact_command.py index 188ab5ea6..656b32713 100644 --- a/tests/typing/valid/fact_command.py +++ b/tests/typing/valid/fact_command.py @@ -1,22 +1,22 @@ -from pyinfra.api import FactBase, StringCommand +from pyinfra.api import ShellFact, StringCommand -class NoArgs(FactBase[str]): +class NoArgs(ShellFact[str]): def command(self) -> str: return "hostname" -class PositionalArgs(FactBase[str]): +class PositionalArgs(ShellFact[str]): def command(self, path: str, depth: int | None = None) -> StringCommand: return StringCommand("find", path) -class KeywordOnlyArgs(FactBase[str]): +class KeywordOnlyArgs(ShellFact[str]): def command(self, *, path: str) -> str | StringCommand: return path -class Static(FactBase[str]): +class Static(ShellFact[str]): @staticmethod def command(path: str) -> str: return path diff --git a/tests/typing/valid/public_imports.py b/tests/typing/valid/public_imports.py index 0e505ff52..3a8efb8ae 100644 --- a/tests/typing/valid/public_imports.py +++ b/tests/typing/valid/public_imports.py @@ -6,6 +6,7 @@ Config, DeployError, FactBase, + FactCore, FactError, FactNotCollected, FactPreconditionError, @@ -26,19 +27,22 @@ OperationValueError, QuoteString, RsyncCommand, + ShellFact, + ShortcutFact, ShortFactBase, State, StringCommand, deploy, + fact, operation, ) from pyinfra.connectors.scp import SCPClient from pyinfra.connectors.sshuserclient import SSHClient print(__version__, config, host, inventory, state) -print(BaseStateCallback, Config, DeployError, FactBase, FactError, FactNotCollected) +print(BaseStateCallback, Config, DeployError, FactBase, FactCore, FactError, FactNotCollected) print(FactPreconditionError, FactProcessError, FactTypeError, FactValueError) print(FileDownloadCommand, FileUploadCommand, FunctionCommand, HiddenValue, Host) print(Inventory, InventoryError, MaskString, MissingCommandError, OperationError) -print(OperationTypeError, OperationValueError, QuoteString, RsyncCommand) -print(ShortFactBase, State, StringCommand, deploy, operation, SCPClient, SSHClient) +print(OperationTypeError, OperationValueError, QuoteString, RsyncCommand, ShellFact, ShortcutFact) +print(ShortFactBase, State, StringCommand, deploy, fact, operation, SCPClient, SSHClient)