Debian Codegraph @

test/lib/ansible_test/_internal/util_common.py

raw
1 """Common utility code that depends on CommonConfig."""
2
3 from __future__ import annotations
4
5 import collections.abc as c
6 import contextlib
7 import functools
8 import json
9 import os
10 import re
11 import shlex
12 import sys
13 import tempfile
14 import textwrap
15 import typing as t
16
17 from .constants import (
18 ANSIBLE_BIN_SYMLINK_MAP,
19 )
20
21 from .encoding import (
22 to_bytes,
23 )
24
25 from .util import (
26 cache,
27 display,
28 get_ansible_version,
29 remove_tree,
30 MODE_DIRECTORY,
31 MODE_FILE_EXECUTE,
32 MODE_FILE,
33 OutputStream,
34 PYTHON_PATHS,
35 POWERSHELL_PATHS,
36 raw_command,
37 ANSIBLE_TEST_DATA_ROOT,
38 ANSIBLE_TEST_TARGET_ROOT,
39 ANSIBLE_TEST_TARGET_TOOLS_ROOT,
40 ApplicationError,
41 SubprocessError,
42 generate_name,
43 verified_chmod,
44 )
45
46 from .io import (
47 make_dirs,
48 read_text_file,
49 write_text_file,
50 write_json_file,
51 )
52
53 from .data import (
54 data_context,
55 )
56
57 from .provider.layout import (
58 LayoutMessages,
59 )
60
61 from .host_configs import (
62 PythonConfig,
63 VirtualPythonConfig,
64 PowerShellConfig,
65 )
66
67 CHECK_YAML_VERSIONS: dict[str, t.Any] = {}
68
69
70 class ExitHandler:
71 """Simple exit handler implementation."""
72
73 _callbacks: list[tuple[t.Callable, tuple[t.Any, ...], dict[str, t.Any]]] = []
74
75 @staticmethod
76 def register(func: t.Callable, *args, **kwargs) -> None:
77 """Register the given function and args as a callback to execute during program termination."""
78 ExitHandler._callbacks.append((func, args, kwargs))
79
80 @staticmethod
81 @contextlib.contextmanager
82 def context() -> t.Generator[None, None, None]:
83 """Run all registered handlers when the context is exited."""
84 last_exception: BaseException | None = None
85
86 try:
87 yield
88 finally:
89 queue = list(ExitHandler._callbacks)
90
91 while queue:
92 func, args, kwargs = queue.pop()
93
94 try:
95 func(*args, **kwargs)
96 except BaseException as ex: # pylint: disable=broad-exception-caught
97 last_exception = ex
98 display.fatal(f'Exit handler failed: {ex}')
99
100 if last_exception:
101 raise last_exception
102
103
104 class ShellScriptTemplate:
105 """A simple substitution template for shell scripts."""
106
107 def __init__(self, template: str) -> None:
108 self.template = template
109
110 def substitute(self, **kwargs: t.Union[str, list[str]]) -> str:
111 """Return a string templated with the given arguments."""
112 kvp = dict((k, self.quote(v)) for k, v in kwargs.items())
113 pattern = re.compile(r'#{(?P<name>[^}]+)}')
114 value = pattern.sub(lambda match: kvp[match.group('name')], self.template)
115 return value
116
117 @staticmethod
118 def quote(value: t.Union[str, list[str]]) -> str:
119 """Return a shell quoted version of the given value."""
120 if isinstance(value, list):
121 return shlex.quote(' '.join(value))
122
123 return shlex.quote(value)
124
125
126 class ResultType:
127 """Test result type."""
128
129 BOT: ResultType = None
130 COVERAGE: ResultType = None
131 DATA: ResultType = None
132 JUNIT: ResultType = None
133 LOGS: ResultType = None
134 REPORTS: ResultType = None
135 TMP: ResultType = None
136
137 @staticmethod
138 def _populate() -> None:
139 ResultType.BOT = ResultType('bot')
140 ResultType.COVERAGE = ResultType('coverage')
141 ResultType.DATA = ResultType('data')
142 ResultType.JUNIT = ResultType('junit')
143 ResultType.LOGS = ResultType('logs')
144 ResultType.REPORTS = ResultType('reports')
145 ResultType.TMP = ResultType('.tmp')
146
147 def __init__(self, name: str) -> None:
148 self.name = name
149
150 @property
151 def relative_path(self) -> str:
152 """The content relative path to the results."""
153 return os.path.join(data_context().content.results_path, self.name)
154
155 @property
156 def path(self) -> str:
157 """The absolute path to the results."""
158 return os.path.join(data_context().content.root, self.relative_path)
159
160 def __str__(self) -> str:
161 return self.name
162
163
164 # noinspection PyProtectedMember
165 ResultType._populate() # pylint: disable=protected-access
166
167
168 class CommonConfig:
169 """Configuration common to all commands."""
170
171 def __init__(self, args: t.Any, command: str) -> None:
172 self.command = command
173 self.interactive = False
174 self.check_layout = True
175 self.success: t.Optional[bool] = None
176
177 self.color: bool = args.color
178 self.explain: bool = args.explain
179 self.verbosity: int = args.verbosity
180 self.debug: bool = args.debug
181 self.truncate: int = args.truncate
182 self.redact: bool = args.redact
183 self.display_traceback: str = args.display_traceback
184
185 self.display_stderr: bool = False
186
187 self.session_name = generate_name()
188
189 self.cache: dict[str, t.Any] = {}
190
191 def get_ansible_config(self) -> str:
192 """Return the path to the Ansible config for the given config."""
193 return os.path.join(ANSIBLE_TEST_DATA_ROOT, 'ansible.cfg')
194
195
196 def get_docs_url(url: str) -> str:
197 """
198 Return the given docs.ansible.com URL updated to match the running ansible-test version, if it is not a pre-release version.
199 The URL should be in the form: https://docs.ansible.com/ansible/devel/path/to/doc.html
200 Where 'devel' will be replaced with the current version, unless it is a pre-release version.
201 When run under a pre-release version, the URL will remain unchanged.
202 This serves to provide a fallback URL for pre-release versions.
203 It also makes searching the source for docs links easier, since a full URL is provided to this function.
204 """
205 url_prefix = 'https://docs.ansible.com/ansible-core/devel/'
206
207 if not url.startswith(url_prefix):
208 raise ValueError(f'URL "{url}" does not start with: {url_prefix}')
209
210 ansible_version = get_ansible_version()
211
212 if re.search(r'^[0-9.]+$', ansible_version):
213 url_version = '.'.join(ansible_version.split('.')[:2])
214 new_prefix = f'https://docs.ansible.com/ansible-core/{url_version}/'
215
216 url = url.replace(url_prefix, new_prefix)
217
218 return url
219
220
221 def create_result_directories(args: CommonConfig) -> None:
222 """Create result directories."""
223 if args.explain:
224 return
225
226 make_dirs(ResultType.COVERAGE.path)
227 make_dirs(ResultType.DATA.path)
228
229
230 def handle_layout_messages(messages: t.Optional[LayoutMessages]) -> None:
231 """Display the given layout messages."""
232 if not messages:
233 return
234
235 for message in messages.info:
236 display.info(message, verbosity=1)
237
238 for message in messages.warning:
239 display.warning(message)
240
241 if messages.error:
242 raise ApplicationError('\n'.join(messages.error))
243
244
245 def process_scoped_temporary_file(args: CommonConfig, prefix: t.Optional[str] = 'ansible-test-', suffix: t.Optional[str] = None) -> str:
246 """Return the path to a temporary file that will be automatically removed when the process exits."""
247 if args.explain:
248 path = os.path.join(tempfile.gettempdir(), f'{prefix or tempfile.gettempprefix()}{generate_name()}{suffix or ""}')
249 else:
250 temp_fd, path = tempfile.mkstemp(prefix=prefix, suffix=suffix)
251 os.close(temp_fd)
252 ExitHandler.register(lambda: os.remove(path))
253
254 return path
255
256
257 def process_scoped_temporary_directory(args: CommonConfig, prefix: t.Optional[str] = 'ansible-test-', suffix: t.Optional[str] = None) -> str:
258 """Return the path to a temporary directory that will be automatically removed when the process exits."""
259 if args.explain:
260 path = os.path.join(tempfile.gettempdir(), f'{prefix or tempfile.gettempprefix()}{generate_name()}{suffix or ""}')
261 else:
262 path = tempfile.mkdtemp(prefix=prefix, suffix=suffix)
263 ExitHandler.register(lambda: remove_tree(path))
264
265 return path
266
267
268 @contextlib.contextmanager
269 def named_temporary_file(args: CommonConfig, prefix: str, suffix: str, directory: t.Optional[str], content: str) -> c.Iterator[str]:
270 """Context manager for a named temporary file."""
271 if args.explain:
272 yield os.path.join(directory or '/tmp', '%stemp%s' % (prefix, suffix))
273 else:
274 with tempfile.NamedTemporaryFile(prefix=prefix, suffix=suffix, dir=directory) as tempfile_fd:
275 tempfile_fd.write(to_bytes(content))
276 tempfile_fd.flush()
277
278 try:
279 yield tempfile_fd.name
280 finally:
281 pass
282
283
284 def write_json_test_results(
285 category: ResultType,
286 name: str,
287 content: t.Union[list[t.Any], dict[str, t.Any]],
288 formatted: bool = True,
289 encoder: t.Optional[t.Type[json.JSONEncoder]] = None,
290 ) -> None:
291 """Write the given json content to the specified test results path, creating directories as needed."""
292 path = os.path.join(category.path, name)
293 write_json_file(path, content, create_directories=True, formatted=formatted, encoder=encoder)
294
295
296 def write_text_test_results(category: ResultType, name: str, content: str) -> None:
297 """Write the given text content to the specified test results path, creating directories as needed."""
298 path = os.path.join(category.path, name)
299 write_text_file(path, content, create_directories=True)
300
301
302 @cache
303 def get_python_injector_path() -> str:
304 """Return the path to a directory which contains a `python.py` executable and associated injector scripts."""
305 injector_path = tempfile.mkdtemp(prefix='ansible-test-', suffix='-injector', dir='/tmp')
306
307 display.info(f'Initializing "{injector_path}" as the temporary injector directory.', verbosity=1)
308
309 injector_names = sorted(list(ANSIBLE_BIN_SYMLINK_MAP) + [
310 'importer.py',
311 'pytest',
312 'ansible_connection_cli_stub.py',
313 ])
314
315 scripts = (
316 ('python.py', '/usr/bin/env python', MODE_FILE_EXECUTE),
317 ('virtualenv.sh', '/usr/bin/env bash', MODE_FILE),
318 )
319
320 source_path = os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'injector')
321
322 for name in injector_names:
323 os.symlink('python.py', os.path.join(injector_path, name))
324
325 for name, shebang, mode in scripts:
326 src = os.path.join(source_path, name)
327 dst = os.path.join(injector_path, name)
328
329 script = read_text_file(src)
330 script = set_shebang(script, shebang)
331
332 write_text_file(dst, script)
333 verified_chmod(dst, mode)
334
335 verified_chmod(injector_path, MODE_DIRECTORY)
336
337 def cleanup_injector() -> None:
338 """Remove the temporary injector directory."""
339 remove_tree(injector_path)
340
341 ExitHandler.register(cleanup_injector)
342
343 return injector_path
344
345
346 def set_shebang(script: str, executable: str) -> str:
347 """Return the given script with the specified executable used for the shebang."""
348 prefix = '#!'
349 shebang = prefix + executable
350
351 overwrite = (
352 prefix,
353 '# auto-shebang',
354 '# shellcheck shell=',
355 )
356
357 lines = script.splitlines()
358
359 if any(lines[0].startswith(value) for value in overwrite):
360 lines[0] = shebang
361 else:
362 lines.insert(0, shebang)
363
364 script = '\n'.join(lines)
365
366 return script
367
368
369 def get_python_path(interpreter: str) -> str:
370 """Return the path to a directory which contains a `python` executable that runs the specified interpreter."""
371 return get_injection_wrapper(interpreter, 'python', PYTHON_PATHS)
372
373
374 def get_powershell_path(interpreter: str) -> str:
375 """Return the path to a directory which contains a `pwsh` executable that runs the specified interpreter."""
376 return get_injection_wrapper(interpreter, 'pwsh', POWERSHELL_PATHS)
377
378
379 def get_injection_wrapper(interpreter: str, name: str, cached_paths: dict[str, str]) -> str:
380 """Return the path to a directory which contains the named executable that runs the specified interpreter."""
381 injected_path = cached_paths.get(interpreter)
382
383 if injected_path:
384 return injected_path
385
386 prefix = f'{name}-'
387 suffix = '-ansible'
388
389 root_temp_dir = '/tmp'
390
391 injected_path = tempfile.mkdtemp(prefix=prefix, suffix=suffix, dir=root_temp_dir)
392 injected_interpreter = os.path.join(injected_path, name)
393
394 # A symlink is faster than the execv wrapper, but isn't guaranteed to provide the correct result.
395 # There are several scenarios known not to work with symlinks:
396 #
397 # - A virtual environment where the target is a symlink to another directory.
398 # - A pyenv environment where the target is a shell script that changes behavior based on the program name.
399 #
400 # To avoid issues for these and other scenarios, only an exec wrapper is used.
401
402 display.info('Injecting "%s" as a execv wrapper for the "%s" interpreter.' % (injected_interpreter, interpreter), verbosity=1)
403
404 create_interpreter_wrapper(interpreter, injected_interpreter)
405
406 verified_chmod(injected_path, MODE_DIRECTORY)
407
408 if not cached_paths:
409 ExitHandler.register(functools.partial(cleanup_injector_paths, cached_paths))
410
411 cached_paths[interpreter] = injected_path
412
413 return injected_path
414
415
416 def create_temp_dir(prefix: t.Optional[str] = None, suffix: t.Optional[str] = None, base_dir: t.Optional[str] = None) -> str:
417 """Create a temporary directory that persists until the current process exits."""
418 temp_path = tempfile.mkdtemp(prefix=prefix or 'tmp', suffix=suffix or '', dir=base_dir)
419 ExitHandler.register(remove_tree, temp_path)
420 return temp_path
421
422
423 def create_interpreter_wrapper(interpreter: str, injected_interpreter: str) -> None:
424 """Create a wrapper for the given interpreter at the specified path."""
425 # sys.executable is used for the shebang to guarantee it is a binary instead of a script
426 # injected_interpreter could be a script from the system or our own wrapper created for the --venv option
427 shebang_interpreter = sys.executable
428
429 code = textwrap.dedent(f"""
430 #!{shebang_interpreter}
431
432 from __future__ import annotations
433
434 from os import execv
435 from sys import argv
436
437 interpreter = {interpreter!r}
438
439 execv(interpreter, [interpreter] + argv[1:])
440 """).lstrip()
441
442 write_text_file(injected_interpreter, code)
443
444 verified_chmod(injected_interpreter, MODE_FILE_EXECUTE)
445
446
447 def cleanup_injector_paths(cached_paths: dict[str, str]) -> None:
448 """Clean up all temporary injector directories."""
449 for path in sorted(cached_paths.values()):
450 display.info(f'Cleaning up temporary injector directory: {path}', verbosity=2)
451 remove_tree(path)
452
453
454 def intercept_python(
455 args: CommonConfig,
456 python: PythonConfig,
457 cmd: list[str],
458 env: dict[str, str],
459 capture: bool,
460 data: t.Optional[str] = None,
461 cwd: t.Optional[str] = None,
462 always: bool = False,
463 ) -> tuple[t.Optional[str], t.Optional[str]]:
464 """
465 Run a command while intercepting invocations of Python to control the version used.
466 If the specified Python is an ansible-test managed virtual environment, it will be added to PATH to activate it.
467 Otherwise, a temporary directory will be created to ensure the correct Python can be found in PATH.
468 """
469 cmd = list(cmd)
470 env = get_python_injector_env(python, env)
471
472 return run_command(args, cmd, capture=capture, env=env, data=data, cwd=cwd, always=always)
473
474
475 def get_python_injector_env(
476 python: PythonConfig,
477 env: dict[str, str],
478 ) -> dict[str, str]:
479 """Get the environment variables needed to inject the given Python interpreter into the environment."""
480 env = env.copy()
481 inject_path = get_python_injector_path()
482
483 # make sure scripts (including injector.py) find the correct Python interpreter
484 if isinstance(python, VirtualPythonConfig):
485 python_path = os.path.dirname(python.path)
486 else:
487 python_path = get_python_path(python.path)
488
489 env['PATH'] = os.path.pathsep.join([inject_path, python_path, env['PATH']])
490 env['ANSIBLE_TEST_PYTHON_VERSION'] = python.version
491 env['ANSIBLE_TEST_PYTHON_INTERPRETER'] = python.path
492
493 return env
494
495
496 def get_powershell_injector_env(
497 powershell: PowerShellConfig | None,
498 env: dict[str, str],
499 ) -> dict[str, str]:
500 """Get the environment variables needed to inject the given PowerShell interpreter into the environment."""
501 env = env.copy()
502
503 if not powershell or not powershell.path:
504 return env
505
506 powershell_path = get_powershell_path(powershell.path)
507
508 env['PATH'] = os.path.pathsep.join([powershell_path, env['PATH']])
509 env['ANSIBLE_TEST_POWERSHELL_INTERPRETER'] = powershell.path
510
511 return env
512
513
514 def run_command(
515 args: CommonConfig,
516 cmd: c.Iterable[str],
517 capture: bool,
518 env: t.Optional[dict[str, str]] = None,
519 data: t.Optional[str] = None,
520 cwd: t.Optional[str] = None,
521 always: bool = False,
522 stdin: t.Optional[t.IO[bytes]] = None,
523 stdout: t.Optional[t.IO[bytes]] = None,
524 interactive: bool = False,
525 output_stream: t.Optional[OutputStream] = None,
526 cmd_verbosity: int = 1,
527 str_errors: str = 'strict',
528 error_callback: t.Optional[c.Callable[[SubprocessError], None]] = None,
529 ) -> tuple[t.Optional[str], t.Optional[str]]:
530 """Run the specified command and return stdout and stderr as a tuple."""
531 explain = args.explain and not always
532 return raw_command(
533 cmd,
534 capture=capture,
535 env=env,
536 data=data,
537 cwd=cwd,
538 explain=explain,
539 stdin=stdin,
540 stdout=stdout,
541 interactive=interactive,
542 output_stream=output_stream,
543 cmd_verbosity=cmd_verbosity,
544 str_errors=str_errors,
545 error_callback=error_callback,
546 )
547
548
549 def yamlcheck(python: PythonConfig, explain: bool = False) -> t.Optional[bool]:
550 """Return True if PyYAML has libyaml support, False if it does not and None if it was not found."""
551 stdout = raw_command([python.path, os.path.join(ANSIBLE_TEST_TARGET_TOOLS_ROOT, 'yamlcheck.py')], capture=True, explain=explain)[0]
552
553 if explain:
554 return None
555
556 result = json.loads(stdout)
557
558 if not result['yaml']:
559 return None
560
561 return result['cloader']
562
563
564 def check_pyyaml(python: PythonConfig, required: bool = True, quiet: bool = False) -> t.Optional[bool]:
565 """
566 Return True if PyYAML has libyaml support, False if it does not and None if it was not found.
567 The result is cached if True or required.
568 """
569 try:
570 return CHECK_YAML_VERSIONS[python.path]
571 except KeyError:
572 pass
573
574 state = yamlcheck(python)
575
576 if state is not None or required:
577 # results are cached only if pyyaml is required or present
578 # it is assumed that tests will not uninstall/re-install pyyaml -- if they do, those changes will go undetected
579 CHECK_YAML_VERSIONS[python.path] = state
580
581 if not quiet:
582 if state is None:
583 if required:
584 display.warning('PyYAML is not installed for interpreter: %s' % python.path)
585 elif not state:
586 display.warning('PyYAML will be slow due to installation without libyaml support for interpreter: %s' % python.path)
587
588 return state