| # Copyright 2023 The Fuchsia Authors. All rights reserved. | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| import asyncio | |
| from collections.abc import Sequence | |
| import contextlib | |
| import dataclasses | |
| import ipaddress | |
| import math | |
| import os | |
| import tempfile | |
| import typing | |
| import async_utils.command as command | |
| import statusinfo | |
| import args | |
| import environment | |
| import event | |
| import host_runner | |
| import package_repository | |
| import test_list_file | |
| # The timeout command-line argument can be used to specify a timeout for all tests that are run | |
| # in a given invocation of 'fx 'test'. The default behavior is to use the 'normal' timeout value | |
| # for each test. A few tests have specific 'normal' timeout values specified using test_spec | |
| # values in build files, but most tests use this default timeout of 5 minutes. | |
| DEFAULT_TIMEOUT = 5 * 60 | |
| # Default timeout in seconds for pre-resolving a test's fuchsia-pkg:// package (and transitive | |
| # subpackages) before starting the per-test execution timeout. Matches | |
| # defaultPackageResolutionTimeout in //tools/testing/testrunner/tester.go. | |
| DEFAULT_PACKAGE_RESOLUTION_TIMEOUT = 2 * 60 | |
| # Bounded timeout for target device discovery, address resolution, and ssh key lookups. | |
| _DEVICE_PROBE_TIMEOUT_SECONDS: float = 30.0 | |
| _PackageResolutionKey = tuple[str, tuple[str, str | None, str | None]] | |
| def _extract_package_resolve_url(package_url: str | None) -> str | None: | |
| if package_url is None or not package_url.startswith("fuchsia-pkg://"): | |
| return None | |
| return package_url.split("#", 1)[0] | |
| def _format_skip_message( | |
| output: command.CommandOutput, skipped_exit_code: int | |
| ) -> str: | |
| """Format a human-readable skip reason from a skipped host test's output.""" | |
| output_parts = tuple( | |
| stripped | |
| for stream in (output.stdout, output.stderr) | |
| if (stripped := stream.strip()) | |
| ) | |
| if output_parts: | |
| return "\n".join(output_parts) | |
| return f"Test exited with skip status (exit code {skipped_exit_code})." | |
| def _format_target_address(address: str, port: str) -> str: | |
| """Format a device address and port as an ffx --target TargetAddr string.""" | |
| stripped_address = address.strip() | |
| stripped_port = port.strip() | |
| if not stripped_address or not stripped_port: | |
| return stripped_address | |
| # Bracket unbracketed IPv6 addresses (which contain at least two colons), | |
| # while leaving single-colon prefixes like "usb:cid" and "vsock:cid" | |
| # unbracketed. | |
| if not stripped_address.startswith("[") and stripped_address.count(":") > 1: | |
| return f"[{stripped_address}]:{stripped_port}" | |
| return f"{stripped_address}:{stripped_port}" | |
| class TestExecutionError(Exception): | |
| """Base error type for test failures.""" | |
| def __init__(self, message: str, command_output: typing.Any = None): | |
| super().__init__(message) | |
| self.command_output = command_output | |
| class TestCouldNotRun(TestExecutionError): | |
| """The test could not be run at all.""" | |
| class TestSkipped(TestExecutionError): | |
| """The test was skipped for some non-error reason""" | |
| class TestFilterUnsupported(TestSkipped): | |
| """The test runner does not support --test-filter.""" | |
| class TestFailed(TestExecutionError): | |
| """The test ran, but returned a failure error code.""" | |
| class TestPackageResolutionFailed(TestFailed): | |
| """Pre-resolving the test's package failed before the test ran.""" | |
| class TestProfilerStopFailed(TestFailed): | |
| """The test passed, but `ffx profiler stop` failed to write the profile.""" | |
| class TestAborted(TestExecutionError): | |
| """The test was aborted before completion.""" | |
| class TestTimeout(TestExecutionError): | |
| """The test timed out.""" | |
| @dataclasses.dataclass(frozen=True) | |
| class _PackageResolutionOutcome: | |
| resolve_url: str | |
| resolution_timeout: float | None | |
| output: command.CommandOutput | None | |
| aborted: bool | |
| @dataclasses.dataclass | |
| class _InFlightResolution: | |
| task: asyncio.Task[_PackageResolutionOutcome] | |
| flight_abort: asyncio.Event | |
| waiters: int = 0 | |
| class PackageResolutionCache: | |
| """Run-scoped cache and single-flight coalescer for package pre-resolution.""" | |
| def __init__(self) -> None: | |
| self._resolved: set[_PackageResolutionKey] = set() | |
| self._in_flight: dict[_PackageResolutionKey, _InFlightResolution] = {} | |
| async def resolve( | |
| self, | |
| key: _PackageResolutionKey, | |
| resolve_url: str, | |
| resolve_cmd: Sequence[str], | |
| resolve_env: dict[str, str] | None, | |
| resolution_timeout: float | None, | |
| recorder: event.EventRecorder, | |
| parent: event.Id, | |
| abort_signal: asyncio.Event | None, | |
| ) -> _PackageResolutionOutcome | None: | |
| """Resolve a package once per key, coalescing concurrent callers. | |
| Returns None when the package was already resolved and cached, or the | |
| outcome of the resolution attempt otherwise. | |
| """ | |
| if abort_signal is not None and abort_signal.is_set(): | |
| raise TestAborted(f"Aborted resolving package {resolve_url}") | |
| if key in self._resolved: | |
| return None | |
| flight = self._in_flight.get(key) | |
| if flight is None or flight.task.done(): | |
| flight_abort = asyncio.Event() | |
| created_flight: _InFlightResolution | |
| async def _run_resolve() -> _PackageResolutionOutcome: | |
| try: | |
| output = await run_command( | |
| *resolve_cmd, | |
| recorder=recorder, | |
| parent=parent, | |
| print_verbatim=False, | |
| env=resolve_env, | |
| timeout=resolution_timeout, | |
| abort_signal=flight_abort, | |
| ) | |
| was_aborted = flight_abort.is_set() | |
| if ( | |
| not was_aborted | |
| and output is not None | |
| and not output.was_timeout | |
| and output.return_code == 0 | |
| ): | |
| self._resolved.add(key) | |
| elif ( | |
| not was_aborted | |
| and output is not None | |
| and output.was_timeout | |
| ): | |
| # If package resolution times out, warn and continue to | |
| # run the test. Any blobs still in flight continue | |
| # resolving via pkg-resolver's work queue and coalesce | |
| # with the test run's resolution. | |
| timeout_desc = ( | |
| f" after {resolution_timeout} seconds" | |
| if resolution_timeout is not None | |
| else "" | |
| ) | |
| recorder.emit_warning_message( | |
| f"Timed out resolving package {resolve_url}{timeout_desc}; " | |
| "continuing to run the test." | |
| ) | |
| return _PackageResolutionOutcome( | |
| resolve_url=resolve_url, | |
| resolution_timeout=resolution_timeout, | |
| output=output, | |
| aborted=was_aborted, | |
| ) | |
| finally: | |
| if self._in_flight.get(key) is created_flight: | |
| del self._in_flight[key] | |
| task = asyncio.create_task(_run_resolve()) | |
| created_flight = _InFlightResolution( | |
| task=task, flight_abort=flight_abort | |
| ) | |
| flight = created_flight | |
| self._in_flight[key] = flight | |
| flight.waiters += 1 | |
| released = False | |
| def _release_waiter() -> bool: | |
| nonlocal released | |
| if released: | |
| return False | |
| released = True | |
| flight.waiters -= 1 | |
| if flight.waiters == 0: | |
| if self._in_flight.get(key) is flight: | |
| del self._in_flight[key] | |
| return True | |
| return False | |
| try: | |
| if abort_signal is None: | |
| return await asyncio.shield(flight.task) | |
| shielded_task = asyncio.ensure_future(asyncio.shield(flight.task)) | |
| abort_wait_task = asyncio.create_task(abort_signal.wait()) | |
| wait_futures: Sequence[asyncio.Future[typing.Any]] = ( | |
| shielded_task, | |
| abort_wait_task, | |
| ) | |
| try: | |
| _done, pending = await asyncio.wait( | |
| wait_futures, | |
| return_when=asyncio.FIRST_COMPLETED, | |
| ) | |
| for p in pending: | |
| p.cancel() | |
| if pending: | |
| await asyncio.wait(pending) | |
| except asyncio.CancelledError: | |
| if shielded_task.done() and not shielded_task.cancelled(): | |
| shielded_task.exception() | |
| shielded_task.cancel() | |
| abort_wait_task.cancel() | |
| raise | |
| if abort_signal.is_set(): | |
| if shielded_task.done() and not shielded_task.cancelled(): | |
| # Retrieve any exception so asyncio does not warn about an | |
| # unretrieved Future exception when aborting. | |
| shielded_task.exception() | |
| is_last = _release_waiter() | |
| if is_last and not flight.task.done(): | |
| flight.flight_abort.set() | |
| try: | |
| await flight.task | |
| except asyncio.CancelledError: | |
| pass | |
| raise TestAborted(f"Aborted resolving package {resolve_url}") | |
| return shielded_task.result() | |
| except asyncio.CancelledError: | |
| is_last = _release_waiter() | |
| if is_last and not flight.task.done(): | |
| flight.flight_abort.set() | |
| flight.task.cancel() | |
| try: | |
| await flight.task | |
| except asyncio.CancelledError: | |
| pass | |
| raise | |
| finally: | |
| _release_waiter() | |
| # Unique number suffix for output subdirectories. | |
| UNIQUE_OUTPUT_SUFFIX = 0 | |
| _PROFILER_ATTACH_TIMEOUT_SECONDS = 60.0 | |
| _PROFILER_STOP_TIMEOUT_SECONDS = 300.0 | |
| _PROFILER_ABORT_TIMEOUT_SECONDS = 15.0 | |
| _PROFILER_TARGET_FLAGS = frozenset( | |
| { | |
| "--url", | |
| "--moniker", | |
| "--pids", | |
| "--tids", | |
| "--job-ids", | |
| "--system-wide", | |
| } | |
| ) | |
| @dataclasses.dataclass | |
| class _ProfileSessionResult: | |
| stop_error: str | None = None | |
| class TestExecution: | |
| """Represents a single execution for a specific test.""" | |
| def __init__( | |
| self, | |
| test: test_list_file.Test, | |
| exec_env: environment.ExecutionEnvironment, | |
| flags: args.Flags, | |
| run_suffix: int | None = None, | |
| device_env: environment.DeviceEnvironment | None = None, | |
| package_resolution_cache: PackageResolutionCache | None = None, | |
| ): | |
| """Initialize the test execution wrapper. | |
| Args: | |
| test (test_list_file.Test): Test to run. | |
| exec_env (environment.ExecutionEnvironment): Execution environment. | |
| flags (args.Flags): Command flags. | |
| run_suffix (int, optional): If set, this is the unique | |
| index of a single run of the referenced test. | |
| device_env (environment.DeviceEnvironment, optional): | |
| If set, this contains information on how to connect to | |
| a device. Otherwise if this is a host test it may not | |
| connect to a device. | |
| package_resolution_cache (PackageResolutionCache, optional): | |
| Shared run-scoped cache for coalescing package pre-resolution. | |
| """ | |
| global UNIQUE_OUTPUT_SUFFIX | |
| self._test = test | |
| self._exec_env = exec_env | |
| self._flags = flags | |
| self._run_suffix = run_suffix | |
| self._device_env = device_env | |
| self._package_resolution_cache = package_resolution_cache | |
| self._cached_host_runner: host_runner.HostTestRunner | None = None | |
| self._host_runner_resolved = False | |
| if self._flags.artifact_output_directory is not None: | |
| self._outdir: str | None = os.path.join( | |
| self._flags.artifact_output_directory, str(UNIQUE_OUTPUT_SUFFIX) | |
| ) | |
| UNIQUE_OUTPUT_SUFFIX += 1 | |
| else: | |
| self._outdir = None | |
| def _get_host_test_runner(self) -> host_runner.HostTestRunner | None: | |
| if not self._host_runner_resolved: | |
| self._cached_host_runner = host_runner.detect_host_test_runner( | |
| self._test, self._exec_env.out_dir | |
| ) | |
| self._host_runner_resolved = True | |
| return self._cached_host_runner | |
| def name(self) -> str: | |
| """Get the name of the test. | |
| Returns: | |
| str: Name of the test. | |
| """ | |
| return self._test.name() + ( | |
| f" (Run {self._run_suffix})" if self._run_suffix is not None else "" | |
| ) | |
| def is_hermetic(self) -> bool: | |
| """Determine if a test is hermetic. | |
| Returns: | |
| bool: True if the wrapped test is hermetic, False otherwise. | |
| """ | |
| return self._test.info.is_hermetic() | |
| def is_host_test(self) -> bool: | |
| """Determine if a test is a pure host test. | |
| Returns: | |
| bool: True if the wrapped test is a pure host test, False otherwise. | |
| """ | |
| return bool(self._test.is_host_test()) | |
| def command_line( | |
| self, | |
| extra_runner_args: Sequence[str] = (), | |
| ) -> list[str]: | |
| """Format the command line required to execute this test. | |
| Raises: | |
| TestCouldNotRun: If we do not know how to run this type of test. | |
| Returns: | |
| list[str]: The command line for the test. | |
| """ | |
| min_severity_logs: list[str] = [] | |
| if ( | |
| self._is_pure_device_test() | |
| and self._test.build.test.path | |
| and self._test.info.execution is not None | |
| ): | |
| execution = self._test.info.execution | |
| if self._flags.min_severity_logs: | |
| min_severity_logs = self._flags.min_severity_logs | |
| elif execution.min_severity_logs is not None: | |
| min_severity_logs = [execution.min_severity_logs] | |
| extra_args = [] | |
| if execution.realm: | |
| extra_args += ["--realm=" + execution.realm] | |
| if execution.max_severity_logs and self._flags.restrict_logs: | |
| extra_args += [ | |
| "--max-severity-logs=" + execution.max_severity_logs, | |
| ] | |
| if min_severity_logs: | |
| extra_args += [ | |
| "--min-severity-logs=" + ",".join(min_severity_logs) | |
| ] | |
| parallel_cases = self._flags.parallel_cases | |
| if ( | |
| parallel_cases == 0 | |
| and self._test.build.test.parallel is not None | |
| ): | |
| parallel_cases = self._test.build.test.parallel | |
| if parallel_cases != 0: | |
| extra_args += [ | |
| "--max-concurrent-test-case-runs=" + str(parallel_cases), | |
| ] | |
| for test_filter in self._flags.test_filter: | |
| extra_args += ["--test-case-filter=" + test_filter] | |
| if self._flags.also_run_disabled_tests: | |
| extra_args += ["--run-disabled-cases"] | |
| if self._flags.show_full_moniker_in_logs: | |
| extra_args += ["--show-full-moniker-in-logs"] | |
| if self._flags.break_on_failure: | |
| extra_args += ["--break-on-failure"] | |
| if self._flags.extra_args: | |
| extra_args += [ | |
| "--target-test-args=" + ",".join(self._flags.extra_args) | |
| ] | |
| timeout = self._calculate_timeout() | |
| if timeout is not None: | |
| extra_args += [ | |
| "--timeout=" + str(math.ceil(timeout)), | |
| ] | |
| return [ | |
| os.path.join(self._exec_env.out_dir, self._test.build.test.path) | |
| ] + extra_args | |
| elif self._test.info.execution is not None: | |
| exec_env = self._exec_env | |
| execution = self._test.info.execution | |
| component_url = self._get_component_url() | |
| assert component_url is not None | |
| if self._flags.min_severity_logs: | |
| min_severity_logs = self._flags.min_severity_logs | |
| elif execution.min_severity_logs is not None: | |
| min_severity_logs = [execution.min_severity_logs] | |
| extra_args = [] | |
| if execution.realm: | |
| extra_args += ["--realm", execution.realm] | |
| if execution.max_severity_logs and self._flags.restrict_logs: | |
| extra_args += [ | |
| "--max-severity-logs", | |
| execution.max_severity_logs, | |
| ] | |
| if min_severity_logs: | |
| for min_severity_log in min_severity_logs: | |
| extra_args += ["--min-severity-logs", min_severity_log] | |
| parallel_cases = self._flags.parallel_cases | |
| if ( | |
| parallel_cases == 0 | |
| and self._test.build.test.parallel is not None | |
| ): | |
| parallel_cases = self._test.build.test.parallel | |
| if parallel_cases != 0: | |
| extra_args += [ | |
| "--parallel", | |
| str(parallel_cases), | |
| ] | |
| if ( | |
| self._test.build.test.create_no_exception_channel is not None | |
| and self._test.build.test.create_no_exception_channel | |
| ): | |
| extra_args += [ | |
| "--no-exception-channel", | |
| ] | |
| # If command line filters are given, they should override (cancel) | |
| # any filters that may be in test-list.json. | |
| test_execution_filters = self._test.info.execution.test_filters | |
| if self._flags.test_filter: | |
| for test_filter in self._flags.test_filter: | |
| extra_args += ["--test-filter", test_filter] | |
| elif test_execution_filters: | |
| extra_args.append("--no-cases-equals-success") | |
| for test_filter in test_execution_filters: | |
| extra_args += ["--test-filter", test_filter] | |
| if self._flags.also_run_disabled_tests: | |
| extra_args += ["--run-disabled"] | |
| if self._flags.show_full_moniker_in_logs: | |
| extra_args += ["--show-full-moniker-in-logs"] | |
| if self._flags.break_on_failure: | |
| extra_args += ["--break-on-failure"] | |
| if self._outdir is not None: | |
| extra_args += ["--output-directory", self._outdir] | |
| if self._flags.capture_syslog: | |
| extra_args += ["--capture-syslog"] | |
| timeout = self._calculate_timeout() | |
| if timeout is not None: | |
| extra_args += [ | |
| "--timeout", | |
| str(math.ceil(timeout)), | |
| ] | |
| suffix_args = ( | |
| ["--"] + self._flags.extra_args | |
| if self._flags.extra_args | |
| else [] | |
| ) | |
| return ( | |
| exec_env.fx_cmd_line("ffx", "test", "run") | |
| + extra_args | |
| + [component_url] | |
| + suffix_args | |
| ) | |
| elif self._test.build.test.path: | |
| command_line = [self._test.build.test.path] | |
| if self._test.is_e2e_test() and self._device_env is not None: | |
| runner = self._get_host_test_runner() | |
| if runner is not None and runner.is_mobly: | |
| command_line += [ | |
| "--ssh-key", | |
| self._device_env.private_key_path, | |
| ] | |
| if extra_runner_args: | |
| command_line += list(extra_runner_args) | |
| return command_line + self._flags.extra_args | |
| else: | |
| raise TestCouldNotRun( | |
| f"We do not know how to run this test: {str(self._test)}" | |
| ) | |
| def enumerate_cases_command_line(self) -> list[str] | None: | |
| """Get the command line to enumerate all test cases in this test. | |
| If this type of test does not support test case enumeration, | |
| return None. | |
| Returns: | |
| list[str] | None: Command line to enumerate cases | |
| if possible, None otherwise. | |
| """ | |
| # If the test definition includes a `list_cases_argument` (e.g. "list_mobly_tests"), | |
| # we construct a command to execute the test binary with that argument. | |
| # Python host unittests are gated through `_get_host_test_runner()` so targets | |
| # using a custom `main_callable` are not misclassified as filterable. | |
| list_cases_arg = self._test.build.test.list_cases_argument | |
| if ( | |
| list_cases_arg | |
| and list_cases_arg != "list_host_python_unittests" | |
| and self._test.build.test.path | |
| ): | |
| arg = f"--{list_cases_arg}" | |
| path = self._test.build.test.path | |
| if not os.path.isabs(path): | |
| path = os.path.join(self._exec_env.out_dir, path) | |
| return [path, arg] | |
| runner = self._get_host_test_runner() | |
| if runner is not None and self._test.build.test.path: | |
| path = self._test.build.test.path | |
| if not os.path.isabs(path): | |
| path = os.path.join(self._exec_env.out_dir, path) | |
| return [ | |
| path, | |
| *runner.enumerate_args( | |
| include_disabled=self._flags.also_run_disabled_tests | |
| ), | |
| ] | |
| execution = self._test.info.execution | |
| exec_env = self._exec_env | |
| try: | |
| component_url = self._get_component_url() | |
| except TestCouldNotRun: | |
| return None | |
| if component_url is None or execution is None: | |
| return None | |
| extra_args = [] | |
| if execution.realm: | |
| extra_args += ["--realm", execution.realm] | |
| return ( | |
| exec_env.fx_cmd_line("ffx", "test", "list-cases") | |
| + extra_args | |
| + [component_url] | |
| ) | |
| def enumerate_cases_output_template(self) -> str: | |
| """Get the template string for the output command. | |
| Returns: | |
| str: The template string | |
| """ | |
| # TODO(fxbug.dev/481539525): This behavior should ideally be in a script run by fx test | |
| runner = self._get_host_test_runner() | |
| if runner is not None: | |
| return runner.output_template() | |
| return host_runner.DEFAULT_TEST_OUTPUT_TEMPLATE | |
| async def enumerate_mobly_test( | |
| self, | |
| recorder: event.EventRecorder, | |
| parent: event.Id | None = None, | |
| timeout: float | None = None, | |
| abort_signal: asyncio.Event | None = None, | |
| ) -> command.CommandOutput | None: | |
| """Enumerate test cases for this (Mobly) test. | |
| Args: | |
| recorder (event.EventRecorder): Recorder for events. | |
| parent (event.Id | None): Parent event ID. | |
| timeout (float | None): Optional timeout in seconds. | |
| abort_signal (asyncio.Event | None): Optional cancellation signal. | |
| Returns: | |
| command.CommandOutput | None: Command output if successful. | |
| """ | |
| cmd = self.enumerate_cases_command_line() | |
| if not cmd: | |
| return None | |
| env = self.environment() or {} | |
| cwd = env.get("CWD") | |
| # mobly_driver (and potentially others) requires FUCHSIA_TEST_OUTDIR to be set. | |
| # We create a temporary directory for enumeration outputs. | |
| with tempfile.TemporaryDirectory() as temp_out_dir: | |
| # Adjust temp_out_dir if CWD is set, mirroring execution.py logic | |
| out_dir_val = temp_out_dir | |
| if cwd and not os.path.isabs(out_dir_val): | |
| out_dir_val = os.path.relpath(out_dir_val, cwd) | |
| env["FUCHSIA_TEST_OUTDIR"] = out_dir_val | |
| output = await run_command( | |
| *cmd, | |
| recorder=recorder, | |
| parent=parent, | |
| env=env, | |
| print_verbatim=False, | |
| timeout=timeout, | |
| abort_signal=abort_signal, | |
| ) | |
| if output and output.stdout: | |
| output.stdout = "\n".join( | |
| host_runner.MoblyRunner().parse_list_output( | |
| output.stdout, include_disabled=False | |
| ) | |
| ) | |
| return output | |
| async def enumerate_test_cases( | |
| self, | |
| recorder: event.EventRecorder, | |
| parent: event.Id | None = None, | |
| timeout: float | None = None, | |
| abort_signal: asyncio.Event | None = None, | |
| ) -> command.CommandOutput | None: | |
| """Enumerate test cases for this test. | |
| This method dispatches to specific enumeration logic based on test type. | |
| Args: | |
| recorder (event.EventRecorder): Recorder for events. | |
| parent (event.Id | None): Parent event ID. | |
| timeout (float | None): Optional timeout in seconds. | |
| abort_signal (asyncio.Event | None): Optional cancellation signal. | |
| Returns: | |
| command.CommandOutput | None: Command output if successful. | |
| """ | |
| runner = self._get_host_test_runner() | |
| if runner is not None and runner.is_mobly: | |
| return await self.enumerate_mobly_test( | |
| recorder, | |
| parent, | |
| timeout=timeout, | |
| abort_signal=abort_signal, | |
| ) | |
| cmd = self.enumerate_cases_command_line() | |
| if not cmd: | |
| return None | |
| # Standard enumeration (device tests and host runners). | |
| output = await run_command( | |
| *cmd, | |
| recorder=recorder, | |
| parent=parent, | |
| print_verbatim=False, | |
| env=self.environment(), | |
| timeout=timeout, | |
| abort_signal=abort_signal, | |
| ) | |
| if ( | |
| runner is not None | |
| and output is not None | |
| and output.return_code == 0 | |
| and output.stdout | |
| ): | |
| output.stdout = "\n".join( | |
| runner.parse_list_output( | |
| output.stdout, | |
| include_disabled=self._flags.also_run_disabled_tests, | |
| ) | |
| ) | |
| return output | |
| def environment(self) -> dict[str, str] | None: | |
| """Format environment variables needed to run the test. | |
| Returns: | |
| dict[str, str] | None: Environment for | |
| the test, or None if no environment is needed. | |
| """ | |
| env = self._flags.computed_env() | |
| if self._test.build.test.path or self._test.is_e2e_test(): | |
| env.update( | |
| { | |
| "CWD": self._exec_env.out_dir, | |
| } | |
| ) | |
| if self._is_pure_device_test() and self._test.build.test.path: | |
| if self._device_env is not None: | |
| # TODO(https://fxbug.dev/550548948): don't assume x64 host | |
| env.update( | |
| { | |
| "FUCHSIA_DEVICE_ADDR": _format_target_address( | |
| self._device_env.address, self._device_env.port | |
| ), | |
| "FUCHSIA_SSH_KEY": self._device_env.private_key_path, | |
| "FUCHSIA_HOST_TOOLS": "./host_x64", | |
| } | |
| ) | |
| if self._flags.extra_args: | |
| custom_args = " ".join(self._flags.extra_args) | |
| env.update( | |
| { | |
| "FUCHSIA_CUSTOM_TEST_ARGS": custom_args, | |
| } | |
| ) | |
| if self._test.is_e2e_test() and self._device_env is not None: | |
| env.update( | |
| { | |
| "FUCHSIA_DEVICE_ADDR": self._device_env.address, | |
| "FUCHSIA_SSH_PORT": self._device_env.port, | |
| "FUCHSIA_SSH_KEY": self._device_env.private_key_path, | |
| "FUCHSIA_NODENAME": self._device_env.name, | |
| } | |
| ) | |
| if self._exec_env.usb_socket_path: | |
| env.update( | |
| { | |
| "FUCHSIA_TEST_FFX_USB_SOCKET_PATH": self._exec_env.usb_socket_path, | |
| } | |
| ) | |
| return None if not env else env | |
| def should_symbolize(self) -> bool: | |
| """Determine if we should symbolize the output of this test. | |
| Returns: | |
| bool: True if we should run the output through a symbolizer, False otherwise. | |
| """ | |
| return self._test.info.execution is not None | |
| async def _resolve_host_test_args( | |
| self, | |
| recorder: event.EventRecorder, | |
| flags: args.Flags, | |
| parent: event.Id, | |
| *, | |
| timeout: float | None = None, | |
| abort_signal: asyncio.Event | None = None, | |
| ) -> Sequence[str]: | |
| """Resolve `--also-run-disabled-tests` and `--test-filter` args for host tests.""" | |
| if ( | |
| self._test.info.execution is not None | |
| or not self._test.build.test.path | |
| or (not flags.test_filter and not flags.also_run_disabled_tests) | |
| ): | |
| return () | |
| runner = self._get_host_test_runner() | |
| extra_runner_args: list[str] = ( | |
| list(runner.disabled_test_args()) | |
| if flags.also_run_disabled_tests and runner is not None | |
| else [] | |
| ) | |
| if not flags.test_filter: | |
| return tuple(extra_runner_args) | |
| if runner is None: | |
| raw_path = self._test.build.test.path | |
| entry_path = ( | |
| raw_path | |
| if os.path.isabs(raw_path) | |
| else os.path.join(self._exec_env.out_dir, raw_path) | |
| ) | |
| if not os.path.isfile(entry_path): | |
| raise TestCouldNotRun( | |
| f"Test binary {entry_path} does not exist; build the test or omit --no-build." | |
| ) | |
| raise TestFilterUnsupported( | |
| "Test does not support --test-filter; pass runner-specific arguments after '--' instead." | |
| ) | |
| enumeration_output = await self.enumerate_test_cases( | |
| recorder, | |
| parent, | |
| timeout=timeout, | |
| abort_signal=abort_signal, | |
| ) | |
| if enumeration_output is not None and enumeration_output.was_timeout: | |
| raise TestTimeout( | |
| "Timed out while enumerating test cases for filtering." | |
| ) | |
| if enumeration_output is None or enumeration_output.return_code != 0: | |
| raise TestCouldNotRun( | |
| f"Failed to enumerate test cases for filtering. Output: " | |
| f"{enumeration_output.stderr if enumeration_output else 'None'}" | |
| ) | |
| all_cases = tuple( | |
| stripped | |
| for line in enumeration_output.stdout.splitlines() | |
| if (stripped := line.strip()) | |
| ) | |
| try: | |
| filter_args = runner.build_filter_args(all_cases, flags.test_filter) | |
| except host_runner.UnsupportedFilterError as e: | |
| raise TestFilterUnsupported(str(e)) from e | |
| except host_runner.NoMatchingCasesError as e: | |
| raise TestSkipped(str(e)) from e | |
| extra_runner_args.extend(filter_args) | |
| return tuple(extra_runner_args) | |
| def _get_package_resolve_url(self) -> str | None: | |
| if not self._is_pure_device_test(): | |
| return None | |
| if ( | |
| _extract_package_resolve_url(self._test.build.test.package_url) | |
| is None | |
| ): | |
| return None | |
| if ( | |
| not self._test.build.test.path | |
| and self._test.info.execution is not None | |
| ): | |
| return _extract_package_resolve_url(self._get_component_url()) | |
| return _extract_package_resolve_url(self._test.build.test.package_url) | |
| def _package_resolution_environment(self) -> dict[str, str] | None: | |
| """Build a minimal environment overlay for `ffx target package resolve`. | |
| Avoids CWD (which breaks `fx` fallback when out_dir is outside | |
| FUCHSIA_DIR), test-pilot-only variables, and user `-e` overrides | |
| intended for the test binary. | |
| """ | |
| env: dict[str, str] = {} | |
| if self._device_env is not None and not os.environ.get( | |
| "FUCHSIA_NODENAME" | |
| ): | |
| target_addr = _format_target_address( | |
| self._device_env.address, self._device_env.port | |
| ) | |
| if target_addr: | |
| env["FUCHSIA_DEVICE_ADDR"] = target_addr | |
| return env if env else None | |
| async def _resolve_test_package( | |
| self, | |
| recorder: event.EventRecorder, | |
| flags: args.Flags, | |
| parent: event.Id, | |
| *, | |
| abort_signal: asyncio.Event | None, | |
| ) -> None: | |
| """Pre-resolve a fuchsia-pkg:// test package before starting the test timeout.""" | |
| resolve_url = self._get_package_resolve_url() | |
| if resolve_url is None: | |
| return | |
| if abort_signal is not None and abort_signal.is_set(): | |
| raise TestAborted(f"Aborted resolving package {resolve_url}") | |
| resolution_timeout = self._calculate_package_resolution_timeout() | |
| resolve_cmd = self._exec_env.fx_cmd_line( | |
| "ffx", "target", "package", "resolve", resolve_url | |
| ) | |
| resolve_env = self._package_resolution_environment() | |
| target_key = ( | |
| self._exec_env.out_dir, | |
| os.environ.get("FUCHSIA_NODENAME"), | |
| ( | |
| resolve_env.get("FUCHSIA_DEVICE_ADDR") | |
| if resolve_env is not None | |
| else os.environ.get("FUCHSIA_DEVICE_ADDR") | |
| ), | |
| ) | |
| cache = ( | |
| self._package_resolution_cache | |
| if self._package_resolution_cache is not None | |
| else PackageResolutionCache() | |
| ) | |
| outcome = await cache.resolve( | |
| key=(resolve_url, target_key), | |
| resolve_url=resolve_url, | |
| resolve_cmd=resolve_cmd, | |
| resolve_env=resolve_env, | |
| resolution_timeout=resolution_timeout, | |
| recorder=recorder, | |
| parent=parent, | |
| abort_signal=abort_signal, | |
| ) | |
| if outcome is None: | |
| return | |
| if outcome.aborted or ( | |
| abort_signal is not None and abort_signal.is_set() | |
| ): | |
| raise TestAborted(f"Aborted resolving package {resolve_url}") | |
| resolve_output = outcome.output | |
| if resolve_output is None: | |
| failure_message = ( | |
| f"Failed to resolve package {resolve_url}: " | |
| "failed to run command." | |
| ) | |
| recorder.emit_info_message( | |
| f"\n{statusinfo.error_highlight(self._test.name(), style=flags.style)}:\n" | |
| ) | |
| recorder.emit_verbatim_message(failure_message) | |
| raise TestPackageResolutionFailed(failure_message) | |
| if resolve_output.was_timeout: | |
| return | |
| if resolve_output.return_code != 0: | |
| failure_message = ( | |
| f"Failed to resolve package {resolve_url} " | |
| f"(exit code {resolve_output.return_code})." | |
| ) | |
| recorder.emit_info_message( | |
| f"\n{statusinfo.error_highlight(self._test.name(), style=flags.style)}:\n" | |
| ) | |
| if resolve_output.stdout: | |
| recorder.emit_verbatim_message(resolve_output.stdout) | |
| if resolve_output.stderr: | |
| recorder.emit_verbatim_message(resolve_output.stderr) | |
| if not resolve_output.stdout and not resolve_output.stderr: | |
| recorder.emit_verbatim_message(failure_message) | |
| raise TestPackageResolutionFailed( | |
| failure_message, | |
| command_output=resolve_output, | |
| ) | |
| async def run( | |
| self, | |
| recorder: event.EventRecorder, | |
| flags: args.Flags, | |
| parent: event.Id, | |
| timeout: float | None = None, | |
| abort_signal: asyncio.Event | None = None, | |
| ) -> command.CommandOutput: | |
| """Asynchronously execute this test. | |
| Args: | |
| recorder (event.EventRecorder): Recorder for events. | |
| flags (args.Flags): Command flags to control output. | |
| parent (event.Id): Parent event to nest the execution under. | |
| timeout (float, optional): If set, timeout after this number of seconds. | |
| abort_event (asyncio.Event, optional): If set and signaled, abort this test. | |
| Raises: | |
| TestAborted: If the test was aborted before completion. | |
| TestFailed: If the test reported failure. | |
| TestTimeout: If the test timed out. | |
| TestSkipped: If the test should not run or exited with skip status. | |
| Returns: | |
| command.CommandOutput: The output of executing this command. | |
| """ | |
| if self._test.is_boot_test(): | |
| raise TestSkipped( | |
| "Boot tests are not supported by `fx test`. Use `fx run-boot-test` or `fx core-tests`." | |
| ) | |
| if self._test.is_e2e_test() and not flags.e2e: | |
| raise TestSkipped( | |
| "Skipping optional end to end test. Pass --e2e to execute this test." | |
| ) | |
| exec_env = self._exec_env | |
| symbolizer_args = None | |
| if self.should_symbolize(): | |
| symbolizer_args = exec_env.fx_cmd_line("ffx", "debug", "symbolize") | |
| # We add a grace period when timing out in order to give the test itself time to time | |
| # out first. If it fails to terminate before the grace period expires, we terminate the | |
| # process. | |
| timeout = self._calculate_timeout() | |
| if timeout is not None: | |
| timeout += self._flags.timeout_grace_period | |
| extra_runner_args = await self._resolve_host_test_args( | |
| recorder, | |
| flags, | |
| parent, | |
| timeout=timeout, | |
| abort_signal=abort_signal, | |
| ) | |
| command = self.command_line(extra_runner_args=extra_runner_args) | |
| await self._resolve_test_package( | |
| recorder, | |
| flags, | |
| parent, | |
| abort_signal=abort_signal, | |
| ) | |
| env = self.environment() or {} | |
| outdir = self._outdir | |
| maybe_temp_dir: tempfile.TemporaryDirectory[str] | None = None | |
| if not outdir: | |
| maybe_temp_dir = tempfile.TemporaryDirectory() | |
| outdir = maybe_temp_dir.name | |
| if not os.path.exists(outdir): | |
| os.makedirs(outdir) | |
| # Update the outdir to match the current working directory for the test command (if any). | |
| # Only do this if the output directory is a relative path, otherwise keep it as is. | |
| if "CWD" in env and not os.path.isabs(outdir): | |
| outdir = os.path.relpath(outdir, env["CWD"]) | |
| env.update( | |
| { | |
| "FUCHSIA_TEST_OUTDIR": outdir, | |
| } | |
| ) | |
| try: | |
| async with self._profile_session( | |
| recorder, parent, abort_signal | |
| ) as profile_result: | |
| output = await run_command( | |
| *command, | |
| recorder=recorder, | |
| parent=parent, | |
| print_verbatim=flags.output, | |
| symbolizer_args=symbolizer_args, | |
| env=env, | |
| timeout=timeout, | |
| abort_signal=abort_signal, | |
| ) | |
| finally: | |
| if maybe_temp_dir is not None: | |
| files: list[str] = [] | |
| for prefix, _, names in os.walk(maybe_temp_dir.name): | |
| files.extend( | |
| [ | |
| os.path.relpath( | |
| os.path.join(prefix, n), maybe_temp_dir.name | |
| ) | |
| for n in names | |
| ] | |
| ) | |
| if files: | |
| name_list = statusinfo.ellipsize(", ".join(files), 100) | |
| recorder.emit_instruction_message( | |
| f"Deleting {len(files)} files at {maybe_temp_dir.name}: {name_list}" | |
| ) | |
| recorder.emit_instruction_message( | |
| "To keep these files, set --ffx-output-directory." | |
| ) | |
| maybe_temp_dir.cleanup() | |
| if not output: | |
| raise TestFailed("Failed to run the test command") | |
| elif ( | |
| self.is_host_test() | |
| and not output.was_timeout | |
| and ( | |
| skipped_exit_code := self._test.build.test.skipped_test_exit_code | |
| ) | |
| is not None | |
| and skipped_exit_code > 0 | |
| and output.return_code == skipped_exit_code | |
| ): | |
| skip_message = ( | |
| f"Test exited with skip status (exit code {skipped_exit_code})." | |
| if flags.output | |
| else _format_skip_message(output, skipped_exit_code) | |
| ) | |
| raise TestSkipped( | |
| skip_message, | |
| command_output=output, | |
| ) | |
| elif output.return_code != 0 or output.was_timeout: | |
| if not flags.output: | |
| # If output wasn't streamed live, print the header for the failure. | |
| recorder.emit_info_message( | |
| f"\n{statusinfo.error_highlight(self._test.name(), style=flags.style)}:\n" | |
| ) | |
| if flags.gemini_analysis is not None: | |
| error_log_parts = [] | |
| if output.stdout: | |
| error_log_parts.append(output.stdout) | |
| if output.stderr: | |
| error_log_parts.append(output.stderr) | |
| if not output.stdout and not output.stderr: | |
| error_log_parts.append("<No command output>") | |
| error_log = "\n".join(error_log_parts) | |
| if error_log and not error_log.endswith("\n"): | |
| error_log += "\n" | |
| if error_log: | |
| api_key = self._exec_env.gemini_api_key | |
| if not api_key: | |
| recorder.emit_warning_message( | |
| "Gemini analysis skipped: GEMINI_API_KEY environment variable not set." | |
| ) | |
| else: | |
| # TODO(https://fxbug.dev/456511584): change gemini_analysis call to use a built binary | |
| gemini_tool_path = os.path.join( | |
| self._exec_env.fuchsia_dir, | |
| "tools/gemini_analysis/gemini_analysis.py", | |
| ) | |
| gemini_output = await run_command( | |
| gemini_tool_path, | |
| "--gemini-model", | |
| flags.gemini_model, | |
| "--verbosity", | |
| str(flags.gemini_analysis), | |
| recorder=recorder, | |
| parent=parent, | |
| print_verbatim=True, | |
| input_bytes=error_log.encode(), | |
| env={"GEMINI_API_KEY": api_key}, | |
| ) | |
| if not gemini_output or gemini_output.return_code != 0: | |
| recorder.emit_warning_message( | |
| "Gemini analysis failed." | |
| ) | |
| if gemini_output and gemini_output.stderr: | |
| recorder.emit_verbatim_message( | |
| gemini_output.stderr | |
| ) | |
| elif not flags.output: | |
| # gemini is off, give output | |
| if output.stdout: | |
| recorder.emit_verbatim_message(output.stdout) | |
| if output.stderr: | |
| recorder.emit_verbatim_message(output.stderr) | |
| if not output.stderr and not output.stdout: | |
| recorder.emit_verbatim_message("<No command output>") | |
| if output.was_timeout: | |
| raise TestTimeout( | |
| f"Test exceeded runtime of {timeout} seconds", | |
| command_output=output, | |
| ) | |
| else: | |
| raise TestFailed("Test reported failure", command_output=output) | |
| elif profile_result.stop_error: | |
| raise TestProfilerStopFailed( | |
| profile_result.stop_error, command_output=output | |
| ) | |
| return output | |
| def _get_component_url(self) -> str | None: | |
| """Get the final component URL to execute for this test. | |
| If this test is not a component test, return None. | |
| Raises: | |
| TestCouldNotRun: If we cannot determine the merkle hash for this test. | |
| Returns: | |
| str | None: The final URL to execute (optionally with | |
| hash), or None if this is not a component test. | |
| """ | |
| if self._test.info.execution is None: | |
| return None | |
| execution = self._test.info.execution | |
| component_url = execution.component_url | |
| if self._flags.use_package_hash: | |
| try: | |
| package_repo = ( | |
| package_repository.PackageRepository.from_env_cached( | |
| self._exec_env | |
| ) | |
| ) | |
| component_url = package_repo.resolve_component_url( | |
| component_url | |
| ) | |
| except package_repository.PackageRepositoryError as e: | |
| raise TestCouldNotRun( | |
| f"Could not load a Merkle hash for this test ({str(e)}).\nTry running fx build." | |
| f"{package_repository.MERKLE_ERROR_HELP_SUFFIX}" | |
| if package_repository.MERKLE_ERROR_HELP_SUFFIX not in str(e) | |
| else str(e) | |
| ) | |
| return component_url | |
| def _is_pure_device_test(self) -> bool: | |
| """Determine if this test is a pure device test. | |
| Returns: | |
| True if the wrapped test is a pure device test, False otherwise. | |
| """ | |
| return self._test.is_pure_device_test() | |
| def _calculate_timeout(self) -> float | None: | |
| # Use the config/default timeout if not specified on the command line. If a zero timeout | |
| # is specified, do not time out. | |
| if self._flags.timeout is None: | |
| if self._test.build.test.timeout_secs is not None: | |
| return self._test.build.test.timeout_secs | |
| else: | |
| return DEFAULT_TIMEOUT | |
| elif self._flags.timeout > 0: | |
| return self._flags.timeout | |
| else: | |
| return None | |
| def _calculate_package_resolution_timeout(self) -> float | None: | |
| # Disable package resolution timeout when timeouts are explicitly disabled | |
| # (e.g. --timeout=0 or during a debugging session). | |
| if self._flags.timeout is not None and self._flags.timeout <= 0: | |
| return None | |
| configured_timeout = ( | |
| self._test.build.test.package_resolution_timeout_secs | |
| ) | |
| if configured_timeout is not None and configured_timeout > 0: | |
| return configured_timeout | |
| return DEFAULT_PACKAGE_RESOLUTION_TIMEOUT | |
| def _ffx_profiler(self, *ffx_args: str) -> list[str]: | |
| return self._exec_env.fx_cmd_line("ffx", "profiler", *ffx_args) | |
| @contextlib.asynccontextmanager | |
| async def _profile_session( | |
| self, | |
| recorder: event.EventRecorder, | |
| parent: event.Id, | |
| abort_signal: asyncio.Event | None, | |
| ) -> typing.AsyncIterator[_ProfileSessionResult]: | |
| """Wrap a test execution in a background `ffx profiler attach` session.""" | |
| result = _ProfileSessionResult() | |
| if not self._flags.profiler: | |
| yield result | |
| return | |
| def is_aborted() -> bool: | |
| return abort_signal is not None and abort_signal.is_set() | |
| if is_aborted(): | |
| raise TestAborted("Aborted before starting profiler session.") | |
| async def abort_session(signal: asyncio.Event | None = None) -> None: | |
| await run_command( | |
| *self._ffx_profiler("stop", "--abort"), | |
| recorder=recorder, | |
| parent=parent, | |
| quiet_mode=True, | |
| timeout=_PROFILER_ABORT_TIMEOUT_SECONDS, | |
| abort_signal=signal, | |
| ) | |
| attach_args = self._flags.profiler_attach_args | |
| stop_args = [*self._flags.profiler_stop_args] | |
| if "--print-stats" not in stop_args: | |
| stop_args.append("--print-stats") | |
| if any( | |
| arg.split("=", 1)[0] in _PROFILER_TARGET_FLAGS | |
| for arg in attach_args | |
| ): | |
| profile_target_args = [] | |
| else: | |
| # test_pilot (a pure device test with a host path) launches the | |
| # component by its unhashed URL. | |
| url = ( | |
| ( | |
| self._test.info.execution.component_url | |
| if self._test.info.execution is not None | |
| else None | |
| ) | |
| if self._is_pure_device_test() and self._test.build.test.path | |
| else self._get_component_url() | |
| ) | |
| profile_target_args = ( | |
| ["--url", url] if url is not None else ["--system-wide"] | |
| ) | |
| attach_cmd = self._ffx_profiler( | |
| "attach", *profile_target_args, "--background", *attach_args | |
| ) | |
| async def run_attach() -> command.CommandOutput | None: | |
| return await run_command( | |
| *attach_cmd, | |
| recorder=recorder, | |
| parent=parent, | |
| timeout=_PROFILER_ATTACH_TIMEOUT_SECONDS, | |
| abort_signal=abort_signal, | |
| ) | |
| start_out = await run_attach() | |
| if ( | |
| start_out | |
| and start_out.return_code != 0 | |
| and ( | |
| "TooManySessions" in start_out.stderr | |
| or "TooManySessions" in start_out.stdout | |
| ) | |
| and not is_aborted() | |
| ): | |
| recorder.emit_warning_message( | |
| "Aborting existing profiler session on device before retrying." | |
| ) | |
| await abort_session(abort_signal) | |
| start_out = await run_attach() | |
| if not is_aborted() and (not start_out or start_out.return_code != 0): | |
| detail = ( | |
| (start_out.stderr.strip() or start_out.stdout.strip()) | |
| if start_out | |
| else "" | |
| ) | |
| suffix = f":\n{detail}" if detail else "." | |
| raise TestCouldNotRun( | |
| f"Failed to start background `ffx profiler attach` session{suffix}" | |
| ) | |
| stopped = False | |
| try: | |
| if is_aborted(): | |
| raise TestAborted("Aborted while starting profiler session.") | |
| yield result | |
| if is_aborted(): | |
| recorder.emit_warning_message( | |
| "Aborted test run; discarding profiler session." | |
| ) | |
| else: | |
| stop_out = await run_command( | |
| *self._ffx_profiler("stop", *stop_args), | |
| recorder=recorder, | |
| parent=parent, | |
| print_verbatim=True, | |
| timeout=_PROFILER_STOP_TIMEOUT_SECONDS, | |
| abort_signal=abort_signal, | |
| ) | |
| if ( | |
| stop_out | |
| and stop_out.return_code == 0 | |
| and not stop_out.was_timeout | |
| ): | |
| stopped = True | |
| else: | |
| detail = ( | |
| (stop_out.stderr.strip() or stop_out.stdout.strip()) | |
| if stop_out | |
| else "" | |
| ) | |
| suffix = f": {detail}" if detail else "." | |
| result.stop_error = f"Failed to stop profiler session and write profile{suffix}" | |
| recorder.emit_warning_message(result.stop_error) | |
| finally: | |
| if not stopped: | |
| await abort_session() | |
| class DeviceConfigError(Exception): | |
| """There was an error reading the device configuration""" | |
| def _parse_device_address( | |
| target_line: str, | |
| raw_output: str = "", | |
| stderr: str = "", | |
| return_code: int = 0, | |
| ) -> tuple[str, str]: | |
| """Parse and validate a device target address and port. | |
| Args: | |
| target_line: The raw address string (e.g. from `ffx target list`). | |
| raw_output: Raw stdout from command, for error reporting. | |
| stderr: Raw stderr from command, for error reporting. | |
| return_code: Process return code, for error reporting. | |
| Returns: | |
| A tuple of (address, port). | |
| Raises: | |
| DeviceConfigError: If the address or port is invalid or cannot be parsed. | |
| """ | |
| target_line = target_line.strip() | |
| if ":" not in target_line: | |
| raise DeviceConfigError( | |
| f"Could not parse target address: {raw_output or target_line!r}.\n" | |
| f"Expected 'ip:port' format.\n" | |
| f"Return code: {return_code},\n" | |
| f"Stderr: {stderr!r}" | |
| ) | |
| if target_line.startswith("["): | |
| closing_bracket = target_line.find("]") | |
| if closing_bracket == -1: | |
| raise DeviceConfigError( | |
| f"Could not parse target address: {raw_output or target_line!r}.\n" | |
| f"Missing closing bracket in IPv6 address.\n" | |
| f"Return code: {return_code},\n" | |
| f"Stderr: {stderr!r}" | |
| ) | |
| ip_inside = target_line[1:closing_bracket].strip() | |
| if not ip_inside: | |
| raise DeviceConfigError( | |
| f"Could not parse target address: {raw_output or target_line!r}.\n" | |
| f"Empty IPv6 address in brackets." | |
| ) | |
| base_ip = ip_inside | |
| if "%" in ip_inside: | |
| base_ip, scope_id = ip_inside.split("%", 1) | |
| if not scope_id: | |
| raise DeviceConfigError( | |
| f"Could not parse target address: {raw_output or target_line!r}.\n" | |
| f"Empty scope ID in IPv6 address." | |
| ) | |
| try: | |
| ipaddress.IPv6Address(base_ip) | |
| except ValueError as e: | |
| raise DeviceConfigError( | |
| f"Invalid IPv6 address in target: {ip_inside!r}: {e}" | |
| ) | |
| ip = target_line[0 : closing_bracket + 1] | |
| remainder = target_line[closing_bracket + 1 :].strip() | |
| if remainder: | |
| if not remainder.startswith(":") or len(remainder) == 1: | |
| raise DeviceConfigError( | |
| f"Could not parse target address: {raw_output or target_line!r}.\n" | |
| f"Invalid or missing port after closing bracket." | |
| ) | |
| port = remainder[1:].strip() | |
| else: | |
| port = "22" | |
| elif target_line.startswith(("usb:cid:", "vsock:cid:")): | |
| last_colon_index = target_line.rfind(":") | |
| ip = target_line[0:last_colon_index].strip() | |
| port = target_line[last_colon_index + 1 :].strip() | |
| if not port.isdigit(): | |
| raise DeviceConfigError( | |
| f"Invalid CID in target address: {port!r}.\n" | |
| f"Expected non-negative integer." | |
| ) | |
| return ip, port | |
| elif target_line.count(":") > 1: | |
| # Unbracketed IPv6 address without port (e.g. fe80::1 or fe80::1%eth0) | |
| base_ip = target_line | |
| if "%" in target_line: | |
| base_ip, scope_id = target_line.split("%", 1) | |
| if not scope_id: | |
| raise DeviceConfigError( | |
| f"Could not parse target address: {raw_output or target_line!r}.\n" | |
| f"Empty scope ID in IPv6 address." | |
| ) | |
| try: | |
| ipaddress.IPv6Address(base_ip) | |
| except ValueError as e: | |
| raise DeviceConfigError( | |
| f"Invalid IPv6 address in target: {target_line!r}: {e}" | |
| ) | |
| ip = target_line | |
| port = "22" | |
| else: | |
| # IPv4 or hostname with port (e.g. 192.168.1.1:8022 or localhost:22) | |
| last_colon_index = target_line.rfind(":") | |
| ip = target_line[0:last_colon_index].strip() | |
| port = target_line[last_colon_index + 1 :].strip() | |
| if not ip: | |
| raise DeviceConfigError( | |
| f"Could not parse target address: {raw_output or target_line!r}.\n" | |
| f"Missing host/IP before colon." | |
| ) | |
| if not port: | |
| raise DeviceConfigError( | |
| f"Could not parse target address: {raw_output or target_line!r}.\n" | |
| f"Missing port after colon." | |
| ) | |
| if not port.isdigit() or not (1 <= int(port) <= 65535): | |
| raise DeviceConfigError( | |
| f"Invalid port in target address: {port!r}.\n" | |
| f"Expected integer between 1 and 65535." | |
| ) | |
| return ip, port | |
| async def get_device_environment_from_exec_env( | |
| exec_env: environment.ExecutionEnvironment, | |
| recorder: event.EventRecorder | None = None, | |
| ) -> environment.DeviceEnvironment: | |
| # Wait for the target to become ready and reachable. | |
| # This is more efficient than polling ffx target list in a sleep loop. | |
| wait_output = await run_command( | |
| *exec_env.fx_cmd_line("ffx", "target", "wait", "-t", "10"), | |
| recorder=recorder, | |
| timeout=_DEVICE_PROBE_TIMEOUT_SECONDS, | |
| ) | |
| if not wait_output or wait_output.return_code != 0: | |
| raise DeviceConfigError("Failed to wait for target to become reachable") | |
| target_output = await run_command( | |
| *exec_env.fx_cmd_line("ffx", "target", "default", "get"), | |
| recorder=recorder, | |
| timeout=_DEVICE_PROBE_TIMEOUT_SECONDS, | |
| ) | |
| if not target_output or target_output.return_code != 0: | |
| raise DeviceConfigError( | |
| "Failed to get the target name. Please ensure you have set a default target using 'fx set-device'. See 'fx set-device --help' for more details on target resolution." | |
| ) | |
| target_name = target_output.stdout.strip() | |
| ssh_output = await run_command( | |
| *exec_env.fx_cmd_line( | |
| "ffx", | |
| "target", | |
| "list", | |
| "--format", | |
| "addresses-with-scope", | |
| target_name, | |
| ), | |
| recorder=recorder, | |
| timeout=_DEVICE_PROBE_TIMEOUT_SECONDS, | |
| ) | |
| if ( | |
| not ssh_output | |
| or ssh_output.return_code != 0 | |
| or not ssh_output.stdout.strip() | |
| ): | |
| raise DeviceConfigError("Failed to get the ssh address of the target") | |
| target_line = ssh_output.stdout.strip().splitlines()[-1].strip() | |
| ip, port = _parse_device_address( | |
| target_line, | |
| raw_output=ssh_output.stdout, | |
| stderr=ssh_output.stderr, | |
| return_code=ssh_output.return_code, | |
| ) | |
| # get the configured private key. Ideally, the private key usage | |
| # should be an implementation detail internal to ffx commands. | |
| ssh_key_output = await run_command( | |
| *exec_env.fx_cmd_line( | |
| "ffx", | |
| "config", | |
| "get", | |
| "--process", | |
| "file", | |
| "ssh.priv", | |
| ), | |
| recorder=recorder, | |
| timeout=_DEVICE_PROBE_TIMEOUT_SECONDS, | |
| ) | |
| if not ssh_key_output or ssh_key_output.return_code != 0: | |
| msg = "No return information" | |
| if ssh_key_output: | |
| msg = ssh_key_output.stderr | |
| raise DeviceConfigError( | |
| f"Failed to get private ssh key: {msg}. Please check your ffx configuration by running 'ffx config get ssh.priv' or 'ffx config env'." | |
| ) | |
| ssh_path = ssh_key_output.stdout.strip() | |
| # remove any double quotes around the path | |
| ssh_path = ssh_path.replace('"', "") | |
| if not os.path.exists(ssh_path): | |
| raise DeviceConfigError( | |
| f"Path returned by 'ssh.priv' does not exist: {ssh_path}. Please check your ffx configuration by running 'ffx config get ssh.priv'. You can also check where config files are located by running 'ffx config env'." | |
| ) | |
| return environment.DeviceEnvironment( | |
| address=ip, port=port, name=target_name, private_key_path=ssh_path | |
| ) | |
| async def run_command( | |
| name: str, | |
| *args: str, | |
| recorder: event.EventRecorder | None = None, | |
| parent: event.Id | None = None, | |
| print_verbatim: bool = False, | |
| symbolizer_args: list[str] | None = None, | |
| env: dict[str, str] | None = None, | |
| timeout: float | None = None, | |
| abort_signal: asyncio.Event | None = None, | |
| quiet_mode: bool = False, | |
| input_bytes: bytes | None = None, | |
| do_not_log_output: bool = False, | |
| ) -> command.CommandOutput | None: | |
| """Utility method to run a test command asynchronously. | |
| Args: | |
| name (str): Command to run. | |
| args (list[str]): Arguments to the command. | |
| recorder (event.EventRecorder | None): | |
| Recorder for events. Defaults to None. | |
| parent (event.Id | None): Parent event ID for reporting. | |
| Defaults to None. | |
| print_verbatim (bool, optional): If set, record verbatim | |
| output events for stdout and stderr. Defaults to False. | |
| symbolize (bool, optional): If true, pipe output through | |
| symbolizer. Defaults to False. | |
| env (dict[str, str], optional): | |
| Environment to pass to the command. Defaults to None. | |
| timeout (float, optional): The number of seconds to wait before timing out. | |
| abort_signal (asyncio.Event, optional): If set, when the | |
| event is signaled this command will attempt a graceful | |
| termination. | |
| quiet_mode (bool, optional): If set, this command will run | |
| quietly in the background and will not announce cancellation or | |
| clutter the running task list. | |
| do_not_log_output (bool, optional): If set, this command will not log its output. | |
| This is useful for noisy programs whose output may be too much for | |
| downstream processing. | |
| Returns: | |
| command.CommandOutput | None: The command output if it could | |
| be executed, None otherwise. | |
| """ | |
| event_id: event.Id | None = None | |
| abort_task: asyncio.Task[None] | None = None | |
| if recorder is not None: | |
| logged_env = env | |
| if env: | |
| logged_env = { | |
| k: ("<REDACTED>" if "API_KEY" in k.upper() else v) | |
| for k, v in env.items() | |
| } | |
| event_id = recorder.emit_program_start( | |
| name, list(args), logged_env, parent=parent, quiet_mode=quiet_mode | |
| ) | |
| try: | |
| started = await command.AsyncCommand.create( | |
| name, | |
| *args, | |
| symbolizer_args=symbolizer_args, | |
| env=env, | |
| timeout=timeout, | |
| input_bytes=input_bytes, | |
| ) | |
| async def handle_abort() -> None: | |
| if abort_signal is not None: | |
| await abort_signal.wait() | |
| if recorder is not None and not quiet_mode: | |
| recorder.emit_info_message(f"Aborting {name}...") | |
| started.terminate() | |
| runner_task = getattr(started, "_runner_task", None) | |
| if runner_task is not None: | |
| try: | |
| await asyncio.wait_for( | |
| asyncio.shield(runner_task), | |
| timeout=5.0, | |
| ) | |
| return | |
| except asyncio.TimeoutError: | |
| pass | |
| else: | |
| await asyncio.sleep(5) | |
| if recorder is not None: | |
| recorder.emit_warning_message( | |
| f"{name} did not terminate in time, killing it" | |
| ) | |
| started.kill() | |
| abort_task = asyncio.Task(handle_abort()) | |
| def handle_event(current_event: command.CommandEvent) -> None: | |
| if recorder is not None: | |
| assert event_id is not None | |
| if ( | |
| isinstance(current_event, command.StdoutEvent) | |
| and not do_not_log_output | |
| ): | |
| recorder.emit_program_output( | |
| event_id, | |
| current_event.text.decode(errors="replace"), | |
| stream=event.ProgramOutputStream.STDOUT, | |
| print_verbatim=print_verbatim, | |
| ) | |
| if ( | |
| isinstance(current_event, command.StderrEvent) | |
| and not do_not_log_output | |
| ): | |
| recorder.emit_program_output( | |
| event_id, | |
| current_event.text.decode(errors="replace"), | |
| stream=event.ProgramOutputStream.STDERR, | |
| print_verbatim=print_verbatim, | |
| ) | |
| if isinstance(current_event, command.TerminationEvent): | |
| recorder.emit_program_termination( | |
| event_id, current_event.return_code | |
| ) | |
| ret = await started.run_to_completion(callback=handle_event) | |
| return ret | |
| except command.AsyncCommandError as e: | |
| if recorder is not None: | |
| assert event_id is not None | |
| recorder.emit_program_termination(event_id, -1, error=str(e)) | |
| return None | |
| finally: | |
| if abort_task is not None: | |
| abort_task.cancel() |