| 1 |
# Copyright: (c) 2021, Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import collections.abc as _c |
| 7 |
import os |
| 8 |
import pathlib |
| 9 |
import subprocess |
| 10 |
import sys |
| 11 |
import typing as t |
| 12 |
|
| 13 |
from ansible.module_utils.common.text.converters import to_bytes |
| 14 |
from ansible.module_utils._internal._ansiballz import _respawn |
| 15 |
|
| 16 |
_ANSIBLE_PARENT_PATH = pathlib.Path(__file__).parents[3] |
| 17 |
|
| 18 |
|
| 19 |
def has_respawned(): |
| 20 |
return hasattr(sys.modules['__main__'], '_respawned') |
| 21 |
|
| 22 |
|
| 23 |
def respawn_module(interpreter_path) -> t.NoReturn: |
| 24 |
""" |
| 25 |
Respawn the currently-running Ansible Python module under the specified Python interpreter. |
| 26 |
|
| 27 |
Ansible modules that require libraries that are typically available only under well-known interpreters |
| 28 |
(eg, ``apt``, ``dnf``) can use bespoke logic to determine the libraries they need are not |
| 29 |
available, then call `respawn_module` to re-execute the current module under a different interpreter |
| 30 |
and exit the current process when the new subprocess has completed. The respawned process inherits only |
| 31 |
stdout/stderr from the current process. |
| 32 |
|
| 33 |
Only a single respawn is allowed. ``respawn_module`` will fail on nested respawns. Modules are encouraged |
| 34 |
to call `has_respawned()` to defensively guide behavior before calling ``respawn_module``, and to ensure |
| 35 |
that the target interpreter exists, as ``respawn_module`` will not fail gracefully. |
| 36 |
|
| 37 |
:arg interpreter_path: path to a Python interpreter to respawn the current module |
| 38 |
""" |
| 39 |
|
| 40 |
if has_respawned(): |
| 41 |
raise Exception('module has already been respawned') |
| 42 |
|
| 43 |
# FUTURE: we need a safe way to log that a respawn has occurred for forensic/debug purposes |
| 44 |
payload = _respawn.create_payload() |
| 45 |
stdin_read, stdin_write = os.pipe() |
| 46 |
os.write(stdin_write, to_bytes(payload)) |
| 47 |
os.close(stdin_write) |
| 48 |
rc = subprocess.call([interpreter_path, '--'], stdin=stdin_read) |
| 49 |
sys.exit(rc) # pylint: disable=ansible-bad-function |
| 50 |
|
| 51 |
|
| 52 |
def get_env_with_pythonpath() -> dict[str, str]: |
| 53 |
""" |
| 54 |
Get an environment dict with PYTHONPATH set for Ansible library imports. |
| 55 |
|
| 56 |
Sets PYTHONPATH to include the Ansible library root so modules can be |
| 57 |
imported via 'python -m ansible.module_utils.X' even when running from |
| 58 |
a zipfile (ansiballz). |
| 59 |
|
| 60 |
:returns: dict suitable for passing to subprocess as env parameter |
| 61 |
""" |
| 62 |
pythonpath = os.getenv('PYTHONPATH', '') |
| 63 |
|
| 64 |
env = os.environ.copy() |
| 65 |
env.update({ |
| 66 |
'PYTHONPATH': f'{_ANSIBLE_PARENT_PATH}:{pythonpath}'.rstrip(': ') |
| 67 |
}) |
| 68 |
|
| 69 |
return env |
| 70 |
|
| 71 |
|
| 72 |
def probe_interpreters_for_module( |
| 73 |
interpreter_paths: _c.Sequence[str], |
| 74 |
module_name: str | None = None, |
| 75 |
*, |
| 76 |
module_names: list[str] | None = None, |
| 77 |
env: dict[str, str] | None = None, |
| 78 |
) -> str | None: |
| 79 |
""" |
| 80 |
Probes a supplied list of Python interpreters, returning the first one capable of |
| 81 |
importing the named modules. This is useful when attempting to locate a "system |
| 82 |
Python" where OS-packaged utility modules are located. |
| 83 |
|
| 84 |
FIXME environment description (do we want the utility method and/or stored location?) |
| 85 |
FIXME: describe module_name includes basic |
| 86 |
""" |
| 87 |
if env is None: |
| 88 |
env = get_env_with_pythonpath() # compatibility behavior |
| 89 |
|
| 90 |
if module_name is not None: |
| 91 |
if module_names: |
| 92 |
raise ValueError("The module_name and module_names arguments are mutually exclusive.") |
| 93 |
|
| 94 |
module_names = [module_name, 'ansible.module_utils.basic'] # compatibility behavior |
| 95 |
|
| 96 |
if not module_names: |
| 97 |
raise ValueError("No module names were specified.") |
| 98 |
|
| 99 |
modules_string = ", ".join(module_names) |
| 100 |
for interpreter_path in interpreter_paths: |
| 101 |
if not os.path.exists(interpreter_path): |
| 102 |
continue |
| 103 |
try: |
| 104 |
rc = subprocess.call( |
| 105 |
[ |
| 106 |
interpreter_path, |
| 107 |
'-c', |
| 108 |
f'import {modules_string}', |
| 109 |
], |
| 110 |
env=env, |
| 111 |
) |
| 112 |
if rc == 0: |
| 113 |
return interpreter_path |
| 114 |
except Exception: |
| 115 |
continue |
| 116 |
|
| 117 |
return None |