Debian Codegraph @

test/lib/ansible_test/_internal/util.py

raw
1 """Miscellaneous utility functions and classes."""
2
3 from __future__ import annotations
4
5 import abc
6 import collections.abc as c
7 import enum
8 import fcntl
9 import importlib.util
10 import inspect
11 import json
12 import keyword
13 import os
14 import platform
15 import pkgutil
16 import random
17 import re
18 import shutil
19 import stat
20 import string
21 import subprocess
22 import sys
23 import time
24 import functools
25 import shlex
26 import typing as t
27 import warnings
28
29 from struct import unpack, pack
30 from termios import TIOCGWINSZ
31
32 # CAUTION: Avoid third-party imports in this module whenever possible.
33 # Any third-party imports occurring here will result in an error if they are vendored by ansible-core.
34
35 from .locale_util import (
36 LOCALE_WARNING,
37 CONFIGURED_LOCALE,
38 )
39
40 from .encoding import (
41 to_bytes,
42 to_optional_bytes,
43 to_optional_text,
44 )
45
46 from .io import (
47 open_binary_file,
48 read_text_file,
49 )
50
51 from .thread import (
52 mutex,
53 WrappedThread,
54 )
55
56 from .constants import (
57 SUPPORTED_PYTHON_VERSIONS,
58 SUPPORTED_POWERSHELL_VERSIONS,
59 )
60
61 PYTHON_PATHS: dict[str, str] = {}
62 POWERSHELL_PATHS: dict[str, str] = {}
63
64 COVERAGE_CONFIG_NAME = 'coveragerc'
65
66 ANSIBLE_TEST_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
67
68 # assume running from install
69 ANSIBLE_ROOT = os.path.dirname(ANSIBLE_TEST_ROOT)
70 ANSIBLE_LIB_ROOT = os.path.join(ANSIBLE_ROOT, 'ansible')
71 ANSIBLE_SOURCE_ROOT = None
72
73 if not os.path.exists(ANSIBLE_LIB_ROOT):
74 # running from source
75 ANSIBLE_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(ANSIBLE_TEST_ROOT)))
76 ANSIBLE_LIB_ROOT = os.path.join(ANSIBLE_ROOT, 'lib', 'ansible')
77 ANSIBLE_SOURCE_ROOT = ANSIBLE_ROOT
78
79 ANSIBLE_TEST_DATA_ROOT = os.path.join(ANSIBLE_TEST_ROOT, '_data')
80 ANSIBLE_TEST_UTIL_ROOT = os.path.join(ANSIBLE_TEST_ROOT, '_util')
81 ANSIBLE_TEST_CONFIG_ROOT = os.path.join(ANSIBLE_TEST_ROOT, 'config')
82
83 ANSIBLE_TEST_CONTROLLER_ROOT = os.path.join(ANSIBLE_TEST_UTIL_ROOT, 'controller')
84 ANSIBLE_TEST_TARGET_ROOT = os.path.join(ANSIBLE_TEST_UTIL_ROOT, 'target')
85
86 ANSIBLE_TEST_TOOLS_ROOT = os.path.join(ANSIBLE_TEST_CONTROLLER_ROOT, 'tools')
87 ANSIBLE_TEST_TARGET_TOOLS_ROOT = os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'tools')
88
89 # Modes are set to allow all users the same level of access.
90 # This permits files to be used in tests that change users.
91 # The only exception is write access to directories for the user creating them.
92 # This avoids having to modify the directory permissions a second time.
93
94 MODE_READ = stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
95
96 MODE_FILE = MODE_READ
97 MODE_FILE_EXECUTE = MODE_FILE | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
98 MODE_FILE_WRITE = MODE_FILE | stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH
99
100 MODE_DIRECTORY = MODE_READ | stat.S_IWUSR | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
101 MODE_DIRECTORY_WRITE = MODE_DIRECTORY | stat.S_IWGRP | stat.S_IWOTH
102
103
104 class OutputStream(enum.Enum):
105 """The output stream to use when running a subprocess and redirecting/capturing stdout or stderr."""
106
107 ORIGINAL = enum.auto()
108 AUTO = enum.auto()
109
110 def get_buffer(self, original: t.BinaryIO) -> t.BinaryIO:
111 """Return the correct output buffer to use, taking into account the given original buffer."""
112
113 if self == OutputStream.ORIGINAL:
114 return original
115
116 if self == OutputStream.AUTO:
117 return display.fd.buffer
118
119 raise NotImplementedError(str(self))
120
121
122 class Architecture:
123 """
124 Normalized architecture names.
125 These are the architectures supported by ansible-test, such as when provisioning remote instances.
126 """
127
128 X86_64 = 'x86_64'
129 AARCH64 = 'aarch64'
130
131
132 REMOTE_ARCHITECTURES = list(value for key, value in Architecture.__dict__.items() if not key.startswith('__'))
133
134
135 WINDOWS_CONNECTION_VARIABLES: dict[str, t.Any] = {
136 'psrp+http': dict(
137 ansible_port=5985,
138 ansible_psrp_protocol='http',
139 use_password=True,
140 ),
141 'psrp+https': dict(
142 ansible_port=5986,
143 ansible_psrp_protocol='https',
144 ansible_psrp_cert_validation='ignore',
145 use_password=True,
146 ),
147 'ssh+key': dict(
148 ansible_port=22,
149 ansible_shell_type='powershell',
150 use_password=False,
151 ),
152 'ssh+password': dict(
153 ansible_port=22,
154 ansible_shell_type='powershell',
155 use_password=True,
156 ),
157 'winrm+http': dict(
158 ansible_port=5985,
159 ansible_winrm_scheme='http',
160 ansible_winrm_transport='ntlm',
161 use_password=True,
162 ),
163 'winrm+https': dict(
164 ansible_port=5986,
165 ansible_winrm_scheme='https',
166 ansible_winrm_server_cert_validation='ignore',
167 use_password=True,
168 ),
169 }
170 """Dictionary of Windows connection types and variables required to use them."""
171
172 WINDOWS_CONNECTIONS = list(WINDOWS_CONNECTION_VARIABLES)
173
174
175 def is_valid_identifier(value: str) -> bool:
176 """Return True if the given value is a valid non-keyword Python identifier, otherwise return False."""
177 return value.isidentifier() and not keyword.iskeyword(value)
178
179
180 def cache[TValue](func: c.Callable[[], TValue]) -> c.Callable[[], TValue]:
181 """Enforce exclusive access on a decorated function and cache the result."""
182 storage: dict[None, TValue] = {}
183 cache_sentinel = object()
184
185 @functools.wraps(func)
186 def cache_func():
187 """Cache the return value from func."""
188 if (value := storage.get(None, cache_sentinel)) is cache_sentinel:
189 value = storage[None] = func()
190
191 return value
192
193 wrapper = mutex(cache_func)
194
195 return wrapper
196
197
198 @mutex
199 def detect_architecture(python: str) -> t.Optional[str]:
200 """Detect the architecture of the specified Python and return a normalized version, or None if it cannot be determined."""
201 results: dict[str, t.Optional[str]]
202
203 try:
204 results = detect_architecture.results # type: ignore[attr-defined]
205 except AttributeError:
206 results = detect_architecture.results = {} # type: ignore[attr-defined]
207
208 if python in results:
209 return results[python]
210
211 if python == sys.executable or os.path.realpath(python) == os.path.realpath(sys.executable):
212 uname = platform.uname()
213 else:
214 data = raw_command([python, '-c', 'import json, platform; print(json.dumps(platform.uname()));'], capture=True)[0]
215 uname = json.loads(data)
216
217 translation = {
218 'x86_64': Architecture.X86_64, # Linux, macOS
219 'amd64': Architecture.X86_64, # FreeBSD
220 'aarch64': Architecture.AARCH64, # Linux, FreeBSD
221 'arm64': Architecture.AARCH64, # FreeBSD
222 }
223
224 candidates = []
225
226 if len(uname) >= 5:
227 candidates.append(uname[4])
228
229 if len(uname) >= 6:
230 candidates.append(uname[5])
231
232 candidates = sorted(set(candidates))
233 architectures = sorted(set(arch for arch in [translation.get(candidate) for candidate in candidates] if arch))
234
235 architecture: t.Optional[str] = None
236
237 if not architectures:
238 display.warning(f'Unable to determine architecture for Python interpreter "{python}" from: {candidates}')
239 elif len(architectures) == 1:
240 architecture = architectures[0]
241 display.info(f'Detected architecture {architecture} for Python interpreter: {python}', verbosity=1)
242 else:
243 display.warning(f'Conflicting architectures detected ({architectures}) for Python interpreter "{python}" from: {candidates}')
244
245 results[python] = architecture
246
247 return architecture
248
249
250 def filter_args(args: list[str], filters: dict[str, int]) -> list[str]:
251 """Return a filtered version of the given command line arguments."""
252 remaining = 0
253 result = []
254 pass_through_args: list[str] = []
255 pass_through_explicit = False
256 pass_through_implicit = False
257
258 for arg in args:
259 if pass_through_explicit:
260 pass_through_args.append(arg)
261 continue
262
263 if arg == '--':
264 pass_through_explicit = True
265 continue
266
267 if not arg.startswith('-') and remaining:
268 remaining -= 1
269 pass_through_implicit = not remaining
270 continue
271
272 if not arg.startswith('-') and pass_through_implicit:
273 pass_through_args.append(arg)
274 continue
275
276 pass_through_implicit = False
277 remaining = 0
278
279 parts = arg.split('=', 1)
280 key = parts[0]
281
282 if key in filters:
283 remaining = filters[key] - len(parts) + 1
284 continue
285
286 result.append(arg)
287
288 if pass_through_args:
289 result += ['--'] + pass_through_args
290
291 return result
292
293
294 def read_lines_without_comments(path: str, remove_blank_lines: bool = False, optional: bool = False) -> list[str]:
295 """
296 Returns lines from the specified text file with comments removed.
297 Comments are any content from a hash symbol to the end of a line.
298 Any spaces immediately before a comment are also removed.
299 """
300 if optional and not os.path.exists(path):
301 return []
302
303 lines = read_text_file(path).splitlines()
304
305 lines = [re.sub(r' *#.*$', '', line) for line in lines]
306
307 if remove_blank_lines:
308 lines = [line for line in lines if line]
309
310 return lines
311
312
313 def exclude_none_values[TKey, TValue](data: dict[TKey, t.Optional[TValue]]) -> dict[TKey, TValue]:
314 """Return the provided dictionary with any None values excluded."""
315 return dict((key, value) for key, value in data.items() if value is not None)
316
317
318 def find_executable(executable: str, cwd: t.Optional[str] = None, path: t.Optional[str] = None, required: t.Union[bool, str] = True) -> t.Optional[str]:
319 """
320 Find the specified executable and return the full path, or None if it could not be found.
321 If required is True an exception will be raised if the executable is not found.
322 If required is set to 'warning' then a warning will be shown if the executable is not found.
323 """
324 match = None
325 real_cwd = os.getcwd()
326
327 if not cwd:
328 cwd = real_cwd
329
330 if os.path.dirname(executable):
331 target = os.path.join(cwd, executable)
332 if os.path.exists(target) and os.access(target, os.F_OK | os.X_OK):
333 match = executable
334 else:
335 if path is None:
336 path = os.environ.get('PATH', os.path.defpath)
337
338 if path:
339 path_dirs = path.split(os.path.pathsep)
340 seen_dirs = set()
341
342 for path_dir in path_dirs:
343 if path_dir in seen_dirs:
344 continue
345
346 seen_dirs.add(path_dir)
347
348 if os.path.abspath(path_dir) == real_cwd:
349 path_dir = cwd
350
351 candidate = os.path.join(path_dir, executable)
352
353 if os.path.exists(candidate) and os.access(candidate, os.F_OK | os.X_OK):
354 match = candidate
355 break
356
357 if not match and required:
358 message = 'Required program "%s" not found.' % executable
359
360 if required != 'warning':
361 raise ApplicationError(message)
362
363 display.warning(message)
364
365 return match
366
367
368 def find_python(version: str, path: t.Optional[str] = None, required: bool = True) -> t.Optional[str]:
369 """
370 Find and return the full path to the specified Python version.
371 If required, an exception will be raised not found.
372 If not required, None will be returned if not found.
373 """
374 version_info = str_to_version(version)
375
376 if not path and version_info == sys.version_info[:len(version_info)]:
377 python_bin = sys.executable
378 else:
379 python_bin = find_executable('python%s' % version, path=path, required=required)
380
381 return python_bin
382
383
384 @cache
385 def get_ansible_version() -> str:
386 """Return the Ansible version."""
387 # ansible may not be in our sys.path
388 # avoids a symlink to release.py since ansible placement relative to ansible-test may change during delegation
389 load_module(os.path.join(ANSIBLE_LIB_ROOT, 'release.py'), 'ansible_release')
390
391 # noinspection PyUnresolvedReferences
392 from ansible_release import __version__ as ansible_version # pylint: disable=import-error
393
394 return ansible_version
395
396
397 def _enable_vendoring() -> None:
398 """Enable support for loading Python packages vendored by ansible-core."""
399 # Load the vendoring code by file path, since ansible may not be in our sys.path.
400 # Convert warnings into errors, to avoid problems from surfacing later.
401
402 with warnings.catch_warnings():
403 warnings.filterwarnings('error')
404
405 load_module(os.path.join(ANSIBLE_LIB_ROOT, '_vendor', '__init__.py'), 'ansible_vendor')
406
407
408 @cache
409 def get_available_python_versions() -> dict[str, str]:
410 """Return a dictionary indicating which supported Python versions are available."""
411 return dict((version, path) for version, path in ((version, find_python(version, required=False)) for version in SUPPORTED_PYTHON_VERSIONS) if path)
412
413
414 def raw_command(
415 cmd: c.Iterable[str],
416 capture: bool,
417 env: t.Optional[dict[str, str]] = None,
418 data: t.Optional[str] = None,
419 cwd: t.Optional[str] = None,
420 explain: bool = False,
421 stdin: t.Optional[t.Union[t.IO[bytes], int]] = None,
422 stdout: t.Optional[t.Union[t.IO[bytes], int]] = None,
423 interactive: bool = False,
424 output_stream: t.Optional[OutputStream] = None,
425 cmd_verbosity: int = 1,
426 str_errors: str = 'strict',
427 error_callback: t.Optional[c.Callable[[SubprocessError], None]] = None,
428 ) -> tuple[t.Optional[str], t.Optional[str]]:
429 """Run the specified command and return stdout and stderr as a tuple."""
430 output_stream = output_stream or OutputStream.AUTO
431
432 if capture and interactive:
433 raise InternalError('Cannot combine capture=True with interactive=True.')
434
435 if data and interactive:
436 raise InternalError('Cannot combine data with interactive=True.')
437
438 if stdin and interactive:
439 raise InternalError('Cannot combine stdin with interactive=True.')
440
441 if stdout and interactive:
442 raise InternalError('Cannot combine stdout with interactive=True.')
443
444 if stdin and data:
445 raise InternalError('Cannot combine stdin with data.')
446
447 if stdout and not capture:
448 raise InternalError('Redirection of stdout requires capture=True to avoid redirection of stderr to stdout.')
449
450 if output_stream != OutputStream.AUTO and capture:
451 raise InternalError(f'Cannot combine {output_stream=} with capture=True.')
452
453 if output_stream != OutputStream.AUTO and interactive:
454 raise InternalError(f'Cannot combine {output_stream=} with interactive=True.')
455
456 if not cwd:
457 cwd = os.getcwd()
458
459 if not env:
460 env = common_environment()
461
462 cmd = list(cmd)
463
464 escaped_cmd = shlex.join(cmd)
465
466 if capture:
467 description = 'Run'
468 elif interactive:
469 description = 'Interactive'
470 else:
471 description = 'Stream'
472
473 description += ' command'
474
475 with_types = []
476
477 if data:
478 with_types.append('data')
479
480 if stdin:
481 with_types.append('stdin')
482
483 if stdout:
484 with_types.append('stdout')
485
486 if with_types:
487 description += f' with {"/".join(with_types)}'
488
489 display.info(f'{description}: {escaped_cmd}', verbosity=cmd_verbosity, truncate=True)
490 display.info('Working directory: %s' % cwd, verbosity=2)
491
492 program = find_executable(cmd[0], cwd=cwd, path=env['PATH'], required=False)
493
494 if program:
495 display.info('Program found: %s' % program, verbosity=2)
496
497 for key in sorted(env.keys()):
498 display.info('%s=%s' % (key, env[key]), verbosity=2)
499
500 if explain:
501 return None, None
502
503 communicate = False
504
505 if stdin is not None:
506 data = None
507 elif data is not None:
508 stdin = subprocess.PIPE
509 communicate = True
510 elif interactive:
511 pass # allow the subprocess access to our stdin
512 else:
513 stdin = subprocess.DEVNULL
514
515 if not interactive:
516 # When not running interactively, send subprocess stdout/stderr through a pipe.
517 # This isolates the stdout/stderr of the subprocess from the current process, and also hides the current TTY from it, if any.
518 # This prevents subprocesses from sharing stdout/stderr with the current process or each other.
519 # Doing so allows subprocesses to safely make changes to their file handles, such as making them non-blocking (ssh does this).
520 # This also maintains consistency between local testing and CI systems, which typically do not provide a TTY.
521 # To maintain output ordering, a single pipe is used for both stdout/stderr when not capturing output unless the output stream is ORIGINAL.
522 stdout = stdout or subprocess.PIPE
523 stderr = subprocess.PIPE if capture or output_stream == OutputStream.ORIGINAL else subprocess.STDOUT
524 communicate = True
525 else:
526 stderr = None
527
528 start = time.time()
529 process = None
530
531 try:
532 try:
533 process = subprocess.Popen(cmd, env=env, stdin=stdin, stdout=stdout, stderr=stderr, cwd=cwd) # pylint: disable=consider-using-with
534 except FileNotFoundError as ex:
535 raise ApplicationError('Required program "%s" not found.' % cmd[0]) from ex
536
537 if communicate:
538 data_bytes = to_optional_bytes(data)
539
540 stdout_bytes, stderr_bytes = communicate_with_process(
541 name=cmd[0],
542 process=process,
543 stdin=data_bytes,
544 stdout=stdout == subprocess.PIPE,
545 stderr=stderr == subprocess.PIPE,
546 capture=capture,
547 output_stream=output_stream,
548 )
549
550 stdout_text = to_optional_text(stdout_bytes, str_errors) or ''
551 stderr_text = to_optional_text(stderr_bytes, str_errors) or ''
552 else:
553 process.wait()
554 stdout_text, stderr_text = None, None
555 finally:
556 if process and process.returncode is None:
557 process.kill()
558 display.info('') # the process we're interrupting may have completed a partial line of output
559 display.notice('Killed command to avoid an orphaned child process during handling of an unexpected exception.')
560
561 status = process.returncode
562 runtime = time.time() - start
563
564 display.info('Command exited with status %s after %s seconds.' % (status, runtime), verbosity=4)
565
566 if status == 0:
567 return stdout_text, stderr_text
568
569 raise SubprocessError(cmd, status, stdout_text, stderr_text, runtime, error_callback)
570
571
572 def communicate_with_process(
573 name: str,
574 process: subprocess.Popen,
575 stdin: t.Optional[bytes],
576 stdout: bool,
577 stderr: bool,
578 capture: bool,
579 output_stream: OutputStream,
580 ) -> tuple[bytes, bytes]:
581 """Communicate with the specified process, handling stdin/stdout/stderr as requested."""
582 threads: list[WrappedThread] = []
583 reader: t.Type[ReaderThread]
584
585 if capture:
586 reader = CaptureThread
587 else:
588 reader = OutputThread
589
590 if stdin is not None:
591 threads.append(WriterThread(process.stdin, stdin, name))
592
593 if stdout:
594 stdout_reader = reader(process.stdout, output_stream.get_buffer(sys.stdout.buffer), name)
595 threads.append(stdout_reader)
596 else:
597 stdout_reader = None
598
599 if stderr:
600 stderr_reader = reader(process.stderr, output_stream.get_buffer(sys.stderr.buffer), name)
601 threads.append(stderr_reader)
602 else:
603 stderr_reader = None
604
605 for thread in threads:
606 thread.start()
607
608 for thread in threads:
609 try:
610 thread.wait_for_result()
611 except Exception as ex: # pylint: disable=broad-except
612 display.error(str(ex))
613
614 if isinstance(stdout_reader, ReaderThread):
615 stdout_bytes = b''.join(stdout_reader.lines)
616 else:
617 stdout_bytes = b''
618
619 if isinstance(stderr_reader, ReaderThread):
620 stderr_bytes = b''.join(stderr_reader.lines)
621 else:
622 stderr_bytes = b''
623
624 process.wait()
625
626 return stdout_bytes, stderr_bytes
627
628
629 class WriterThread(WrappedThread):
630 """Thread to write data to stdin of a subprocess."""
631
632 def __init__(self, handle: t.IO[bytes], data: bytes, name: str) -> None:
633 super().__init__(self._run, f'{self.__class__.__name__}: {name}')
634
635 self.handle = handle
636 self.data = data
637
638 def _run(self) -> None:
639 """Workload to run on a thread."""
640 try:
641 self.handle.write(self.data)
642 self.handle.flush()
643 finally:
644 self.handle.close()
645
646
647 class ReaderThread(WrappedThread, metaclass=abc.ABCMeta):
648 """Thread to read stdout from a subprocess."""
649
650 def __init__(self, handle: t.IO[bytes], buffer: t.BinaryIO, name: str) -> None:
651 super().__init__(self._run, f'{self.__class__.__name__}: {name}')
652
653 self.handle = handle
654 self.buffer = buffer
655 self.lines: list[bytes] = []
656
657 @abc.abstractmethod
658 def _run(self) -> None:
659 """Workload to run on a thread."""
660
661
662 class CaptureThread(ReaderThread):
663 """Thread to capture stdout from a subprocess into a buffer."""
664
665 def _run(self) -> None:
666 """Workload to run on a thread."""
667 src = self.handle
668 dst = self.lines
669
670 try:
671 for line in src:
672 dst.append(line)
673 finally:
674 src.close()
675
676
677 class OutputThread(ReaderThread):
678 """Thread to pass stdout from a subprocess to stdout."""
679
680 def _run(self) -> None:
681 """Workload to run on a thread."""
682 src = self.handle
683 dst = self.buffer
684
685 try:
686 for line in src:
687 dst.write(line)
688 dst.flush()
689 finally:
690 src.close()
691
692
693 def common_environment() -> dict[str, str]:
694 """Common environment used for executing all programs."""
695 env = dict(
696 LC_ALL=CONFIGURED_LOCALE,
697 PATH=os.environ.get('PATH', os.path.defpath),
698 )
699
700 required = (
701 'HOME',
702 )
703
704 optional = (
705 'LD_LIBRARY_PATH',
706 'SSH_AUTH_SOCK',
707 'SSH_SK_PROVIDER',
708 # MacOS High Sierra Compatibility
709 # http://sealiesoftware.com/blog/archive/2017/6/5/Objective-C_and_fork_in_macOS_1013.html
710 # Example configuration for macOS:
711 # export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES
712 'OBJC_DISABLE_INITIALIZE_FORK_SAFETY',
713 'ANSIBLE_KEEP_REMOTE_FILES',
714 # MacOS Homebrew Compatibility
715 # https://cryptography.io/en/latest/installation/#building-cryptography-on-macos
716 # This may also be required to install pyyaml with libyaml support when installed in non-standard locations.
717 # Example configuration for brew on macOS:
718 # export LDFLAGS="-L$(brew --prefix openssl)/lib/ -L$(brew --prefix libyaml)/lib/"
719 # export CFLAGS="-I$(brew --prefix openssl)/include/ -I$(brew --prefix libyaml)/include/"
720 'LDFLAGS',
721 'CFLAGS',
722 )
723
724 # FreeBSD Compatibility
725 # This is required to include libyaml support in PyYAML.
726 # The header /usr/local/include/yaml.h isn't in the default include path for the compiler.
727 # It is included here so that tests can take advantage of it, rather than only ansible-test during managed pip installs.
728 # If CFLAGS has been set in the environment that value will take precedence due to being an optional var when calling pass_vars.
729 if os.path.exists('/etc/freebsd-update.conf'):
730 env.update(CFLAGS='-I/usr/local/include/')
731
732 env.update(pass_vars(required=required, optional=optional))
733
734 return env
735
736
737 def report_locale(show_warning: bool) -> None:
738 """Report the configured locale and the locale warning, if applicable."""
739
740 display.info(f'Configured locale: {CONFIGURED_LOCALE}', verbosity=1)
741
742 if LOCALE_WARNING and show_warning:
743 display.warning(LOCALE_WARNING)
744
745
746 def pass_vars(required: c.Collection[str], optional: c.Collection[str]) -> dict[str, str]:
747 """Return a filtered dictionary of environment variables based on the current environment."""
748 env = {}
749
750 for name in required:
751 if name not in os.environ:
752 raise MissingEnvironmentVariable(name)
753 env[name] = os.environ[name]
754
755 for name in optional:
756 if name not in os.environ:
757 continue
758 env[name] = os.environ[name]
759
760 return env
761
762
763 def verified_chmod(path: str, mode: int) -> None:
764 """Perform chmod on the specified path and then verify the permissions were applied."""
765 os.chmod(path, mode) # pylint: disable=ansible-bad-function
766
767 executable = any(mode & perm for perm in (stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH))
768
769 if executable and not os.access(path, os.X_OK):
770 raise ApplicationError(f'Path "{path}" should executable, but is not. Is the filesystem mounted with the "noexec" option?')
771
772
773 def remove_tree(path: str) -> None:
774 """Remove the specified directory, silently continuing if the directory does not exist."""
775 try:
776 shutil.rmtree(to_bytes(path))
777 except FileNotFoundError:
778 pass
779
780
781 def is_binary_file(path: str) -> bool:
782 """Return True if the specified file is a binary file, otherwise return False."""
783 assume_text = {
784 '.cfg',
785 '.conf',
786 '.crt',
787 '.cs',
788 '.css',
789 '.html',
790 '.ini',
791 '.j2',
792 '.js',
793 '.json',
794 '.md',
795 '.pem',
796 '.ps1',
797 '.psm1',
798 '.py',
799 '.rst',
800 '.sh',
801 '.txt',
802 '.xml',
803 '.yaml',
804 '.yml',
805 }
806
807 assume_binary = {
808 '.bin',
809 '.eot',
810 '.gz',
811 '.ico',
812 '.iso',
813 '.jpg',
814 '.otf',
815 '.p12',
816 '.png',
817 '.pyc',
818 '.rpm',
819 '.ttf',
820 '.woff',
821 '.woff2',
822 '.zip',
823 }
824
825 ext = os.path.splitext(path)[1]
826
827 if ext in assume_text:
828 return False
829
830 if ext in assume_binary:
831 return True
832
833 with open_binary_file(path) as path_fd:
834 return b'\0' in path_fd.read(4096)
835
836
837 def generate_name(length: int = 8) -> str:
838 """Generate and return a random name."""
839 return ''.join(random.choice(string.ascii_letters + string.digits) for _idx in range(length))
840
841
842 def generate_password() -> str:
843 """Generate and return random password."""
844 chars = [
845 string.ascii_letters,
846 string.digits,
847 string.ascii_letters,
848 string.digits,
849 '-',
850 ] * 4
851
852 password = ''.join([random.choice(char) for char in chars[:-1]])
853
854 display.sensitive.add(password)
855
856 return password
857
858
859 class Display:
860 """Manages color console output."""
861
862 clear = '\033[0m'
863 red = '\033[31m'
864 green = '\033[32m'
865 yellow = '\033[33m'
866 blue = '\033[34m'
867 purple = '\033[35m'
868 cyan = '\033[36m'
869
870 verbosity_colors = {
871 0: None,
872 1: green,
873 2: blue,
874 3: cyan,
875 }
876
877 def __init__(self) -> None:
878 self.verbosity = 0
879 self.color = sys.stdout.isatty()
880 self.warnings: list[str] = []
881 self.warnings_unique: set[str] = set()
882 self.fd = sys.stderr # default to stderr until config is initialized to avoid early messages going to stdout
883 self.rows = 0
884 self.columns = 0
885 self.truncate = 0
886 self.redact = True
887 self.sensitive: set[str] = set()
888
889 if os.isatty(0):
890 self.rows, self.columns = unpack('HHHH', fcntl.ioctl(0, TIOCGWINSZ, pack('HHHH', 0, 0, 0, 0)))[:2]
891
892 def __warning(self, message: str) -> None:
893 """Internal implementation for displaying a warning message."""
894 self.print_message('WARNING: %s' % message, color=self.purple)
895
896 def review_warnings(self) -> None:
897 """Review all warnings which previously occurred."""
898 if not self.warnings:
899 return
900
901 self.__warning('Reviewing previous %d warning(s):' % len(self.warnings))
902
903 for warning in self.warnings:
904 self.__warning(warning)
905
906 def warning(self, message: str, unique: bool = False, verbosity: int = 0) -> None:
907 """Display a warning level message."""
908 if verbosity > self.verbosity:
909 return
910
911 if unique:
912 if message in self.warnings_unique:
913 return
914
915 self.warnings_unique.add(message)
916
917 self.__warning(message)
918 self.warnings.append(message)
919
920 def notice(self, message: str) -> None:
921 """Display a notice level message."""
922 self.print_message('NOTICE: %s' % message, color=self.purple)
923
924 def error(self, message: str) -> None:
925 """Display an error level message."""
926 self.print_message('ERROR: %s' % message, color=self.red)
927
928 def fatal(self, message: str) -> None:
929 """Display a fatal level message."""
930 self.print_message('FATAL: %s' % message, color=self.red, stderr=True)
931
932 def info(self, message: str, verbosity: int = 0, truncate: bool = False) -> None:
933 """Display an info level message."""
934 if self.verbosity >= verbosity:
935 color = self.verbosity_colors.get(verbosity, self.yellow)
936 self.print_message(message, color=color, truncate=truncate)
937
938 def print_message( # pylint: disable=locally-disabled, invalid-name
939 self,
940 message: str,
941 color: t.Optional[str] = None,
942 stderr: bool = False,
943 truncate: bool = False,
944 ) -> None:
945 """Display a message."""
946 if self.redact and self.sensitive:
947 for item in self.sensitive:
948 if not item:
949 continue
950
951 message = message.replace(item, '*' * len(item))
952
953 if truncate:
954 if len(message) > self.truncate > 5:
955 message = message[:self.truncate - 5] + ' ...'
956
957 if color and self.color:
958 # convert color resets in message to desired color
959 message = message.replace(self.clear, color)
960 message = '%s%s%s' % (color, message, self.clear)
961
962 fd = sys.stderr if stderr else self.fd
963
964 print(message, file=fd)
965 fd.flush()
966
967
968 class InternalError(Exception):
969 """An unhandled internal error indicating a bug in the code."""
970
971 def __init__(self, message: str) -> None:
972 super().__init__(f'An internal error has occurred in ansible-test: {message}')
973
974
975 class ApplicationError(Exception):
976 """General application error."""
977
978
979 class ApplicationWarning(Exception):
980 """General application warning which interrupts normal program flow."""
981
982
983 class TimeoutExpiredError(SystemExit):
984 """Error raised when the test timeout has been reached or exceeded."""
985
986
987 class SubprocessError(ApplicationError):
988 """Error resulting from failed subprocess execution."""
989
990 def __init__(
991 self,
992 cmd: list[str],
993 status: int = 0,
994 stdout: t.Optional[str] = None,
995 stderr: t.Optional[str] = None,
996 runtime: t.Optional[float] = None,
997 error_callback: t.Optional[c.Callable[[SubprocessError], None]] = None,
998 ) -> None:
999 message = 'Command "%s" returned exit status %s.\n' % (shlex.join(cmd), status)
1000 message += format_command_output(stdout, stderr)
1001
1002 self.cmd = cmd
1003 self.message = message
1004 self.status = status
1005 self.stdout = stdout
1006 self.stderr = stderr
1007 self.runtime = runtime
1008
1009 if error_callback:
1010 error_callback(self)
1011
1012 self.message = self.message.strip()
1013
1014 super().__init__(self.message)
1015
1016
1017 class MissingEnvironmentVariable(ApplicationError):
1018 """Error caused by missing environment variable."""
1019
1020 def __init__(self, name: str) -> None:
1021 super().__init__('Missing environment variable: %s' % name)
1022
1023 self.name = name
1024
1025
1026 class HostConnectionError(ApplicationError):
1027 """
1028 Raised when the initial connection during host profile setup has failed and all retries have been exhausted.
1029 Raised by provisioning code when one or more provisioning threads raise this exception.
1030 Also raised when an SSH connection fails for the shell command.
1031 """
1032
1033 def __init__(self, message: str, callback: t.Callable[[], None] = None) -> None:
1034 super().__init__(message)
1035
1036 self._callback = callback
1037
1038 def run_callback(self) -> None:
1039 """Run the error callback, if any."""
1040 if self._callback:
1041 self._callback()
1042
1043
1044 def format_command_output(stdout: str | None, stderr: str | None) -> str:
1045 """Return a formatted string containing the given stdout and stderr (if any)."""
1046 message = ''
1047
1048 if stderr and (stderr := stderr.strip()):
1049 message += '>>> Standard Error\n'
1050 message += f'{stderr}{Display.clear}\n'
1051
1052 if stdout and (stdout := stdout.strip()):
1053 message += '>>> Standard Output\n'
1054 message += f'{stdout}{Display.clear}\n'
1055
1056 return message
1057
1058
1059 def retry[T](func: t.Callable[..., T], ex_type: t.Type[BaseException] = SubprocessError, sleep: int = 10, attempts: int = 10, warn: bool = True) -> T:
1060 """Retry the specified function on failure."""
1061 for dummy in range(1, attempts):
1062 try:
1063 return func()
1064 except ex_type as ex:
1065 if warn:
1066 display.warning(str(ex))
1067
1068 time.sleep(sleep)
1069
1070 return func()
1071
1072
1073 def parse_to_list_of_dict(pattern: str, value: str) -> list[dict[str, str]]:
1074 """Parse lines from the given value using the specified pattern and return the extracted list of key/value pair dictionaries."""
1075 matched = []
1076 unmatched: list[str] = []
1077
1078 for line in value.splitlines():
1079 match = re.search(pattern, line)
1080
1081 if match:
1082 matched.append(match.groupdict())
1083 else:
1084 unmatched.append(line)
1085
1086 if unmatched:
1087 raise Exception('Pattern "%s" did not match values:\n%s' % (pattern, '\n'.join(unmatched)))
1088
1089 return matched
1090
1091
1092 def get_subclasses[C](class_type: t.Type[C]) -> list[t.Type[C]]:
1093 """Returns a list of types that are concrete subclasses of the given type."""
1094 subclasses: set[t.Type[C]] = set()
1095 queue: list[t.Type[C]] = [class_type]
1096
1097 while queue:
1098 parent = queue.pop()
1099
1100 for child in parent.__subclasses__():
1101 if child not in subclasses:
1102 if not inspect.isabstract(child):
1103 subclasses.add(child)
1104 queue.append(child)
1105
1106 return sorted(subclasses, key=lambda sc: sc.__name__)
1107
1108
1109 def is_subdir(candidate_path: str, path: str) -> bool:
1110 """Returns true if candidate_path is path or a subdirectory of path."""
1111 if not path.endswith(os.path.sep):
1112 path += os.path.sep
1113
1114 if not candidate_path.endswith(os.path.sep):
1115 candidate_path += os.path.sep
1116
1117 return candidate_path.startswith(path)
1118
1119
1120 def paths_to_dirs(paths: list[str]) -> list[str]:
1121 """Returns a list of directories extracted from the given list of paths."""
1122 dir_names = set()
1123
1124 for path in paths:
1125 while True:
1126 path = os.path.dirname(path)
1127
1128 if not path or path == os.path.sep:
1129 break
1130
1131 dir_names.add(path + os.path.sep)
1132
1133 return sorted(dir_names)
1134
1135
1136 def str_to_version(version: str) -> tuple[int, ...]:
1137 """Return a version tuple from a version string."""
1138 return tuple(int(n) for n in version.split('.'))
1139
1140
1141 def version_to_str(version: tuple[int, ...]) -> str:
1142 """Return a version string from a version tuple."""
1143 return '.'.join(str(n) for n in version)
1144
1145
1146 def sorted_versions(versions: list[str]) -> list[str]:
1147 """Return a sorted copy of the given list of versions."""
1148 return [version_to_str(version) for version in sorted(str_to_version(version) for version in versions)]
1149
1150
1151 def import_plugins(directory: str, root: t.Optional[str] = None) -> None:
1152 """
1153 Import plugins from the given directory relative to the given root.
1154 If the root is not provided, the 'lib' directory for the test runner will be used.
1155 """
1156 if root is None:
1157 root = os.path.dirname(__file__)
1158
1159 path = os.path.join(root, directory)
1160 package = __name__.rsplit('.', 1)[0]
1161 prefix = '%s.%s.' % (package, directory.replace(os.path.sep, '.'))
1162
1163 for (_module_loader, name, _ispkg) in pkgutil.iter_modules([path], prefix=prefix):
1164 module_path = os.path.join(root, name[len(package) + 1:].replace('.', os.path.sep) + '.py')
1165 load_module(module_path, name)
1166
1167
1168 def load_plugins[C](base_type: t.Type[C], database: dict[str, t.Type[C]]) -> None:
1169 """
1170 Load plugins of the specified type and track them in the specified database.
1171 Only plugins which have already been imported will be loaded.
1172 """
1173 plugins: dict[str, t.Type[C]] = dict((sc.__module__.rsplit('.', 1)[1], sc) for sc in get_subclasses(base_type))
1174
1175 for plugin in plugins:
1176 database[plugin] = plugins[plugin]
1177
1178
1179 def load_module(path: str, name: str) -> None:
1180 """Load a Python module using the given name and path."""
1181 if name in sys.modules:
1182 return
1183
1184 spec = importlib.util.spec_from_file_location(name, path)
1185 module = importlib.util.module_from_spec(spec)
1186 sys.modules[name] = module
1187 spec.loader.exec_module(module)
1188
1189
1190 def sanitize_host_name(name: str) -> str:
1191 """Return a sanitized version of the given name, suitable for use as a hostname."""
1192 return re.sub('[^A-Za-z0-9]+', '-', name)[:63].strip('-')
1193
1194
1195 def get_generic_type[TValue](base_type: t.Type, generic_base_type: t.Type[TValue]) -> t.Optional[t.Type[TValue]]:
1196 """Return the generic type arg derived from the generic_base_type type that is associated with the base_type type, if any, otherwise return None."""
1197 # noinspection PyUnresolvedReferences
1198 type_arg = t.get_args(base_type.__orig_bases__[0])[0]
1199 return None if isinstance(type_arg, generic_base_type) else type_arg
1200
1201
1202 def get_type_associations[TBase, TValue](base_type: t.Type[TBase], generic_base_type: t.Type[TValue]) -> list[tuple[t.Type[TValue], t.Type[TBase]]]:
1203 """Create and return a list of tuples associating generic_base_type derived types with a corresponding base_type derived type."""
1204 return [item for item in [(get_generic_type(sc_type, generic_base_type), sc_type) for sc_type in get_subclasses(base_type)] if item[1]]
1205
1206
1207 def get_type_map[TBase, TValue](base_type: t.Type[TBase], generic_base_type: t.Type[TValue]) -> dict[t.Type[TValue], t.Type[TBase]]:
1208 """Create and return a mapping of generic_base_type derived types to base_type derived types."""
1209 return {item[0]: item[1] for item in get_type_associations(base_type, generic_base_type)}
1210
1211
1212 def verify_sys_executable(path: str) -> t.Optional[str]:
1213 """Verify that the given path references the current Python interpreter. If not, return the expected path, otherwise return None."""
1214 if path == sys.executable:
1215 return None
1216
1217 if os.path.realpath(path) == os.path.realpath(sys.executable):
1218 return None
1219
1220 expected_executable = raw_command([path, '-c', 'import sys; print(sys.executable)'], capture=True)[0]
1221
1222 if expected_executable == sys.executable:
1223 return None
1224
1225 return expected_executable
1226
1227
1228 def type_guard[C](sequence: c.Sequence[t.Any], guard_type: t.Type[C]) -> t.TypeGuard[c.Sequence[C]]:
1229 """
1230 Raises an exception if any item in the given sequence does not match the specified guard type.
1231 Use with assert so that type checkers are aware of the type guard.
1232 """
1233 invalid_types = set(type(item) for item in sequence if not isinstance(item, guard_type))
1234
1235 if not invalid_types:
1236 return True
1237
1238 invalid_type_names = sorted(str(item) for item in invalid_types)
1239
1240 raise Exception(f'Sequence required to contain only {guard_type} includes: {", ".join(invalid_type_names)}')
1241
1242
1243 def get_powershell_version_map() -> dict[str, str]:
1244 """Return a mapping of PowerShell {major}.{minor} version to full PowerShell version."""
1245 return {version_to_str(tuple((int(v) for v in version.split('.')[:2]))): version for version in SUPPORTED_POWERSHELL_VERSIONS}
1246
1247
1248 def get_supported_powershell_versions() -> list[str]:
1249 """Return a list of supported PowerShell versions."""
1250 return list(get_powershell_version_map())
1251
1252
1253 display = Display() # pylint: disable=locally-disabled, invalid-name
1254
1255 _enable_vendoring()