Debian Codegraph @

lib/ansible/executor/module_common.py

raw
1 # (c) 2013-2014, Michael DeHaan <[email protected]>
2 # (c) 2015 Toshio Kuratomi <[email protected]>
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18
19 from __future__ import annotations
20
21 import ast
22 import base64
23 import dataclasses
24 import datetime
25 import importlib.util as _importlib_util
26 import json
27 import os
28 import pathlib
29 import pickle
30 import shlex
31 import zipfile
32 import re
33 import pkgutil
34 import types
35 import typing as t
36
37 from ast import Assign, Constant, Import, ImportFrom, Name, Call, Attribute
38 from importlib.resources import files as ir_files
39 from io import BytesIO
40
41 from ansible._internal import _locking
42 from ansible._internal._ansiballz import _builder
43 from ansible._internal import _ansiballz
44 from ansible._internal._datatag import _utils
45 from ansible._internal._powershell import _clixml, _script as _ps_script
46 from ansible.module_utils._internal import _dataclass_validation
47 from ansible.module_utils.common.yaml import yaml_load
48 from ansible.module_utils.datatag import deprecator_from_collection_name
49 from ansible._internal._datatag._tags import Origin
50 from ansible.module_utils.common.json import Direction, get_module_encoder
51 from ansible.module_utils.embed import EmbeddedResource
52 from ansible.release import __version__, __author__
53 from ansible import constants as C
54 from ansible.errors import AnsibleError
55 from ansible.executor.interpreter_discovery import InterpreterDiscoveryRequiredError
56 from ansible.executor.powershell import module_manifest as ps_manifest
57 from ansible.module_utils.common.text.converters import to_bytes, to_text, to_native
58 from ansible.plugins.become import BecomeBase
59 from ansible.plugins.loader import module_utils_loader
60 from ansible._internal._templating._engine import TemplateOptions, TemplateEngine
61 from ansible.template import Templar
62 from ansible.utils.collection_loader._collection_finder import _get_collection_metadata, _nested_dict_get
63 from ansible.module_utils._internal import _json
64 from ansible.module_utils._internal._ansiballz import _loader
65 from ansible.module_utils import basic as _basic
66 from ansible.module_utils import secrets as _secrets
67
68 if t.TYPE_CHECKING:
69 from ansible import template as _template
70 from ansible.playbook.task import Task
71
72 from ansible.utils.display import Display
73
74 import importlib.util
75 import importlib.machinery
76
77 display = Display()
78
79
80 @dataclasses.dataclass(frozen=True, order=True)
81 class _ModuleUtilsProcessEntry:
82 """Represents a module/module_utils item awaiting import analysis."""
83 name_parts: tuple[str, ...]
84 is_ambiguous: bool = False
85 child_is_redirected: bool = False
86 is_optional: bool = False
87
88 @classmethod
89 def from_module(cls, module: types.ModuleType, append: str | None = None) -> t.Self:
90 name = module.__name__
91
92 if append:
93 name += '.' + append
94
95 return cls.from_module_name(name)
96
97 @classmethod
98 def from_module_name(cls, module_name: str) -> t.Self:
99 return cls(tuple(module_name.split('.')))
100
101
102 REPLACER = b"#<<INCLUDE_ANSIBLE_MODULE_COMMON>>"
103 REPLACER_VERSION = b"\"<<ANSIBLE_VERSION>>\""
104 REPLACER_COMPLEX = b"\"<<INCLUDE_ANSIBLE_MODULE_COMPLEX_ARGS>>\""
105 REPLACER_WINDOWS = b"# POWERSHELL_COMMON"
106 REPLACER_JSONARGS = b"<<INCLUDE_ANSIBLE_MODULE_JSON_ARGS>>"
107 REPLACER_SELINUX = b"<<SELINUX_SPECIAL_FILESYSTEMS>>"
108
109 # module_common is relative to module_utils, so fix the path
110 _MODULE_UTILS_PATH = os.path.join(os.path.dirname(__file__), '..', 'module_utils')
111 _SHEBANG_PLACEHOLDER = '# shebang placeholder'
112
113 # ******************************************************************************
114
115
116 def _strip_comments(source: str) -> str:
117 # Strip comments and blank lines from the wrapper
118 buf = []
119 for line in source.splitlines():
120 l = line.strip()
121 if (not l or l.startswith('#')) and l != _SHEBANG_PLACEHOLDER:
122 line = ''
123 buf.append(line)
124 return '\n'.join(buf)
125
126
127 def _read_ansiballz_code() -> str:
128 code = (pathlib.Path(_ansiballz.__file__).parent / '_wrapper.py').read_text()
129
130 if not C.DEFAULT_KEEP_REMOTE_FILES:
131 # Keep comments when KEEP_REMOTE_FILES is set. That way users will see
132 # the comments with some nice usage instructions.
133 # Otherwise, strip comments for smaller over the wire size.
134 code = _strip_comments(code)
135
136 return code
137
138
139 _ANSIBALLZ_CODE = _read_ansiballz_code() # read during startup to prevent individual workers from doing so
140
141
142 def _get_ansiballz_code(shebang: str) -> str:
143 code = _ANSIBALLZ_CODE
144 code = code.replace(_SHEBANG_PLACEHOLDER, shebang)
145
146 return code
147
148
149 # dirname(dirname(dirname(site-packages/ansible/executor/module_common.py) == site-packages
150 # Do this instead of getting site-packages from distutils.sysconfig so we work when we
151 # haven't been installed
152 site_packages = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
153 CORE_LIBRARY_PATH_RE = re.compile(r'%s/(?P<path>ansible/modules/.*)\.(py|ps1)$' % re.escape(site_packages))
154 COLLECTION_PATH_RE = re.compile(r'/(?P<path>ansible_collections/[^/]+/[^/]+/plugins/modules/.*)\.(py|ps1)$')
155
156 # Detect new-style Python modules by looking for required imports:
157 # import ansible_collections.[my_ns.my_col.plugins.module_utils.my_module_util]
158 # from ansible_collections.[my_ns.my_col.plugins.module_utils import my_module_util]
159 # import ansible.module_utils[.basic]
160 # from ansible.module_utils[ import basic]
161 # from ansible.module_utils[.basic import AnsibleModule]
162 # from ..module_utils[ import basic]
163 # from ..module_utils[.basic import AnsibleModule]
164 NEW_STYLE_PYTHON_MODULE_RE = re.compile(
165 # Relative imports
166 br'(?:from +\.{2,} *module_utils.* +import |'
167 # Collection absolute imports:
168 br'from +ansible_collections\.[^.]+\.[^.]+\.plugins\.module_utils.* +import |'
169 br'import +ansible_collections\.[^.]+\.[^.]+\.plugins\.module_utils.*|'
170 # Core absolute imports
171 br'from +ansible\.module_utils.* +import |'
172 br'import +ansible\.module_utils\.)'
173 )
174
175
176 class ModuleDepFinder(ast.NodeVisitor):
177 # DTFIX-FUTURE: add support for ignoring imports with a "controller only" comment, this will allow replacing import_controller_module with standard imports
178 def __init__(self, module_fqn: str, module_data: bytes, is_pkg_init=False, *args, **kwargs):
179 """
180 Walk the ast tree for the python module.
181 :arg module_fqn: The fully qualified name to reach this module in dotted notation.
182 example: ansible.module_utils.basic
183 :arg is_pkg_init: Inform the finder it's looking at a package init (eg __init__.py) to allow
184 relative import expansion to use the proper package level without having imported it locally first.
185
186 Save submodule[.submoduleN][.identifier] into self.submodules
187 when they are from ansible.module_utils or ansible_collections packages
188
189 self.submodules will end up with tuples like:
190 - ('ansible', 'module_utils', 'basic',)
191 - ('ansible', 'module_utils', 'urls', 'fetch_url')
192 - ('ansible', 'module_utils', 'database', 'postgres')
193 - ('ansible', 'module_utils', 'database', 'postgres', 'quote')
194 - ('ansible', 'module_utils', 'database', 'postgres', 'quote')
195 - ('ansible_collections', 'my_ns', 'my_col', 'plugins', 'module_utils', 'foo')
196
197 It's up to calling code to determine whether the final element of the
198 tuple are module names or something else (function, class, or variable names)
199 .. seealso:: :python3:class:`ast.NodeVisitor`
200 """
201 super(ModuleDepFinder, self).__init__(*args, **kwargs)
202 self.submodules: set[tuple[str, ...]] = set()
203 self.optional_imports: set[tuple[str, ...]] = set()
204 self.embeds: set[EmbeddedResource] = set()
205 self.module_fqn = module_fqn
206 self.is_pkg_init = is_pkg_init
207 self._depth = -1
208 self._origin = Origin.get_tag(module_data) or Origin.UNKNOWN
209 self.tree = _compile_module_ast(module_fqn, module_data)
210
211 self._embed_sniffing = False
212 self._embed_module_name = None
213 self._embedmanager_type_name = None
214 self._embed_import_origin: Origin | None = None
215
216 self.visit(self.tree)
217
218 if self._embed_sniffing and not self.embeds:
219 raise AnsibleError("Module embedding support was imported, but no EmbedManager.embed calls were found.", obj=self._embed_import_origin)
220
221 def generic_visit(self, node):
222 """Overridden ``generic_visit`` that makes some assumptions about our
223 use case, and improves performance by calling visitors directly instead
224 of calling ``visit`` to offload calling visitors.
225 """
226 self._depth += 1
227 depth = self._depth
228 generic_visit = self.generic_visit
229 visit_Assign = self.visit_Assign
230 visit_Import = self.visit_Import
231 visit_ImportFrom = self.visit_ImportFrom
232 for field, value in ast.iter_fields(node):
233 if value.__class__ is list:
234 for item in value:
235 item_class = item.__class__
236 if item_class is Import:
237 visit_Import(item)
238 elif item_class is ImportFrom:
239 visit_ImportFrom(item)
240 elif not depth and item_class is Assign:
241 if not self._embed_sniffing:
242 continue # if the module hasn't imported the `embed` module_utils module, skip assignment analysis
243
244 visit_Assign(item)
245 elif hasattr(item, 'end_col_offset'):
246 # ASTish without the hit of isinstance
247 generic_visit(item)
248 self._depth -= 1
249
250 visit = generic_visit
251
252 def visit_Import(self, node):
253 """
254 Handle import ansible.module_utils.MODLIB[.MODLIBn] [as asname]
255
256 We save these as interesting submodules when the imported library is in ansible.module_utils
257 or ansible.collections
258 """
259 depth = self._depth
260 submodules_add = self.submodules.add
261 optional_imports_add = self.optional_imports.add
262 for alias in node.names:
263 aname = alias.name
264 if aname.startswith(('ansible.module_utils.', 'ansible_collections.')):
265 py_mod = tuple(aname.split('.'))
266 submodules_add(py_mod)
267 # if the import's parent is the root document, it's a required import, otherwise it's optional
268 if depth:
269 optional_imports_add(py_mod)
270
271 def visit_ImportFrom(self, node):
272 """
273 Handle from ansible.module_utils.MODLIB import [.MODLIBn] [as asname]
274
275 Also has to handle relative imports.
276
277 We save these as interesting submodules when the imported library is in ansible.module_utils
278 or ansible.collections.
279
280 If the module imports `ansible.module_utils.embed`, assignment analysis is enabled for static resource embedding via EmbedManager.embed().
281 """
282 # FIXME: These should all get skipped:
283 # from ansible.executor import module_common
284 # from ...executor import module_common
285 # from ... import executor (Currently it gives a non-helpful error)
286
287 depth = self._depth
288 module_fqn = self.module_fqn
289 submodules_add = self.submodules.add
290 optional_imports_add = self.optional_imports.add
291
292 node_level = node.level
293 module = node.module
294
295 if node_level > 0:
296 # if we're in a package init, we have to add one to the node level (and make it none if 0 to preserve the right slicing behavior)
297 level_slice_offset = -node_level + 1 or None if self.is_pkg_init else -node_level
298 if module_fqn:
299 parts = tuple(module_fqn.split('.'))
300 if module:
301 # relative import: from .module import x
302 node_module = '.'.join(parts[:level_slice_offset] + (module,))
303 else:
304 # relative import: from . import x
305 node_module = '.'.join(parts[:level_slice_offset])
306 else:
307 # fall back to an absolute import
308 node_module = module
309 else:
310 # absolute import: from module import x
311 node_module = module
312
313 # Specialcase: six is a special case because of its
314 # import logic
315 py_mod = None
316 if node.names[0].name == '_six':
317 submodules_add(('_six',))
318 elif node_module.startswith('ansible.module_utils'):
319 # from ansible.module_utils.MODULE1[.MODULEn] import IDENTIFIER [as asname]
320 # from ansible.module_utils.MODULE1[.MODULEn] import MODULEn+1 [as asname]
321 # from ansible.module_utils.MODULE1[.MODULEn] import MODULEn+1 [,IDENTIFIER] [as asname]
322 # from ansible.module_utils import MODULE1 [,MODULEn] [as asname]
323 py_mod = tuple(node_module.split('.'))
324
325 elif node_module.startswith('ansible_collections.'):
326 if node_module.endswith('plugins.module_utils') or '.plugins.module_utils.' in node_module:
327 # from ansible_collections.ns.coll.plugins.module_utils import MODULE [as aname] [,MODULE2] [as aname]
328 # from ansible_collections.ns.coll.plugins.module_utils.MODULE import IDENTIFIER [as aname]
329 # FIXME: Unhandled cornercase (needs to be ignored):
330 # from ansible_collections.ns.coll.plugins.[!module_utils].[FOO].plugins.module_utils import IDENTIFIER
331 py_mod = tuple(node_module.split('.'))
332 else:
333 # Not from module_utils so ignore. for instance:
334 # from ansible_collections.ns.coll.plugins.lookup import IDENTIFIER
335 pass
336
337 if py_mod:
338 for alias in node.names:
339 submodules_add(a_py_mod := py_mod + (alias.name,))
340 # if the import's parent is the root document, it's a required import, otherwise it's optional
341 if depth:
342 optional_imports_add(a_py_mod)
343 elif alias.name == 'embed' and node_module == 'ansible.module_utils':
344 self._visit_embed_import(node_module, node, alias)
345 elif alias.name == 'EmbedManager' and node_module == 'ansible.module_utils.embed':
346 self._visit_embed_import(node_module, node, alias)
347
348 def _visit_embed_import(self, node_module_name: str, node: ast.ImportFrom, alias: ast.alias) -> None:
349 self._embed_sniffing = True
350
351 if node_module_name == 'ansible.module_utils':
352 # from ansible.module_utils import embed (as modulealias)
353 self._embed_module_name = alias.asname or alias.name
354 self._embedmanager_type_name = 'EmbedManager'
355 elif node_module_name == 'ansible.module_utils.embed':
356 # from ansible.module_utils.embed import EmbedManager as EmbedManagerAlias
357 self._embed_module_name = None
358 self._embedmanager_type_name = alias.asname or alias.name
359
360 self._embed_import_origin = self._origin.replace(line_num=node.lineno, col_num=node.col_offset + 1)
361
362 def _assert_embed(self, assertion: bool, message: str, node: ast.stmt | ast.expr) -> None:
363 """
364 If the required `EmbedManager` pre-condition `assertion` is False, raise an `AnsibleError` that includes the specified `message`
365 and the most-specific `obj` context available from `node`.
366 """
367 if not assertion:
368 raise AnsibleError(
369 message=f"Invalid EmbedManager request: {message}.",
370 obj=self._origin.replace(line_num=node.lineno, col_num=node.col_offset + 1)
371 )
372
373 def visit_Assign(self, node: ast.Assign) -> None:
374 """
375 Validate top-level calls to `EmbedManager.embed` to include the requested resources and collect them in `embeds`.
376
377 All calls must be of the form `var = (embed.)EmbedManager.embed(...)`.
378 Optional import-time aliases for the `embed` module or `EmbedManager` type are supported.
379
380 The `embed` callsite requires exactly two inline literal string posargs; any other form will fail the module build.
381 If the `package` argument starts with `.`, it is assumed to be a relative import path from the calling Python module.
382 """
383 if not isinstance(call := node.value, Call) or not isinstance(func := call.func, Attribute) or func.attr != 'embed':
384 return # bail - an assignment whose RHS is not a function call to (something).embed()
385
386 match func.value:
387 case Attribute(attr=self._embedmanager_type_name, value=Name(id=self._embed_module_name)):
388 pass # keep going - embed_module_or_alias.EmbedManagerOrAlias.embed()
389 case Name(id=self._embedmanager_type_name):
390 pass # keep going - EmbedManagerOrAlias.embed()
391 case _:
392 return # bail - an embed() call we're not interested in
393
394 # origin-tag the args with this callsite location so a later failure can point here
395 embed_origin = self._origin.replace(line_num=call.lineno, col_num=call.col_offset + 1)
396 call_posargs: list[str] = [embed_origin.tag(a.value) for a in call.args if isinstance(a, Constant) and isinstance(a.value, str)]
397
398 self._assert_embed(len(call_posargs) == len(call.args) == 2, message="Embed requires exactly two inline literal strings", node=call)
399 self._assert_embed(not call.keywords, message="Embed does not support keyword args", node=call)
400
401 if call_posargs[0].startswith('.'):
402 # resolve relative anchor reference
403 call_posargs[0] = embed_origin.tag(_importlib_util.resolve_name(call_posargs[0], self.module_fqn.rpartition('.')[0]))
404
405 self.embeds.add(EmbeddedResource(*call_posargs))
406
407
408 def _slurp(path):
409 if not os.path.exists(path):
410 raise AnsibleError("imported module support code does not exist at %s" % os.path.abspath(path))
411 with open(path, 'rb') as fd:
412 data = fd.read()
413 return data
414
415
416 def _get_shebang(
417 interpreter: str,
418 task_vars: dict[str, t.Any],
419 templar: _template.Templar,
420 args: tuple[str, ...] = tuple(),
421 remote_is_local: bool = False,
422 default_interpreters: dict[str, str] | None = None,
423 ) -> tuple[str, str]:
424 """
425 Handles the different ways ansible allows overriding the shebang target for a module.
426 """
427 # FUTURE: add logical equivalence for python3 in the case of py3-only modules
428
429 # For backwards compatibility we can adjust #!powershell using the pwsh
430 # interpreter vars.
431 if interpreter == 'powershell':
432 interpreter_name = 'pwsh'
433 else:
434 interpreter_name = os.path.basename(interpreter).strip()
435
436 # name for interpreter var
437 interpreter_config = u'ansible_%s_interpreter' % interpreter_name
438 # key for config
439 interpreter_config_key = "INTERPRETER_%s" % interpreter_name.upper()
440
441 interpreter_out: str | None = None
442
443 # looking for python, rest rely on matching vars
444 if interpreter_name == 'python':
445 # skip detection for network os execution, use playbook supplied one if possible
446 if remote_is_local:
447 interpreter_out = task_vars['ansible_playbook_python']
448
449 # a config def exists for this interpreter type; consult config for the value
450 elif C.config.get_configuration_definition(interpreter_config_key):
451
452 interpreter_from_config = C.config.get_config_value(interpreter_config_key, variables=task_vars)
453 interpreter_out = templar._engine.template(_utils.str_problematic_strip(interpreter_from_config),
454 options=TemplateOptions(value_for_omit=C.config.get_config_default(interpreter_config_key)))
455
456 # handle interpreter discovery if requested or empty interpreter was provided
457 if not interpreter_out or interpreter_out in ['auto', 'auto_silent']:
458
459 discovered_interpreter_config = u'discovered_interpreter_%s' % interpreter_name
460 facts_from_task_vars = task_vars.get('ansible_facts', {})
461
462 if discovered_interpreter_config not in facts_from_task_vars:
463 # interpreter discovery is desired, but has not been run for this host
464 raise InterpreterDiscoveryRequiredError("interpreter discovery needed", interpreter_name=interpreter_name, discovery_mode=interpreter_out)
465 else:
466 interpreter_out = facts_from_task_vars[discovered_interpreter_config]
467 else:
468 raise InterpreterDiscoveryRequiredError("interpreter discovery required", interpreter_name=interpreter_name, discovery_mode='auto')
469
470 elif interpreter_config in task_vars:
471 # for non python we consult vars for a possible direct override
472 interpreter_out = templar._engine.template(_utils.str_problematic_strip(task_vars.get(interpreter_config)),
473 options=TemplateOptions(value_for_omit=None))
474
475 if not interpreter_out:
476 # nothing matched(None) or in case someone configures empty string or empty interpreter
477 default_interpreters = default_interpreters or {}
478 interpreter_out = default_interpreters.get(interpreter, interpreter)
479
480 # set shebang
481 shebang = u'#!{0}'.format(interpreter_out)
482 if args:
483 shebang = shebang + u' ' + u' '.join(args)
484
485 return shebang, interpreter_out
486
487
488 class ModuleUtilLocatorBase:
489 def __init__(self, fq_name_parts, is_ambiguous=False, child_is_redirected=False, is_optional=False):
490 self._is_ambiguous = is_ambiguous
491 # a child package redirection could cause intermediate package levels to be missing, eg
492 # from ansible.module_utils.x.y.z import foo; if x.y.z.foo is redirected, we may not have packages on disk for
493 # the intermediate packages x.y.z, so we'll need to supply empty packages for those
494 self._child_is_redirected = child_is_redirected
495 self._is_optional = is_optional
496 self.found = False
497 self.redirected = False
498 self.fq_name_parts = fq_name_parts
499 self.source_code = b''
500 self.output_path = ''
501 self.is_package = False
502 self._collection_name = None
503 # for ambiguous imports, we should only test for things more than one level below module_utils
504 # this lets us detect erroneous imports and redirections earlier
505 if is_ambiguous and len(self._get_module_utils_remainder_parts(fq_name_parts)) > 1:
506 self.candidate_names = [fq_name_parts, fq_name_parts[:-1]]
507 else:
508 self.candidate_names = [fq_name_parts]
509
510 @property
511 def candidate_names_joined(self):
512 return ['.'.join(n) for n in self.candidate_names]
513
514 def _handle_redirect(self, name_parts):
515 module_utils_relative_parts = self._get_module_utils_remainder_parts(name_parts)
516
517 # only allow redirects from below module_utils- if above that, bail out (eg, parent package names)
518 if not module_utils_relative_parts:
519 return False
520
521 try:
522 collection_metadata = _get_collection_metadata(self._collection_name)
523 except ValueError as ve: # collection not found or some other error related to collection load
524 if self._is_optional:
525 return False
526 raise AnsibleError('error processing module_util {0} loading redirected collection {1}: {2}'
527 .format('.'.join(name_parts), self._collection_name, to_native(ve)))
528
529 routing_entry = _nested_dict_get(collection_metadata, ['plugin_routing', 'module_utils', '.'.join(module_utils_relative_parts)])
530 if not routing_entry:
531 return False
532 # FIXME: add deprecation warning support
533
534 dep_or_ts = routing_entry.get('tombstone')
535 removed = dep_or_ts is not None
536 if not removed:
537 dep_or_ts = routing_entry.get('deprecation')
538
539 if dep_or_ts:
540 removal_date = dep_or_ts.get('removal_date')
541 removal_version = dep_or_ts.get('removal_version')
542 warning_text = dep_or_ts.get('warning_text')
543
544 msg = 'module_util {0} has been removed'.format('.'.join(name_parts))
545 if warning_text:
546 msg += ' ({0})'.format(warning_text)
547 else:
548 msg += '.'
549
550 display.deprecated( # pylint: disable=ansible-deprecated-date-not-permitted,ansible-deprecated-unnecessary-collection-name
551 msg=msg,
552 version=removal_version,
553 removed=removed,
554 date=removal_date,
555 deprecator=deprecator_from_collection_name(self._collection_name),
556 )
557 if 'redirect' in routing_entry:
558 self.redirected = True
559 source_pkg = '.'.join(name_parts)
560 self.is_package = True # treat all redirects as packages
561 redirect_target_pkg = routing_entry['redirect']
562
563 # expand FQCN redirects
564 if not redirect_target_pkg.startswith('ansible_collections'):
565 split_fqcn = redirect_target_pkg.split('.')
566 if len(split_fqcn) < 3:
567 raise Exception('invalid redirect for {0}: {1}'.format(source_pkg, redirect_target_pkg))
568 # assume it's an FQCN, expand it
569 redirect_target_pkg = 'ansible_collections.{0}.{1}.plugins.module_utils.{2}'.format(
570 split_fqcn[0], # ns
571 split_fqcn[1], # coll
572 '.'.join(split_fqcn[2:]) # sub-module_utils remainder
573 )
574 display.vvv('redirecting module_util {0} to {1}'.format(source_pkg, redirect_target_pkg))
575 self.source_code = self._generate_redirect_shim_source(source_pkg, redirect_target_pkg)
576 return True
577 return False
578
579 def _get_module_utils_remainder_parts(self, name_parts):
580 # subclasses should override to return the name parts after module_utils
581 return []
582
583 def _get_module_utils_remainder(self, name_parts):
584 # return the remainder parts as a package string
585 return '.'.join(self._get_module_utils_remainder_parts(name_parts))
586
587 def _find_module(self, name_parts):
588 return False
589
590 def _locate(self, redirect_first=True):
591 for candidate_name_parts in self.candidate_names:
592 if redirect_first and self._handle_redirect(candidate_name_parts):
593 break
594
595 if self._find_module(candidate_name_parts):
596 break
597
598 if not redirect_first and self._handle_redirect(candidate_name_parts):
599 break
600
601 else: # didn't find what we were looking for- last chance for packages whose parents were redirected
602 if self._child_is_redirected: # make fake packages
603 self.is_package = True
604 self.source_code = b''
605 else: # nope, just bail
606 return
607
608 if self.is_package:
609 path_parts = candidate_name_parts + ('__init__',)
610 else:
611 path_parts = candidate_name_parts
612 self.found = True
613 self.output_path = os.path.join(*path_parts) + '.py'
614 self.fq_name_parts = candidate_name_parts
615
616 def _generate_redirect_shim_source(self, fq_source_module, fq_target_module) -> bytes:
617 return """
618 import sys
619 import {1} as mod
620
621 sys.modules['{0}'] = mod
622 """.format(fq_source_module, fq_target_module).encode()
623
624 # FIXME: add __repr__ impl
625
626
627 class LegacyModuleUtilLocator(ModuleUtilLocatorBase):
628 def __init__(self, fq_name_parts, is_ambiguous=False, mu_paths=None, child_is_redirected=False):
629 super(LegacyModuleUtilLocator, self).__init__(fq_name_parts, is_ambiguous, child_is_redirected)
630
631 if fq_name_parts[0:2] != ('ansible', 'module_utils'):
632 raise Exception('this class can only locate from ansible.module_utils, got {0}'.format(fq_name_parts))
633
634 if fq_name_parts[2] == 'six':
635 # FIXME: handle the ansible.module_utils.six._six case with a redirect or an internal _six attr on six itself?
636 # six creates its submodules at runtime; convert all these to just 'ansible.module_utils.six'
637 fq_name_parts = ('ansible', 'module_utils', 'six')
638 self.candidate_names = [fq_name_parts]
639
640 self._mu_paths = mu_paths
641 self._collection_name = 'ansible.builtin' # legacy module utils always look in ansible.builtin for redirects
642 self._locate(redirect_first=False) # let local stuff override redirects for legacy
643
644 def _get_module_utils_remainder_parts(self, name_parts):
645 return name_parts[2:] # eg, foo.bar for ansible.module_utils.foo.bar
646
647 def _find_module(self, name_parts):
648 rel_name_parts = self._get_module_utils_remainder_parts(name_parts)
649
650 # no redirection; try to find the module
651 if len(rel_name_parts) == 1: # direct child of module_utils, just search the top-level dirs we were given
652 paths = self._mu_paths
653 else: # a nested submodule of module_utils, extend the paths given with the intermediate package names
654 paths = [os.path.join(p, *rel_name_parts[:-1]) for p in
655 self._mu_paths] # extend the MU paths with the relative bit
656
657 # find_spec needs the full module name
658 self._info = info = importlib.machinery.PathFinder.find_spec('.'.join(name_parts), paths)
659 if info is not None and info.origin is not None and os.path.splitext(info.origin)[1] in importlib.machinery.SOURCE_SUFFIXES:
660 self.is_package = info.origin.endswith('/__init__.py')
661 path = info.origin
662 else:
663 return False
664 self.source_code = Origin(path=path).tag(_slurp(path))
665
666 return True
667
668
669 class CollectionModuleUtilLocator(ModuleUtilLocatorBase):
670 def __init__(self, fq_name_parts, is_ambiguous=False, child_is_redirected=False, is_optional=False):
671 super(CollectionModuleUtilLocator, self).__init__(fq_name_parts, is_ambiguous, child_is_redirected, is_optional)
672
673 if fq_name_parts[0] != 'ansible_collections':
674 raise Exception('CollectionModuleUtilLocator can only locate from ansible_collections, got {0}'.format(fq_name_parts))
675 elif len(fq_name_parts) >= 6 and fq_name_parts[3:5] != ('plugins', 'module_utils'):
676 raise Exception('CollectionModuleUtilLocator can only locate below ansible_collections.(ns).(coll).plugins.module_utils, got {0}'
677 .format(fq_name_parts))
678
679 self._collection_name = '.'.join(fq_name_parts[1:3])
680
681 self._locate()
682
683 def _find_module(self, name_parts):
684 # synthesize empty inits for packages down through module_utils- we don't want to allow those to be shipped over, but the
685 # package hierarchy needs to exist
686 if len(name_parts) < 6:
687 self.source_code = b''
688 self.is_package = True
689 return True
690
691 # NB: we can't use pkgutil.get_data safely here, since we don't want to import/execute package/module code on
692 # the controller while analyzing/assembling the module, so we'll have to manually import the collection's
693 # Python package to locate it (import root collection, reassemble resource path beneath, fetch source)
694
695 collection_pkg_name = '.'.join(name_parts[0:3])
696 resource_base_path = os.path.join(*name_parts[3:])
697
698 src = None
699
700 # look for package_dir first, then module
701 src_path = to_native(os.path.join(resource_base_path, '__init__.py'))
702
703 try:
704 collection_pkg = importlib.import_module(collection_pkg_name)
705 pkg_path = os.path.dirname(collection_pkg.__file__)
706 except (ImportError, AttributeError):
707 pkg_path = None
708
709 try:
710 src = pkgutil.get_data(collection_pkg_name, src_path)
711 except ImportError:
712 pass
713
714 # TODO: we might want to synthesize fake inits for py3-style packages, for now they're required beneath module_utils
715
716 if src is not None: # empty string is OK
717 self.is_package = True
718 else:
719 src_path = to_native(resource_base_path + '.py')
720
721 try:
722 src = pkgutil.get_data(collection_pkg_name, src_path)
723 except ImportError:
724 pass
725
726 if src is None: # empty string is OK
727 return False
728
729 # TODO: this feels brittle and funky; we should be able to more definitively assure the source path
730
731 if pkg_path:
732 origin = Origin(path=os.path.join(pkg_path, src_path))
733 else:
734 # DTFIX-FUTURE: not sure if this case is even reachable
735 origin = Origin(description=f'<synthetic collection package for {collection_pkg_name}!r>')
736
737 self.source_code = origin.tag(src)
738 return True
739
740 def _get_module_utils_remainder_parts(self, name_parts):
741 return name_parts[5:] # eg, foo.bar for ansible_collections.ns.coll.plugins.module_utils.foo.bar
742
743
744 def _make_zinfo(filename: str, date_time: datetime.datetime, zf: zipfile.ZipFile | None = None) -> zipfile.ZipInfo:
745 zinfo = zipfile.ZipInfo(
746 filename=filename,
747 date_time=date_time.utctimetuple()[:6],
748 )
749
750 if zf:
751 zinfo.compress_type = zf.compression
752
753 return zinfo
754
755
756 @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
757 class ModuleMetadata:
758 @classmethod
759 def __post_init__(cls):
760 _dataclass_validation.inject_post_init_validation(cls)
761
762
763 @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
764 class ModuleMetadataV1(ModuleMetadata):
765 serialization_profile: str
766
767
768 metadata_versions: dict[t.Any, type[ModuleMetadata]] = {
769 1: ModuleMetadataV1,
770 }
771
772 _DEFAULT_LEGACY_METADATA = ModuleMetadataV1(serialization_profile='legacy')
773
774
775 def _get_module_metadata(module: ast.Module) -> ModuleMetadata:
776 # experimental module metadata; off by default
777 if not C.config.get_config_value('_MODULE_METADATA'):
778 return _DEFAULT_LEGACY_METADATA
779
780 metadata_nodes: list[ast.Assign] = []
781
782 for node in module.body:
783 if isinstance(node, ast.Assign):
784 if len(node.targets) == 1:
785 target = node.targets[0]
786
787 if isinstance(target, ast.Name):
788 if target.id == 'METADATA':
789 metadata_nodes.append(node)
790
791 if not metadata_nodes:
792 return _DEFAULT_LEGACY_METADATA
793
794 if len(metadata_nodes) > 1:
795 raise ValueError('Module METADATA must defined only once.')
796
797 metadata_node = metadata_nodes[0]
798
799 if not isinstance(metadata_node.value, ast.Constant):
800 raise TypeError(f'Module METADATA node must be {ast.Constant} not {type(metadata_node)}.')
801
802 unparsed_metadata = metadata_node.value.value
803
804 if not isinstance(unparsed_metadata, str):
805 raise TypeError(f'Module METADATA must be {str} not {type(unparsed_metadata)}.')
806
807 try:
808 parsed_metadata = yaml_load(unparsed_metadata)
809 except Exception as ex:
810 raise ValueError('Module METADATA must be valid YAML.') from ex
811
812 if not isinstance(parsed_metadata, dict):
813 raise TypeError(f'Module METADATA must parse to {dict} not {type(parsed_metadata)}.')
814
815 schema_version = parsed_metadata.pop('schema_version', None)
816
817 if not (metadata_type := metadata_versions.get(schema_version)):
818 raise ValueError(f'Module METADATA schema_version {schema_version} is unknown.')
819
820 try:
821 metadata = metadata_type(**parsed_metadata) # type: ignore
822 except Exception as ex:
823 raise ValueError('Module METADATA is invalid.') from ex
824
825 return metadata
826
827
828 def recursive_finder(
829 name: str,
830 module_fqn: str,
831 module_data: bytes,
832 zf: zipfile.ZipFile,
833 date_time: datetime.datetime,
834 extension_manager: _builder.ExtensionManager,
835 ) -> ModuleMetadata:
836 """
837 Using ModuleDepFinder, make sure we have all of the module_utils files that
838 the module and its module_utils files needs. (no longer actually recursive)
839 :arg name: Name of the python module we're examining
840 :arg module_fqn: Fully qualified name of the python module we're scanning
841 :arg module_data: string Python code of the module we're scanning
842 :arg zf: An open :python:class:`zipfile.ZipFile` object that holds the Ansible module payload
843 which we're assembling
844 """
845 # py_module_cache maps python module names to a tuple of the code in the module
846 # and the pathname to the module.
847 # Here we pre-load it with modules which we create without bothering to
848 # read from actual files (In some cases, these need to differ from what ansible
849 # ships because they're namespace packages in the module)
850 # FIXME: do we actually want ns pkg behavior for these? Seems like they should just be forced to emptyish pkg stubs
851 py_module_cache = {
852 ('ansible',): (
853 b'from pkgutil import extend_path\n'
854 b'__path__=extend_path(__path__,__name__)\n'
855 b'__version__="' + to_bytes(__version__) +
856 b'"\n__author__="' + to_bytes(__author__) + b'"\n',
857 'ansible/__init__.py'),
858 ('ansible', 'module_utils'): (
859 b'from pkgutil import extend_path\n'
860 b'__path__=extend_path(__path__,__name__)\n',
861 'ansible/module_utils/__init__.py')}
862
863 module_utils_paths = [p for p in module_utils_loader._get_paths(subdirs=False) if os.path.isdir(p)]
864 module_utils_paths.append(_MODULE_UTILS_PATH)
865
866 finder = ModuleDepFinder(module_fqn, module_data)
867 module_metadata = _get_module_metadata(finder.tree)
868
869 embeds = finder.embeds.copy()
870
871 if not isinstance(module_metadata, ModuleMetadataV1):
872 raise NotImplementedError()
873
874 profile = module_metadata.serialization_profile
875
876 # the format of this set is a tuple of the module name and whether the import is ambiguous as a module name
877 # or an attribute of a module (e.g. from x.y import z <-- is z a module or an attribute of x.y?)
878 modules_to_process = [_ModuleUtilsProcessEntry(m, True, False, is_optional=m in finder.optional_imports) for m in finder.submodules]
879
880 # include module_utils that are always required
881 modules_to_process.extend((
882 _ModuleUtilsProcessEntry.from_module(_loader),
883 _ModuleUtilsProcessEntry.from_module(_basic),
884 _ModuleUtilsProcessEntry.from_module_name(_json.get_module_serialization_profile_module_name(profile, True)),
885 _ModuleUtilsProcessEntry.from_module_name(_json.get_module_serialization_profile_module_name(profile, False)),
886 ))
887
888 modules_to_process.extend(_ModuleUtilsProcessEntry.from_module_name(name) for name in extension_manager.module_names)
889
890 module_info: ModuleUtilLocatorBase
891
892 # we'll be adding new modules inline as we discover them, so just keep going til we've processed them all
893 while modules_to_process:
894 modules_to_process.sort() # not strictly necessary, but nice to process things in predictable and repeatable order
895 entry = modules_to_process.pop(0)
896
897 if entry.name_parts in py_module_cache:
898 # this is normal; we'll often see the same module imported many times, but we only need to process it once
899 continue
900
901 if entry.name_parts[0:2] == ('ansible', 'module_utils'):
902 module_info = LegacyModuleUtilLocator(entry.name_parts, is_ambiguous=entry.is_ambiguous,
903 mu_paths=module_utils_paths, child_is_redirected=entry.child_is_redirected)
904 elif entry.name_parts[0] == 'ansible_collections':
905 module_info = CollectionModuleUtilLocator(entry.name_parts, is_ambiguous=entry.is_ambiguous,
906 child_is_redirected=entry.child_is_redirected, is_optional=entry.is_optional)
907 else:
908 # FIXME: dot-joined result
909 display.warning('ModuleDepFinder improperly found a non-module_utils import %s'
910 % [entry.name_parts])
911 continue
912
913 # Could not find the module. Construct a helpful error message.
914 if not module_info.found:
915 if entry.is_optional:
916 # this was a best-effort optional import that we couldn't find, oh well, move along...
917 continue
918 # FIXME: use dot-joined candidate names
919 msg = 'Could not find imported module support code for {0}. Looked for ({1})'.format(module_fqn, module_info.candidate_names_joined)
920 raise AnsibleError(msg)
921
922 # check the cache one more time with the module we actually found, since the name could be different than the input
923 # eg, imported name vs module
924 if module_info.fq_name_parts in py_module_cache:
925 continue
926
927 finder = ModuleDepFinder('.'.join(module_info.fq_name_parts), module_info.source_code, is_pkg_init=module_info.is_package)
928 embeds.update(finder.embeds)
929 modules_to_process.extend(_ModuleUtilsProcessEntry(m, True, False, is_optional=m in finder.optional_imports)
930 for m in finder.submodules if m not in py_module_cache)
931
932 # we've processed this item, add it to the output list
933 py_module_cache[module_info.fq_name_parts] = (module_info.source_code, module_info.output_path)
934
935 # ensure we process all ancestor package inits
936 accumulated_pkg_name = []
937 for pkg in module_info.fq_name_parts[:-1]:
938 accumulated_pkg_name.append(pkg) # we're accumulating this across iterations
939 normalized_name = tuple(accumulated_pkg_name) # extra machinations to get a hashable type (list is not)
940 if normalized_name not in py_module_cache:
941 modules_to_process.append(_ModuleUtilsProcessEntry(normalized_name, False, module_info.redirected, is_optional=entry.is_optional))
942
943 written_files = set()
944 for py_module_name in py_module_cache:
945 source_code, py_module_file_name = py_module_cache[py_module_name]
946
947 mu_file = to_text(py_module_file_name, errors='surrogate_or_strict')
948 display.vvvvv("Including module_utils file %s" % mu_file)
949
950 zf.writestr(_make_zinfo(py_module_file_name, date_time, zf=zf), source_code)
951 written_files.add(py_module_file_name)
952
953 if extension_manager.debugger_enabled and (origin := Origin.get_tag(source_code)) and origin.path:
954 extension_manager.source_mapping[origin.path] = py_module_file_name
955
956 anchor_cache: dict[str, pathlib.Path] = {}
957 for embed in embeds:
958 try:
959 embed_path_cm = embed.path_context_manager
960 except ModuleNotFoundError as e:
961 # the source exception message includes the package name, no need to repeat
962 raise AnsibleError('Embed package not found while packaging module.', obj=embed.package) from e
963
964 with embed_path_cm as path:
965 if not path.is_file():
966 raise AnsibleError(f'Embed resource {embed.resource!r} not found while packaging module.', obj=embed.resource)
967 anchor_parts = embed.package.split('.')
968 if anchor_parts[0] == 'ansible':
969 try:
970 root = anchor_cache['ansible']
971 except KeyError:
972 root = anchor_cache['ansible'] = ir_files('ansible').parent
973 rel_path = path.relative_to(root)
974 elif anchor_parts[0] == 'ansible_collections':
975 pkg = '.'.join(anchor_parts[:3])
976 try:
977 root = anchor_cache[pkg]
978 except KeyError:
979 root = anchor_cache[pkg] = ir_files(pkg).parents[2]
980 rel_path = path.relative_to(root)
981 else:
982 raise AnsibleError('Embed must be an ansible/ansible_collections resource.', obj=embed.resource)
983
984 display.vvvvv(f"Including embed file {rel_path}")
985 zf.writestr(_make_zinfo(str_path := str(rel_path), date_time, zf=zf), path.read_bytes())
986 written_files.add(str_path)
987 for parent in rel_path.parents:
988 if not parent.name:
989 continue
990 p_init = str(parent / '__init__.py')
991 if p_init not in written_files:
992 display.vvvvv(f"Including parent init file {p_init}")
993 zf.writestr(_make_zinfo(p_init, date_time, zf=zf), b'')
994 written_files.add(p_init)
995
996 return module_metadata
997
998
999 def _compile_module_ast(module_name: str, source_code: str | bytes) -> ast.Module:
1000 origin = Origin.get_tag(source_code) or Origin.UNKNOWN
1001
1002 # compile the source, process all relevant imported modules
1003 try:
1004 tree = t.cast(ast.Module, compile(source_code, str(origin), 'exec', ast.PyCF_ONLY_AST))
1005 except SyntaxError as ex:
1006 raise AnsibleError(f"Unable to compile {module_name!r}.", obj=origin.replace(line_num=ex.lineno, col_num=ex.offset)) from ex
1007
1008 return tree
1009
1010
1011 def _is_binary(b_module_data):
1012 """Heuristic to classify a file as binary by sniffing a 1k header; see https://stackoverflow.com/a/7392391"""
1013 textchars = bytearray(set([7, 8, 9, 10, 12, 13, 27]) | set(range(0x20, 0x100)) - set([0x7f]))
1014 start = b_module_data[:1024]
1015 return bool(start.translate(None, textchars))
1016
1017
1018 def _get_ansible_module_fqn(module_path):
1019 """
1020 Get the fully qualified name for an ansible module based on its pathname
1021
1022 remote_module_fqn is the fully qualified name. Like ansible.modules.system.ping
1023 Or ansible_collections.Namespace.Collection_name.plugins.modules.ping
1024 .. warning:: This function is for ansible modules only. It won't work for other things
1025 (non-module plugins, etc)
1026 """
1027 remote_module_fqn = None
1028
1029 # Is this a core module?
1030 match = CORE_LIBRARY_PATH_RE.search(module_path)
1031 if not match:
1032 # Is this a module in a collection?
1033 match = COLLECTION_PATH_RE.search(module_path)
1034
1035 # We can tell the FQN for core modules and collection modules
1036 if match:
1037 path = match.group('path')
1038 if '.' in path:
1039 # FQNs must be valid as python identifiers. This sanity check has failed.
1040 # we could check other things as well
1041 raise ValueError('Module name (or path) was not a valid python identifier')
1042
1043 remote_module_fqn = '.'.join(path.split('/'))
1044 else:
1045 # Currently we do not handle modules in roles so we can end up here for that reason
1046 raise ValueError("Unable to determine module's fully qualified name")
1047
1048 return remote_module_fqn
1049
1050
1051 def _add_module_to_zip(
1052 zf: zipfile.ZipFile,
1053 date_time: datetime.datetime,
1054 remote_module_fqn: str,
1055 b_module_data: bytes,
1056 module_path: str,
1057 extension_manager: _builder.ExtensionManager,
1058 ) -> None:
1059 """Add a module from ansible or from an ansible collection into the module zip"""
1060 module_path_parts = remote_module_fqn.split('.')
1061
1062 # Write the module
1063 zip_module_path = '/'.join(module_path_parts) + '.py'
1064 zf.writestr(
1065 _make_zinfo(zip_module_path, date_time, zf=zf),
1066 b_module_data
1067 )
1068
1069 if extension_manager.debugger_enabled:
1070 extension_manager.source_mapping[module_path] = zip_module_path
1071
1072 existing_paths: frozenset[str]
1073
1074 # Write the __init__.py's necessary to get there
1075 if module_path_parts[0] == 'ansible':
1076 # The ansible namespace is setup as part of the module_utils setup...
1077 start = 2
1078 existing_paths = frozenset()
1079 else:
1080 # ... but ansible_collections and other toplevels are not
1081 start = 1
1082 existing_paths = frozenset(zf.namelist())
1083
1084 for idx in range(start, len(module_path_parts)):
1085 package_path = '/'.join(module_path_parts[:idx]) + '/__init__.py'
1086 # If a collections module uses module_utils from a collection then most packages will have already been added by recursive_finder.
1087 if package_path in existing_paths:
1088 continue
1089 # Note: We don't want to include more than one ansible module in a payload at this time
1090 # so no need to fill the __init__.py with namespace code
1091 zf.writestr(
1092 _make_zinfo(package_path, date_time, zf=zf),
1093 b''
1094 )
1095
1096
1097 class _GetCommandArgs(t.Protocol):
1098 def __call__(
1099 self,
1100 module_path: str | None,
1101 ) -> tuple[list[str], bytes | None] | None:
1102 ...
1103
1104
1105 class _ProcessResult(t.Protocol):
1106 def __call__(
1107 self,
1108 rc: int,
1109 stdout: bytes,
1110 stderr: bytes,
1111 ) -> tuple[int, bytes, bytes]:
1112 ...
1113
1114
1115 @dataclasses.dataclass(kw_only=True, slots=True, frozen=True)
1116 class _BuiltModule:
1117 """Payload required to execute an Ansible module, along with information required to do so."""
1118 b_module_data: bytes
1119 module_style: t.Literal['binary', 'new', 'non_native_want_json', 'old']
1120 shebang: str | None
1121 serialization_profile: str
1122 has_async: bool = False
1123 has_become: bool = False
1124 has_environment: bool = False
1125 command_lookup: _GetCommandArgs | None = None
1126 process_result: _ProcessResult | None = None
1127
1128 def get_command_args(
1129 self,
1130 module_path: str | None,
1131 ) -> tuple[list[str], bytes | None] | None:
1132 if self.command_lookup:
1133 return self.command_lookup(module_path=module_path)
1134 else:
1135 return None
1136
1137 def process_module_result(
1138 self,
1139 rc: int,
1140 stdout: bytes,
1141 stderr: bytes,
1142 ) -> tuple[int, bytes, bytes]:
1143 if self.process_result:
1144 return self.process_result(rc, stdout, stderr)
1145 else:
1146 return rc, stdout, stderr
1147
1148
1149 @dataclasses.dataclass(kw_only=True, slots=True, frozen=True)
1150 class _CachedModule:
1151 """Cached Python module created by AnsiballZ."""
1152
1153 # FIXME: switch this to use a locked down pickle config or don't use pickle- easy to mess up and reach objects that shouldn't be pickled
1154
1155 zip_data: bytes
1156 metadata: ModuleMetadata
1157 source_mapping: dict[str, str]
1158 """A mapping of controller absolute source locations to target relative source locations within the AnsiballZ payload."""
1159
1160 def dump(self, path: str) -> None:
1161 temp_path = pathlib.Path(path + '-part')
1162
1163 with temp_path.open('wb') as cache_file:
1164 pickle.dump(self, cache_file)
1165
1166 temp_path.rename(path)
1167
1168 @classmethod
1169 def load(cls, path: str) -> t.Self:
1170 with pathlib.Path(path).open('rb') as cache_file:
1171 return pickle.load(cache_file)
1172
1173
1174 def _find_module_utils(
1175 *,
1176 module_name: str,
1177 b_module_data: bytes,
1178 module_path: str,
1179 module_args: dict[object, object],
1180 task_vars: dict[str, object],
1181 templar: Templar,
1182 module_compression: str,
1183 async_timeout: int,
1184 become_plugin: BecomeBase | None,
1185 environment: dict[str, str],
1186 remote_is_local: bool = False,
1187 platform: t.Literal["posix", "windows"] = "posix",
1188 default_interpreters: dict[str, str] | None = None,
1189 ) -> _BuiltModule:
1190 """
1191 Given the source of the module, convert it to a Jinja2 template to insert
1192 module code and return whether it's a new or old style module.
1193 """
1194 module_substyle: t.Literal['binary', 'jsonargs', 'non_native_want_json', 'old', 'powershell', 'python']
1195 module_style: t.Literal['binary', 'new', 'non_native_want_json', 'old']
1196 module_substyle = module_style = 'old'
1197
1198 # module_style is something important to calling code (ActionBase). It
1199 # determines how arguments are formatted (json vs k=v) and whether
1200 # a separate arguments file needs to be sent over the wire.
1201 # module_substyle is extra information that's useful internally. It tells
1202 # us what we have to look to substitute in the module files and whether
1203 # we're using module replacer or ansiballz to format the module itself.
1204 if _is_binary(b_module_data):
1205 module_substyle = module_style = 'binary'
1206 elif REPLACER in b_module_data:
1207 # Do REPLACER before from ansible.module_utils because we need make sure
1208 # we substitute "from ansible.module_utils basic" for REPLACER
1209 module_style = 'new'
1210 module_substyle = 'python'
1211 b_module_data = b_module_data.replace(REPLACER, b'from ansible.module_utils.basic import *')
1212 elif NEW_STYLE_PYTHON_MODULE_RE.search(b_module_data):
1213 module_style = 'new'
1214 module_substyle = 'python'
1215 elif REPLACER_WINDOWS in b_module_data:
1216 module_style = 'new'
1217 module_substyle = 'powershell'
1218 b_module_data = b_module_data.replace(REPLACER_WINDOWS, b'#AnsibleRequires -PowerShell Ansible.ModuleUtils.Legacy')
1219 elif re.search(b'#Requires -Module', b_module_data, re.IGNORECASE) \
1220 or re.search(b'#Requires -Version', b_module_data, re.IGNORECASE) \
1221 or re.search(b'#AnsibleRequires -(OSVersion|PowerShell|CSharpUtil|Wrapper)', b_module_data, re.IGNORECASE):
1222 module_style = 'new'
1223 module_substyle = 'powershell'
1224 elif REPLACER_JSONARGS in b_module_data:
1225 module_style = 'new'
1226 module_substyle = 'jsonargs'
1227 elif b'WANT_JSON' in b_module_data:
1228 module_substyle = module_style = 'non_native_want_json'
1229
1230 shebang = None
1231 # Neither old-style, non_native_want_json nor binary modules should be modified
1232 # except for the shebang line (Done by modify_module)
1233 if module_style in ('old', 'non_native_want_json', 'binary'):
1234 return _BuiltModule(
1235 b_module_data=b"", # Marker to indicate the original file should be used without modification.
1236 module_style=module_style,
1237 shebang=shebang,
1238 serialization_profile='legacy',
1239 )
1240
1241 output = BytesIO()
1242
1243 try:
1244 remote_module_fqn = _get_ansible_module_fqn(module_path)
1245 except ValueError:
1246 # Modules in roles currently are not found by the fqn heuristic so we
1247 # fallback to this. This means that relative imports inside a module from
1248 # a role may fail. Absolute imports should be used for future-proofness.
1249 # People should start writing collections instead of modules in roles so we
1250 # may never fix this
1251 display.debug('ANSIBALLZ: Could not determine module FQN')
1252 # FIXME: add integration test to validate that builtins and legacy modules with the same name are tracked separately by the caching mechanism
1253 # FIXME: surrogate FQN should be unique per source path- role-packaged modules with name collisions can still be aliased
1254 remote_module_fqn = 'ansible.legacy.%s' % module_name
1255
1256 has_async = False
1257 has_become = False
1258 has_environment = False
1259 command_lookup: _GetCommandArgs | None = None
1260 process_result: _ProcessResult | None = None
1261
1262 if module_substyle == 'python':
1263 date_time = datetime.datetime.now(datetime.timezone.utc)
1264
1265 if date_time.year < 1980:
1266 raise AnsibleError(f'Cannot create zipfile due to pre-1980 configured date: {date_time}')
1267
1268 try:
1269 compression_method = getattr(zipfile, module_compression)
1270 except AttributeError:
1271 display.warning(u'Bad module compression string specified: %s. Using ZIP_STORED (no compression)' % module_compression)
1272 compression_method = zipfile.ZIP_STORED
1273
1274 extension_manager = _builder.ExtensionManager.create(task_vars=task_vars)
1275 extension_key = '~'.join(extension_manager.extension_names) if extension_manager.extension_names else 'none'
1276 lookup_path = os.path.join(C.DEFAULT_LOCAL_TMP, 'ansiballz_cache') # type: ignore[attr-defined]
1277 cached_module_filename = os.path.join(lookup_path, '-'.join((remote_module_fqn, module_compression, extension_key)))
1278
1279 os.makedirs(os.path.dirname(cached_module_filename), exist_ok=True)
1280
1281 cached_module: _CachedModule | None = None
1282
1283 # Optimization -- don't lock if the module has already been cached
1284 if os.path.exists(cached_module_filename):
1285 display.debug('ANSIBALLZ: using cached module: %s' % cached_module_filename)
1286 cached_module = _CachedModule.load(cached_module_filename)
1287 else:
1288 display.debug('ANSIBALLZ: Acquiring lock')
1289 lock_path = f'{cached_module_filename}.lock'
1290 with _locking.named_mutex(lock_path):
1291 display.debug(f'ANSIBALLZ: Lock acquired: {lock_path}')
1292 # Check that no other process has created this while we were
1293 # waiting for the lock
1294 if not os.path.exists(cached_module_filename):
1295 display.debug('ANSIBALLZ: Creating module')
1296 # Create the module zip data
1297 zipoutput = BytesIO()
1298 zf = zipfile.ZipFile(zipoutput, mode='w', compression=compression_method)
1299
1300 # walk the module imports, looking for module_utils to send- they'll be added to the zipfile
1301 module_metadata = recursive_finder(
1302 module_name,
1303 remote_module_fqn,
1304 Origin(path=module_path).tag(b_module_data),
1305 zf,
1306 date_time,
1307 extension_manager,
1308 )
1309
1310 display.debug('ANSIBALLZ: Writing module into payload')
1311 _add_module_to_zip(zf, date_time, remote_module_fqn, b_module_data, module_path, extension_manager)
1312
1313 zf.close()
1314 zip_data = base64.b64encode(zipoutput.getvalue())
1315
1316 # Write the assembled module to a temp file (write to temp
1317 # so that no one looking for the file reads a partially
1318 # written file)
1319 os.makedirs(lookup_path, exist_ok=True)
1320 display.debug('ANSIBALLZ: Writing module')
1321 cached_module = _CachedModule(zip_data=zip_data, metadata=module_metadata, source_mapping=extension_manager.source_mapping)
1322 cached_module.dump(cached_module_filename)
1323 display.debug('ANSIBALLZ: Done creating module')
1324
1325 if not cached_module:
1326 display.debug('ANSIBALLZ: Reading module after lock')
1327 # Another process wrote the file while we were waiting for
1328 # the write lock. Go ahead and read the data from disk
1329 # instead of re-creating it.
1330 try:
1331 cached_module = _CachedModule.load(cached_module_filename)
1332 except OSError as ex:
1333 raise AnsibleError('A different worker process failed to create module file. '
1334 'Look at traceback for that process for debugging information.') from ex
1335
1336 o_interpreter, o_args = _extract_interpreter(b_module_data)
1337 if o_interpreter is None:
1338 o_interpreter = u'/usr/bin/python'
1339
1340 shebang, dummy = _get_shebang(
1341 o_interpreter,
1342 task_vars,
1343 templar,
1344 o_args,
1345 remote_is_local=remote_is_local,
1346 default_interpreters=default_interpreters,
1347 )
1348
1349 # FUTURE: the module cache entry should be invalidated if we got this value from a host-dependent source
1350 rlimit_nofile = C.config.get_config_value('PYTHON_MODULE_RLIMIT_NOFILE', variables=task_vars)
1351
1352 if not isinstance(rlimit_nofile, int):
1353 rlimit_nofile = int(templar._engine.template(rlimit_nofile, options=TemplateOptions(value_for_omit=0)))
1354
1355 if not isinstance(cached_module.metadata, ModuleMetadataV1):
1356 raise NotImplementedError()
1357
1358 params = dict(ANSIBLE_MODULE_ARGS=module_args,)
1359 encoder = get_module_encoder(cached_module.metadata.serialization_profile, Direction.CONTROLLER_TO_MODULE)
1360
1361 try:
1362 encoded_params = json.dumps(params, cls=encoder)
1363 except TypeError as ex:
1364 raise AnsibleError(f'Failed to serialize arguments for the {module_name!r} module.') from ex
1365
1366 extension_manager.source_mapping = cached_module.source_mapping
1367
1368 code = _get_ansiballz_code(shebang)
1369 args = dict(
1370 ansible_module=module_name,
1371 module_fqn=remote_module_fqn,
1372 profile=cached_module.metadata.serialization_profile,
1373 date_time=date_time,
1374 rlimit_nofile=rlimit_nofile,
1375 params=encoded_params,
1376 extensions=extension_manager.get_extensions(),
1377 secrets=_secrets._secret_masker.secrets_in_json(encoded_params),
1378 zip_data=to_text(cached_module.zip_data),
1379 )
1380
1381 args_string = '\n'.join(f'{key}={value!r},' for key, value in args.items())
1382
1383 wrapper = f"""{code}
1384
1385
1386 if __name__ == "__main__":
1387 _ansiballz_main(
1388 {args_string}
1389 )
1390 """
1391
1392 output.write(to_bytes(wrapper))
1393
1394 module_metadata = cached_module.metadata
1395 b_module_data = output.getvalue()
1396
1397 elif module_substyle == 'powershell':
1398 module_metadata = ModuleMetadataV1(serialization_profile='legacy') # DTFIX-FUTURE: support serialization profiles for PowerShell modules
1399
1400 wrapper_environment = {}
1401 wrapper_async_timeout = 0
1402 wrapper_become = None
1403
1404 if platform == "windows":
1405 # Async, become, and environment support in the wrapper is Windows only.
1406 wrapper_environment = environment
1407 wrapper_async_timeout = async_timeout
1408 wrapper_become = become_plugin
1409 has_async = True
1410 has_become = True
1411 has_environment = True
1412
1413 module_interpreter, dummy = _extract_interpreter(b_module_data)
1414 if not module_interpreter:
1415 module_interpreter = 'powershell'
1416
1417 shebang, dummy = _get_shebang(
1418 module_interpreter,
1419 task_vars,
1420 templar,
1421 default_interpreters=default_interpreters,
1422 )
1423
1424 # We pass the interpreter to the exec wrapper in case the connection
1425 # plugin (psrp) is unable to control what interpreter to use.
1426 pwsh_interpreter = shebang[2:] # Drop the #!
1427
1428 # create the common exec wrapper payload and set that as the module_data
1429 # bytes
1430 b_module_data = ps_manifest._create_powershell_wrapper(
1431 name=remote_module_fqn,
1432 module_data=b_module_data,
1433 module_path=module_path,
1434 module_args=module_args,
1435 environment=wrapper_environment,
1436 async_timeout=wrapper_async_timeout,
1437 become_plugin=wrapper_become,
1438 substyle=module_substyle,
1439 task_vars=task_vars,
1440 profile=module_metadata.serialization_profile,
1441 pwsh_interpreter=pwsh_interpreter,
1442 )
1443
1444 def get_module_command_args(
1445 module_path: str | None,
1446 ) -> tuple[list[str], bytes | None] | None:
1447 bootstrap_wrapper = ps_manifest._get_powershell_script("bootstrap_wrapper.ps1").decode('utf-8')
1448
1449 module_data = None
1450 bootstrap_args = []
1451 disable_input = False
1452 if not module_path:
1453 # We are pipelining
1454 module_data = b_module_data
1455 else:
1456 # Running powershell without any input might hang the process
1457 # if the parent spawns powershell with a redirected stdin but
1458 # never closes it. By explicitly disabling the input,
1459 # powershell never attempts to wait for stdin to close.
1460 disable_input = True
1461 bootstrap_args = [module_path]
1462
1463 interpreter_args = _ps_script.get_pwsh_encoded_cmdline(
1464 script=bootstrap_wrapper,
1465 args=bootstrap_args,
1466 pwsh_path=pwsh_interpreter,
1467 disable_input=disable_input,
1468 override_execution_policy=platform == "windows",
1469 )
1470
1471 return interpreter_args, module_data
1472
1473 def parse_clixml_stderr(rc: int, stdout: bytes, stderr: bytes) -> tuple[int, bytes, bytes]:
1474 return (rc, stdout, _clixml.replace_stderr_clixml(stderr))
1475
1476 command_lookup = get_module_command_args
1477 process_result = parse_clixml_stderr
1478
1479 elif module_substyle == 'jsonargs':
1480 encoder = get_module_encoder('legacy', Direction.CONTROLLER_TO_MODULE)
1481 module_args_json = to_bytes(json.dumps(module_args, cls=encoder))
1482
1483 # these strings could be included in a third-party module but
1484 # officially they were included in the 'basic' snippet for new-style
1485 # python modules (which has been replaced with something else in
1486 # ansiballz) If we remove them from jsonargs-style module replacer
1487 # then we can remove them everywhere.
1488 python_repred_args = to_bytes(repr(module_args_json))
1489 b_module_data = b_module_data.replace(REPLACER_VERSION, to_bytes(repr(__version__)))
1490 b_module_data = b_module_data.replace(REPLACER_COMPLEX, python_repred_args)
1491 b_module_data = b_module_data.replace(
1492 REPLACER_SELINUX,
1493 to_bytes(','.join(C.DEFAULT_SELINUX_SPECIAL_FS))) # type: ignore[attr-defined]
1494
1495 # The main event -- substitute the JSON args string into the module
1496 b_module_data = b_module_data.replace(REPLACER_JSONARGS, module_args_json)
1497
1498 syslog_facility = task_vars.get(
1499 'ansible_syslog_facility',
1500 C.DEFAULT_SYSLOG_FACILITY) # type: ignore[attr-defined]
1501 facility = b'syslog.' + to_bytes(syslog_facility, errors='surrogate_or_strict')
1502 b_module_data = b_module_data.replace(b'syslog.LOG_USER', facility)
1503
1504 module_metadata = ModuleMetadataV1(serialization_profile='legacy')
1505 else:
1506 module_metadata = ModuleMetadataV1(serialization_profile='legacy')
1507
1508 if not isinstance(module_metadata, ModuleMetadataV1):
1509 raise NotImplementedError(type(module_metadata))
1510
1511 return _BuiltModule(
1512 b_module_data=b_module_data,
1513 module_style=module_style,
1514 shebang=shebang,
1515 serialization_profile=module_metadata.serialization_profile,
1516 has_async=has_async,
1517 has_become=has_become,
1518 has_environment=has_environment,
1519 command_lookup=command_lookup,
1520 process_result=process_result,
1521 )
1522
1523
1524 def _extract_interpreter(b_module_data):
1525 """
1526 Used to extract shebang expression from binary module data and return a text
1527 string with the shebang, or None if no shebang is detected.
1528 """
1529
1530 interpreter = None
1531 args = []
1532 b_lines = b_module_data.split(b"\n", 1)
1533 if b_lines[0].startswith(b"#!"):
1534 b_shebang = b_lines[0].strip()
1535
1536 # shlex.split needs text on Python 3
1537 cli_split = shlex.split(to_text(b_shebang[2:], errors='surrogate_or_strict'))
1538
1539 # convert args to text
1540 cli_split = [to_text(a, errors='surrogate_or_strict') for a in cli_split]
1541 interpreter = cli_split[0]
1542 args = cli_split[1:]
1543
1544 return interpreter, args
1545
1546
1547 def modify_module(
1548 *,
1549 module_name: str,
1550 module_path,
1551 module_args,
1552 templar,
1553 task_vars=None,
1554 module_compression='ZIP_STORED',
1555 async_timeout=0,
1556 become_plugin=None,
1557 environment=None,
1558 remote_is_local=False,
1559 shell_plugin=None,
1560 ) -> _BuiltModule:
1561 """
1562 Used to insert chunks of code into modules before transfer rather than
1563 doing regular python imports. This allows for more efficient transfer in
1564 a non-bootstrapping scenario by not moving extra files over the wire and
1565 also takes care of embedding arguments in the transferred modules.
1566
1567 This version is done in such a way that local imports can still be
1568 used in the module code, so IDEs don't have to be aware of what is going on.
1569
1570 Example:
1571
1572 from ansible.module_utils.basic import *
1573
1574 ... will result in the insertion of basic.py into the module
1575 from the module_utils/ directory in the source tree.
1576
1577 For powershell, this code effectively no-ops, as the exec wrapper requires access to a number of
1578 properties not available here.
1579
1580 """
1581 task_vars = {} if task_vars is None else task_vars
1582 environment = {} if environment is None else environment
1583 platform: t.Literal["posix", "windows"] = "windows" if getattr(shell_plugin, "_IS_WINDOWS", False) else "posix"
1584
1585 # For backwards compatibility and to make it easy for module authors to
1586 # distinguish between pwsh versions for 5.1 or 7.x we default #!powershell
1587 # to be powershell and #!/usr/bin/pwsh to pwsh on Windows. Linux only has
1588 # pwsh 7 and the shebang path works as normal.
1589 default_interpreters = {
1590 'powershell': 'powershell' if platform == "windows" else '/usr/bin/pwsh',
1591 '/usr/bin/pwsh': 'pwsh' if platform == "windows" else '/usr/bin/pwsh',
1592 }
1593
1594 with open(module_path, 'rb') as f:
1595
1596 # read in the module source
1597 b_module_data = f.read()
1598
1599 module_bits = _find_module_utils(
1600 module_name=module_name,
1601 b_module_data=b_module_data,
1602 module_path=module_path,
1603 module_args=module_args,
1604 task_vars=task_vars,
1605 templar=templar,
1606 module_compression=module_compression,
1607 async_timeout=async_timeout,
1608 become_plugin=become_plugin,
1609 environment=environment,
1610 remote_is_local=remote_is_local,
1611 platform=platform,
1612 default_interpreters=default_interpreters,
1613 )
1614
1615 if module_bits.b_module_data:
1616 b_module_data = module_bits.b_module_data
1617 shebang = module_bits.shebang
1618
1619 if shebang is None and module_bits.module_style != 'binary':
1620 interpreter, args = _extract_interpreter(b_module_data)
1621 # No interpreter/shebang, assume a binary module?
1622 if interpreter is not None:
1623
1624 shebang, new_interpreter = _get_shebang(
1625 interpreter,
1626 task_vars,
1627 templar,
1628 args,
1629 remote_is_local=remote_is_local,
1630 default_interpreters=default_interpreters,
1631 )
1632
1633 # update shebang
1634 b_lines = b_module_data.split(b"\n", 1)
1635
1636 if interpreter != new_interpreter:
1637 b_lines[0] = to_bytes(shebang, errors='surrogate_or_strict', nonstring='passthru')
1638
1639 b_module_data = b"\n".join(b_lines)
1640
1641 module_bits = dataclasses.replace(module_bits, b_module_data=b_module_data, shebang=shebang)
1642
1643 return module_bits
1644
1645
1646 def _get_action_arg_defaults(action: str, task: Task, templar: TemplateEngine) -> dict[str, t.Any]:
1647 """
1648 Get module_defaults that match or contain a fully qualified action/module name.
1649 """
1650 action_groups = task._parent._play._action_groups
1651 defaults = task.module_defaults
1652
1653 # Get the list of groups that contain this action
1654 if action_groups is None:
1655 msg = (
1656 "Finding module_defaults for action %s. "
1657 "The caller has not passed the action_groups, so any "
1658 "that may include this action will be ignored."
1659 )
1660 display.warning(msg=msg)
1661 group_names = []
1662 else:
1663 group_names = action_groups.get(action, [])
1664
1665 tmp_args: dict[str, t.Any] = {}
1666 module_defaults = {}
1667
1668 # Merge latest defaults into dict, since they are a list of dicts
1669 if isinstance(defaults, list):
1670 for default in defaults:
1671 module_defaults.update(default)
1672
1673 for default in module_defaults:
1674 if default.startswith('group/'):
1675 group_name = default.split('group/')[-1]
1676 if group_name in group_names:
1677 tmp_args.update(templar.resolve_to_container(module_defaults.get(f'group/{group_name}', {})))
1678
1679 # handle specific action defaults
1680 tmp_args.update(templar.resolve_to_container(module_defaults.get(action, {})))
1681
1682 return tmp_args
1683
1684
1685 def _apply_action_arg_defaults(action: str, task: Task, action_args: dict[str, t.Any], templar: Templar) -> dict[str, t.Any]:
1686 """
1687 Finalize arguments from module_defaults and update with action_args.
1688
1689 This is used by action plugins like gather_facts, package, and service,
1690 which select modules to execute after normal task argument finalization.
1691 """
1692 args = _get_action_arg_defaults(action, task, templar._engine)
1693 args = templar.template({k: v for k, v in args.items() if k not in action_args})
1694 args.update(action_args)
1695
1696 return args