Debian Codegraph @

test/lib/ansible_test/_internal/delegation.py

raw
1 """Delegate test execution to another environment."""
2
3 from __future__ import annotations
4
5 import collections.abc as c
6 import contextlib
7 import json
8 import os
9 import tempfile
10 import typing as t
11
12 from .constants import (
13 STATUS_HOST_CONNECTION_ERROR,
14 )
15
16 from .locale_util import (
17 STANDARD_LOCALE,
18 )
19
20 from .io import (
21 make_dirs,
22 )
23
24 from .config import (
25 CommonConfig,
26 EnvironmentConfig,
27 IntegrationConfig,
28 ShellConfig,
29 TestConfig,
30 UnitsConfig,
31 )
32
33 from .util import (
34 SubprocessError,
35 display,
36 filter_args,
37 ANSIBLE_LIB_ROOT,
38 ANSIBLE_TEST_ROOT,
39 OutputStream,
40 )
41
42 from .util_common import (
43 ResultType,
44 process_scoped_temporary_directory,
45 )
46
47 from .ansible_util import (
48 get_ansible_bin_path,
49 )
50
51 from .containers import (
52 support_container_context,
53 ContainerDatabase,
54 )
55
56 from .data import (
57 data_context,
58 )
59
60 from .payload import (
61 create_payload,
62 )
63
64 from .ci import (
65 get_ci_provider,
66 )
67
68 from .host_configs import (
69 OriginConfig,
70 PythonConfig,
71 )
72
73 from .connections import (
74 Connection,
75 DockerConnection,
76 SshConnection,
77 LocalConnection,
78 )
79
80 from .provisioning import (
81 HostState,
82 )
83
84 from .content_config import (
85 serialize_content_config,
86 )
87
88
89 @contextlib.contextmanager
90 def delegation_context(args: EnvironmentConfig, host_state: HostState) -> c.Iterator[None]:
91 """Context manager for serialized host state during delegation."""
92 make_dirs(ResultType.TMP.path)
93
94 # noinspection PyUnusedLocal
95 python = host_state.controller_profile.python # make sure the python interpreter has been initialized before serializing host state
96 del python
97
98 with tempfile.TemporaryDirectory(prefix='host-', dir=ResultType.TMP.path) as host_dir:
99 args.host_settings.serialize(os.path.join(host_dir, 'settings.dat'))
100 host_state.serialize(os.path.join(host_dir, 'state.dat'))
101 serialize_content_config(args, os.path.join(host_dir, 'config.dat'))
102
103 args.host_path = os.path.join(ResultType.TMP.relative_path, os.path.basename(host_dir))
104
105 try:
106 yield
107 finally:
108 args.host_path = None
109
110
111 def delegate(args: CommonConfig, host_state: HostState, exclude: list[str], require: list[str]) -> None:
112 """Delegate execution of ansible-test to another environment."""
113 assert isinstance(args, EnvironmentConfig)
114
115 with delegation_context(args, host_state):
116 args.metadata.ci_provider = get_ci_provider().code
117
118 make_dirs(ResultType.TMP.path)
119
120 with metadata_context(args):
121 delegate_command(args, host_state, exclude, require)
122
123
124 @contextlib.contextmanager
125 def metadata_context(args: EnvironmentConfig) -> t.Generator[None]:
126 """A context manager which exports delegation metadata."""
127 os.makedirs(ResultType.TMP.path, exist_ok=True)
128
129 with tempfile.NamedTemporaryFile(prefix='metadata-', suffix='.json', dir=ResultType.TMP.path) as metadata_fd:
130 args.metadata_path = os.path.join(ResultType.TMP.relative_path, os.path.basename(metadata_fd.name))
131 args.metadata.to_file(args.metadata_path)
132
133 try:
134 yield
135 finally:
136 args.metadata_path = None
137
138
139 def delegate_command(args: EnvironmentConfig, host_state: HostState, exclude: list[str], require: list[str]) -> None:
140 """Delegate execution based on the provided host state."""
141 con = host_state.controller_profile.get_origin_controller_connection()
142 working_directory = host_state.controller_profile.get_working_directory()
143 host_delegation = not isinstance(args.controller, OriginConfig)
144
145 if host_delegation:
146 if data_context().content.collection:
147 content_root = os.path.join(working_directory, data_context().content.collection.directory)
148 else:
149 content_root = os.path.join(working_directory, 'ansible')
150
151 ansible_bin_path = os.path.join(working_directory, 'ansible', 'bin')
152
153 with tempfile.NamedTemporaryFile(prefix='ansible-source-', suffix='.tgz') as payload_file:
154 create_payload(args, payload_file.name)
155 con.extract_archive(chdir=working_directory, src=payload_file)
156 else:
157 content_root = working_directory
158 ansible_bin_path = get_ansible_bin_path(args)
159
160 command = generate_command(args, host_state.controller_profile.python, ansible_bin_path, content_root, exclude, require)
161
162 if isinstance(con, SshConnection):
163 ssh = con.settings
164 else:
165 ssh = None
166
167 options = []
168
169 if isinstance(args, IntegrationConfig) and args.controller.is_managed and all(target.is_managed for target in args.targets):
170 if not args.allow_destructive:
171 options.append('--allow-destructive')
172
173 with support_container_context(args, ssh) as containers: # type: t.Optional[ContainerDatabase]
174 if containers:
175 options.extend(['--containers', json.dumps(containers.to_dict())])
176
177 # Run unit tests unprivileged to prevent stray writes to the source tree.
178 # Also disconnect from the network once requirements have been installed.
179 if isinstance(args, UnitsConfig) and isinstance(con, DockerConnection):
180 pytest_user = 'pytest'
181
182 writable_dirs = [
183 os.path.join(content_root, ResultType.JUNIT.relative_path),
184 os.path.join(content_root, ResultType.COVERAGE.relative_path),
185 ]
186
187 con.run(['mkdir', '-p'] + writable_dirs, capture=True)
188 con.run(['chmod', '777'] + writable_dirs, capture=True)
189 con.run(['chmod', '755', working_directory], capture=True)
190 con.run(['useradd', pytest_user, '--create-home'], capture=True)
191
192 con.run(insert_options(command, options + ['--requirements-mode', 'only']), capture=False)
193
194 container = con.inspect()
195 networks = container.get_network_names()
196
197 if networks is not None:
198 if args.metadata.debugger_flags.enable:
199 networks = []
200 display.warning('Skipping network isolation to enable remote debugging.')
201
202 for network in networks:
203 try:
204 con.disconnect_network(network)
205 except SubprocessError:
206 display.warning(
207 'Unable to disconnect network "%s" (this is normal under podman). '
208 'Tests will not be isolated from the network. Network-related tests may '
209 'misbehave.' % (network,)
210 )
211 else:
212 display.warning('Network disconnection is not supported (this is normal under podman). '
213 'Tests will not be isolated from the network. Network-related tests may misbehave.')
214
215 options.extend(['--requirements-mode', 'skip'])
216
217 con.user = pytest_user
218
219 success = False
220 status = 0
221
222 try:
223 # When delegating, preserve the original separate stdout/stderr streams, but only when the following conditions are met:
224 # 1) Display output is being sent to stderr. This indicates the output on stdout must be kept separate from stderr.
225 # 2) The delegation is non-interactive. Interactive mode, which generally uses a TTY, is not compatible with intercepting stdout/stderr.
226 # The downside to having separate streams is that individual lines of output from each are more likely to appear out-of-order.
227 output_stream = OutputStream.ORIGINAL if args.display_stderr and not args.interactive else None
228 con.run(insert_options(command, options), capture=False, interactive=args.interactive, output_stream=output_stream)
229 success = True
230 except SubprocessError as ex:
231 status = ex.status
232 raise
233 finally:
234 if host_delegation:
235 download_results(args, con, content_root, success)
236
237 if not success and status == STATUS_HOST_CONNECTION_ERROR:
238 for target in host_state.target_profiles:
239 target.on_target_failure() # when the controller is delegated, report failures after delegation fails
240
241
242 def insert_options(command: list[str], options: list[str]) -> list[str]:
243 """Insert addition command line options into the given command and return the result."""
244 result = []
245
246 for arg in command:
247 if options and arg.startswith('--'):
248 result.extend(options)
249 options = None
250
251 result.append(arg)
252
253 return result
254
255
256 def download_results(args: EnvironmentConfig, con: Connection, content_root: str, success: bool) -> None:
257 """Download results from a delegated controller."""
258 remote_results_root = os.path.join(content_root, data_context().content.results_path)
259 local_test_root = os.path.dirname(os.path.join(data_context().content.root, data_context().content.results_path))
260
261 remote_test_root = os.path.dirname(remote_results_root)
262 remote_results_name = os.path.basename(remote_results_root)
263
264 make_dirs(local_test_root) # make sure directory exists for collections which have no tests
265
266 with tempfile.NamedTemporaryFile(prefix='ansible-test-result-', suffix='.tgz') as result_file:
267 try:
268 con.create_archive(chdir=remote_test_root, name=remote_results_name, dst=result_file, exclude=ResultType.TMP.name)
269 except SubprocessError as ex:
270 if success:
271 raise # download errors are fatal if tests succeeded
272
273 # surface download failures as a warning here to avoid masking test failures
274 display.warning(f'Failed to download results while handling an exception: {ex}')
275 else:
276 result_file.seek(0)
277
278 local_con = LocalConnection(args)
279 local_con.extract_archive(chdir=local_test_root, src=result_file)
280
281
282 def generate_command(
283 args: EnvironmentConfig,
284 python: PythonConfig,
285 ansible_bin_path: str,
286 content_root: str,
287 exclude: list[str],
288 require: list[str],
289 ) -> list[str]:
290 """Generate the command necessary to delegate ansible-test."""
291 cmd = [os.path.join(ansible_bin_path, 'ansible-test')]
292 cmd = [python.path] + cmd
293
294 env_vars = dict(
295 ANSIBLE_TEST_CONTENT_ROOT=content_root,
296 )
297
298 if isinstance(args.controller, OriginConfig):
299 # Expose the ansible and ansible_test library directories to the Python environment.
300 # This is only required when delegation is used on the origin host.
301 library_path = process_scoped_temporary_directory(args)
302
303 os.symlink(ANSIBLE_LIB_ROOT, os.path.join(library_path, 'ansible'))
304 os.symlink(ANSIBLE_TEST_ROOT, os.path.join(library_path, 'ansible_test'))
305
306 env_vars.update(
307 PYTHONPATH=library_path,
308 )
309 else:
310 # When delegating to a host other than the origin, the locale must be explicitly set.
311 # Setting of the locale for the origin host is handled by common_environment().
312 # Not all connections support setting the locale, and for those that do, it isn't guaranteed to work.
313 # This is needed to make sure the delegated environment is configured for UTF-8 before running Python.
314 env_vars.update(
315 LC_ALL=STANDARD_LOCALE,
316 )
317
318 # Propagate the TERM environment variable to the remote host when using the shell command.
319 if isinstance(args, ShellConfig):
320 term = os.environ.get('TERM')
321
322 if term is not None:
323 env_vars.update(TERM=term)
324
325 env_args = ['%s=%s' % (key, env_vars[key]) for key in sorted(env_vars)]
326
327 cmd = ['/usr/bin/env'] + env_args + cmd
328
329 cmd += list(filter_options(args, args.host_settings.filtered_args, exclude, require))
330
331 return cmd
332
333
334 def filter_options(
335 args: EnvironmentConfig,
336 argv: list[str],
337 exclude: list[str],
338 require: list[str],
339 ) -> c.Iterable[str]:
340 """Return an iterable that filters out unwanted CLI options and injects new ones as requested."""
341 replace: list[tuple[str, int, t.Optional[t.Union[bool, str, list[str]]]]] = [
342 ('--truncate', 1, str(args.truncate)),
343 ('--color', 1, 'yes' if args.color else 'no'),
344 ('--redact', 0, False),
345 ('--no-redact', 0, not args.redact),
346 ('--host-path', 1, args.host_path),
347 ('--metadata', 1, args.metadata_path),
348 ]
349
350 if isinstance(args, TestConfig):
351 replace.extend([
352 ('--changed', 0, False),
353 ('--tracked', 0, False),
354 ('--untracked', 0, False),
355 ('--ignore-committed', 0, False),
356 ('--ignore-staged', 0, False),
357 ('--ignore-unstaged', 0, False),
358 ('--changed-from', 1, False),
359 ('--changed-path', 1, False),
360 ('--exclude', 1, exclude),
361 ('--require', 1, require),
362 ('--base-branch', 1, False),
363 ])
364
365 pass_through_args: list[str] = []
366
367 for arg in filter_args(argv, {option: count for option, count, replacement in replace}):
368 if arg == '--' or pass_through_args:
369 pass_through_args.append(arg)
370 continue
371
372 yield arg
373
374 for option, _count, replacement in replace:
375 if not replacement:
376 continue
377
378 if isinstance(replacement, bool):
379 yield option
380 elif isinstance(replacement, str):
381 yield from [option, replacement]
382 elif isinstance(replacement, list):
383 for item in replacement:
384 yield from [option, item]
385
386 yield from args.delegate_args
387 yield from pass_through_args