Debian Codegraph @

test/lib/ansible_test/_internal/ansible_util.py

raw
1 """Miscellaneous utility functions and classes specific to ansible cli tools."""
2
3 from __future__ import annotations
4
5 import json
6 import os
7 import pathlib
8 import shutil
9 import typing as t
10
11 from .constants import (
12 ANSIBLE_BIN_SYMLINK_MAP,
13 SOFT_RLIMIT_NOFILE,
14 )
15
16 from .io import (
17 write_text_file,
18 )
19
20 from .util import (
21 common_environment,
22 ApplicationError,
23 ANSIBLE_LIB_ROOT,
24 ANSIBLE_TEST_ROOT,
25 ANSIBLE_TEST_DATA_ROOT,
26 ANSIBLE_ROOT,
27 ANSIBLE_SOURCE_ROOT,
28 ANSIBLE_TEST_TOOLS_ROOT,
29 MODE_FILE_EXECUTE,
30 get_ansible_version,
31 raw_command,
32 verified_chmod,
33 )
34
35 from .util_common import (
36 create_temp_dir,
37 ResultType,
38 intercept_python,
39 get_python_injector_path,
40 )
41
42 from .config import (
43 IntegrationConfig,
44 PosixIntegrationConfig,
45 EnvironmentConfig,
46 CommonConfig,
47 )
48
49 from .data import (
50 data_context,
51 )
52
53 from .python_requirements import (
54 install_requirements,
55 )
56
57 from .host_configs import (
58 PythonConfig,
59 )
60
61 from .thread import (
62 mutex,
63 )
64
65
66 def parse_inventory(args: EnvironmentConfig, inventory_path: str) -> dict[str, t.Any]:
67 """Return a dict parsed from the given inventory file."""
68 cmd = ['ansible-inventory', '-i', inventory_path, '--list']
69 env = ansible_environment(args)
70 inventory = json.loads(intercept_python(args, args.controller_python, cmd, env, capture=True, always=True)[0])
71 return inventory
72
73
74 def get_hosts(inventory: dict[str, t.Any], group_name: str) -> dict[str, dict[str, t.Any]]:
75 """Return a dict of hosts from the specified group in the given inventory."""
76 hostvars = inventory.get('_meta', {}).get('hostvars', {})
77 group = inventory.get(group_name, {})
78 host_names = group.get('hosts', [])
79 hosts = dict((name, hostvars.get(name, {})) for name in host_names)
80 return hosts
81
82
83 def ansible_environment(args: CommonConfig, color: bool = True, ansible_config: t.Optional[str] = None) -> dict[str, str]:
84 """Return a dictionary of environment variables to use when running Ansible commands."""
85 env = common_environment()
86 path = env['PATH']
87
88 ansible_bin_path = get_ansible_bin_path(args)
89
90 if not path.startswith(ansible_bin_path + os.path.pathsep):
91 path = ansible_bin_path + os.path.pathsep + path
92
93 if not ansible_config:
94 # use the default empty configuration unless one has been provided
95 ansible_config = args.get_ansible_config()
96
97 if not args.explain and not os.path.exists(ansible_config):
98 raise ApplicationError('Configuration not found: %s' % ansible_config)
99
100 ansible = dict(
101 ANSIBLE_PYTHON_MODULE_RLIMIT_NOFILE=str(SOFT_RLIMIT_NOFILE),
102 ANSIBLE_INVENTORY_PLUGIN_EXTS='.yaml, .yml, .json, .winrm, .networking', # allows the yaml/json inventory format for windows and networking
103 ANSIBLE_FORCE_COLOR='%s' % 'true' if args.color and color else 'false',
104 ANSIBLE_FORCE_HANDLERS='true', # allow cleanup handlers to run when tests fail
105 ANSIBLE_HOST_PATTERN_MISMATCH='error', # prevent tests from unintentionally passing when hosts are not found
106 ANSIBLE_INVENTORY='/dev/null', # force tests to provide inventory
107 ANSIBLE_DEPRECATION_WARNINGS='false',
108 ANSIBLE_HOST_KEY_CHECKING='false',
109 ANSIBLE_RETRY_FILES_ENABLED='false',
110 ANSIBLE_DISPLAY_TRACEBACK=args.display_traceback,
111 ANSIBLE_CONFIG=ansible_config,
112 ANSIBLE_LIBRARY='/dev/null',
113 ANSIBLE_DEVEL_WARNING='false', # Don't show warnings that CI is running devel
114 PYTHONPATH=get_ansible_python_path(args),
115 PAGER='/bin/cat',
116 PATH=path,
117 # give TQM worker processes time to report code coverage results
118 # without this the last task in a play may write no coverage file, an empty file, or an incomplete file
119 # enabled even when not using code coverage to surface warnings when worker processes do not exit cleanly
120 ANSIBLE_WORKER_SHUTDOWN_POLL_COUNT='100',
121 ANSIBLE_WORKER_SHUTDOWN_POLL_DELAY='0.1',
122 # ansible-test specific environment variables require an 'ANSIBLE_TEST_' prefix to distinguish them from ansible-core env vars defined by config
123 ANSIBLE_TEST_ANSIBLE_LIB_ROOT=ANSIBLE_LIB_ROOT, # used by the coverage injector
124 )
125
126 if isinstance(args, IntegrationConfig) and args.coverage:
127 # standard path injection is not effective for the persistent connection helper, instead the location must be configured
128 # it only requires the injector for code coverage
129 # the correct python interpreter is already selected using the sys.executable used to invoke ansible
130 ansible.update(
131 _ANSIBLE_CONNECTION_PATH=os.path.join(get_python_injector_path(), 'ansible_connection_cli_stub.py'),
132 )
133
134 if isinstance(args, PosixIntegrationConfig):
135 ansible.update(
136 ANSIBLE_PYTHON_INTERPRETER='/set/ansible_python_interpreter/in/inventory', # force tests to set ansible_python_interpreter in inventory
137 )
138
139 env.update(ansible)
140
141 if args.debug:
142 env.update(
143 ANSIBLE_DEBUG='true',
144 ANSIBLE_LOG_PATH=os.path.join(ResultType.LOGS.name, 'debug.log'),
145 )
146
147 if data_context().content.collection:
148 env.update(
149 ANSIBLE_COLLECTIONS_PATH=data_context().content.collection.root,
150 )
151
152 if data_context().content.is_ansible:
153 env.update(configure_plugin_paths(args))
154
155 return env
156
157
158 def configure_plugin_paths(args: CommonConfig) -> dict[str, str]:
159 """Return environment variables with paths to plugins relevant for the current command."""
160 if not isinstance(args, IntegrationConfig):
161 return {}
162
163 support_path = os.path.join(ANSIBLE_SOURCE_ROOT, 'test', 'support', args.command)
164
165 # provide private copies of collections for integration tests
166 collection_root = os.path.join(support_path, 'collections')
167
168 env = dict(
169 ANSIBLE_COLLECTIONS_PATH=collection_root,
170 )
171
172 # provide private copies of plugins for integration tests
173 plugin_root = os.path.join(support_path, 'plugins')
174
175 plugin_list = [
176 'action',
177 'become',
178 'cache',
179 'callback',
180 'cliconf',
181 'connection',
182 'filter',
183 'httpapi',
184 'inventory',
185 'lookup',
186 'netconf',
187 # 'shell' is not configurable
188 'strategy',
189 'terminal',
190 'test',
191 'vars',
192 ]
193
194 # most plugins follow a standard naming convention
195 plugin_map = dict(('%s_plugins' % name, name) for name in plugin_list)
196
197 # these plugins do not follow the standard naming convention
198 plugin_map.update(
199 doc_fragment='doc_fragments',
200 library='modules',
201 module_utils='module_utils',
202 )
203
204 env.update(dict(('ANSIBLE_%s' % key.upper(), os.path.join(plugin_root, value)) for key, value in plugin_map.items()))
205
206 # only configure directories which exist
207 env = dict((key, value) for key, value in env.items() if os.path.isdir(value))
208
209 return env
210
211
212 @mutex
213 def get_ansible_bin_path(args: CommonConfig) -> str:
214 """
215 Return a directory usable for PATH, containing only the ansible entry points.
216 If a temporary directory is required, it will be cached for the lifetime of the process and cleaned up at exit.
217 """
218 try:
219 return get_ansible_bin_path.bin_path # type: ignore[attr-defined]
220 except AttributeError:
221 pass
222
223 if ANSIBLE_SOURCE_ROOT:
224 # when running from source there is no need for a temporary directory since we already have known entry point scripts
225 bin_path = os.path.join(ANSIBLE_ROOT, 'bin')
226 else:
227 # when not running from source the installed entry points cannot be relied upon
228 # doing so would require using the interpreter specified by those entry points, which conflicts with using our interpreter and injector
229 # instead a temporary directory is created which contains only ansible entry points
230 # symbolic links cannot be used since the files are likely not executable
231 bin_path = create_temp_dir(prefix='ansible-test-', suffix='-bin')
232 bin_links = {os.path.join(bin_path, name): get_cli_path(path) for name, path in ANSIBLE_BIN_SYMLINK_MAP.items()}
233
234 if not args.explain:
235 for dst, src in bin_links.items():
236 shutil.copy(src, dst)
237 verified_chmod(dst, MODE_FILE_EXECUTE)
238
239 get_ansible_bin_path.bin_path = bin_path # type: ignore[attr-defined]
240
241 return bin_path
242
243
244 def get_cli_path(path: str) -> str:
245 """Return the absolute path to the CLI script from the given path which is relative to the `bin` directory of the original source tree layout."""
246 path_rewrite = {
247 '../lib/ansible/': ANSIBLE_LIB_ROOT,
248 '../test/lib/ansible_test/': ANSIBLE_TEST_ROOT,
249 }
250
251 for prefix, destination in path_rewrite.items():
252 if path.startswith(prefix):
253 return os.path.join(destination, path[len(prefix):])
254
255 raise RuntimeError(path)
256
257
258 @mutex
259 def get_ansible_python_path(args: CommonConfig) -> str:
260 """
261 Return a directory usable for PYTHONPATH, containing only the ansible package.
262 If a temporary directory is required, it will be cached for the lifetime of the process and cleaned up at exit.
263 """
264 try:
265 return get_ansible_python_path.python_path # type: ignore[attr-defined]
266 except AttributeError:
267 pass
268
269 if ANSIBLE_SOURCE_ROOT:
270 # when running from source there is no need for a temporary directory to isolate the ansible package
271 python_path = os.path.dirname(ANSIBLE_LIB_ROOT)
272 else:
273 # when not running from source the installed directory is unsafe to add to PYTHONPATH
274 # doing so would expose many unwanted packages on sys.path
275 # instead a temporary directory is created which contains only ansible using a symlink
276 python_path = create_temp_dir(prefix='ansible-test-')
277
278 os.symlink(ANSIBLE_LIB_ROOT, os.path.join(python_path, 'ansible'))
279
280 if not args.explain:
281 generate_dist_info(python_path)
282
283 get_ansible_python_path.python_path = python_path # type: ignore[attr-defined]
284
285 return python_path
286
287
288 def generate_dist_info(path: str) -> None:
289 """Generate a dist-info in the specified base directory."""
290 version = get_ansible_version()
291 metadata = f'''\
292 Metadata-Version: 2.1
293 Name: ansible-core
294 Version: {version}
295 '''
296 python_path = pathlib.Path(path)
297
298 current_dist_info = python_path / f'ansible_core-{version}.dist-info'
299
300 for dist_info in pathlib.Path(path).glob('ansible_core-*.dist-info'):
301 if dist_info == current_dist_info:
302 continue
303 shutil.rmtree(dist_info, ignore_errors=True)
304
305 metadata_path = current_dist_info / 'METADATA'
306 if metadata_path.is_file():
307 return
308
309 write_text_file(str(metadata_path), metadata, create_directories=True)
310
311
312 class CollectionDetail:
313 """Collection detail."""
314
315 def __init__(self) -> None:
316 self.version: t.Optional[str] = None
317
318
319 class CollectionDetailError(ApplicationError):
320 """An error occurred retrieving collection detail."""
321
322 def __init__(self, reason: str) -> None:
323 super().__init__('Error collecting collection detail: %s' % reason)
324 self.reason = reason
325
326
327 def get_collection_detail(python: PythonConfig) -> CollectionDetail:
328 """Return collection detail."""
329 collection = data_context().content.collection
330 directory = os.path.join(collection.root, collection.directory)
331
332 stdout = raw_command([python.path, os.path.join(ANSIBLE_TEST_TOOLS_ROOT, 'collection_detail.py'), directory], capture=True)[0]
333 result = json.loads(stdout)
334 error = result.get('error')
335
336 if error:
337 raise CollectionDetailError(error)
338
339 version = result.get('version')
340
341 detail = CollectionDetail()
342 detail.version = str(version) if version is not None else None
343
344 return detail
345
346
347 def run_playbook(
348 args: EnvironmentConfig,
349 inventory_path: str,
350 playbook: str,
351 capture: bool,
352 variables: t.Optional[dict[str, t.Any]] = None,
353 ) -> None:
354 """Run the specified playbook using the given inventory file and playbook variables."""
355 playbook_path = os.path.join(ANSIBLE_TEST_DATA_ROOT, 'playbooks', playbook)
356 cmd = ['ansible-playbook', '-i', inventory_path, playbook_path]
357
358 if variables:
359 cmd.extend(['-e', json.dumps(variables)])
360
361 if args.verbosity:
362 cmd.append('-%s' % ('v' * args.verbosity))
363
364 install_requirements(args, None, args.controller_python, ansible=True) # run_playbook()
365 env = ansible_environment(args)
366 intercept_python(args, args.controller_python, cmd, env, capture=capture)