diff --git a/mobly/controllers/android_device_lib/snippet_client_v2.py b/mobly/controllers/android_device_lib/snippet_client_v2.py index 054ecff0..db37ef21 100644 --- a/mobly/controllers/android_device_lib/snippet_client_v2.py +++ b/mobly/controllers/android_device_lib/snippet_client_v2.py @@ -18,6 +18,7 @@ import json import re import socket +import threading from mobly import utils from mobly.controllers.android_device_lib import adb @@ -97,6 +98,10 @@ # in the snippet server. UNKNOWN_UID = -1 +# Maximum time to wait for the snippet server instrumentation to report its +# listening port during `start_server`. +_SERVER_START_TIMEOUT_SEC = 60.0 + # Maximum time to wait for the socket to open on the device. _SOCKET_CONNECTION_TIMEOUT = 60 @@ -121,6 +126,9 @@ class Config: user_id: The user id under which to launch the snippet process. am_cmd_prefix: An optional prefix string prepended directly before the `am` command (e.g. `'CLASSPATH=/data/local/tmp/app.apk'` or `'env ...'`). + server_start_timeout_sec: Maximum seconds to wait for the snippet server to + start and report its listening port before aborting, or `None` for no + timeout. """ am_instrument_options: dict[str, str] = dataclasses.field( @@ -128,6 +136,7 @@ class Config: ) user_id: int | None = None am_cmd_prefix: str | None = None + server_start_timeout_sec: float | None = _SERVER_START_TIMEOUT_SEC class ConnectionHandshakeCommand(enum.Enum): @@ -309,11 +318,18 @@ def start_server(self): output and sets it to self.device_port. Raises: + ValueError: if `Config.server_start_timeout_sec` is not positive. errors.ServerStartProtocolError: if the protocol reported by the server startup process is unknown. - errors.ServerStartError: if failed to start the server or process the - server output. + errors.ServerStartError: if failed to start the server, timed out waiting + for startup, or failed to process the server output. """ + timeout = self._config.server_start_timeout_sec + if timeout is not None and timeout <= 0: + raise ValueError( + f'server_start_timeout_sec must be positive, got {timeout}.' + ) + persists_shell_cmd = self._get_persisting_command() self.log.debug( 'Snippet server for %s is using protocol %d.%d', @@ -330,24 +346,79 @@ def start_server(self): ) if self._config.am_cmd_prefix: cmd = f'{self._config.am_cmd_prefix.strip()} {cmd}' - self._proc = self._run_adb_cmd(cmd) - - # Check protocol version and get the device port + proc = self._run_adb_cmd(cmd) + self._proc = proc self._server_start_stdout = [] - line = self._read_protocol_line() - match = re.match('^SNIPPET START, PROTOCOL ([0-9]+) ([0-9]+)$', line) - if not match or int(match.group(1)) != _PROTOCOL_MAJOR_VERSION: - raise errors.ServerStartProtocolError(self._device, line) - - line = self._read_protocol_line() - match = re.match('^SNIPPET SERVING, PORT ([0-9]+)$', line) - if not match: - message = _SNIPPET_SERVER_START_ERROR_DEBUG_TIP.format( - instrumentation_result=line, - server_start_stdout='\n'.join(self._server_start_stdout), - ) - raise errors.ServerStartProtocolError(self._device, message) - self.device_port = int(match.group(1)) + + state_lock = threading.Lock() + completed = False + timed_out = False + timer = None + if timeout is not None: + + def _on_timeout(): + nonlocal timed_out + with state_lock: + if completed: + return + timed_out = True + try: + utils.stop_standing_subprocess(proc) + except Exception: # pylint: disable=broad-except + self.log.debug( + 'Error stopping timed-out snippet server subprocess.', + exc_info=True, + ) + + timer = threading.Timer(timeout, _on_timeout) + timer.daemon = True + timer.start() + + try: + # Check protocol version and get the device port + line = self._read_protocol_line() + match = re.match('^SNIPPET START, PROTOCOL ([0-9]+) ([0-9]+)$', line) + if not match or int(match.group(1)) != _PROTOCOL_MAJOR_VERSION: + raise errors.ServerStartProtocolError(self._device, line) + + line = self._read_protocol_line() + match = re.match('^SNIPPET SERVING, PORT ([0-9]+)$', line) + if not match: + message = _SNIPPET_SERVER_START_ERROR_DEBUG_TIP.format( + instrumentation_result=line, + server_start_stdout='\n'.join(self._server_start_stdout), + ) + raise errors.ServerStartProtocolError(self._device, message) + with state_lock: + if not timed_out: + completed = True + self.device_port = int(match.group(1)) + except Exception as err: + if timer is not None: + timer.cancel() + if timed_out: + timer.join() + self._proc = None + raise self._build_start_timeout_error(timeout) from err + raise + finally: + if timer is not None: + timer.cancel() + + if timed_out: + timer.join() + self._proc = None + raise self._build_start_timeout_error(timeout) + + def _build_start_timeout_error(self, timeout): + msg = ( + f'Timed out after {timeout}s waiting for snippet server ' + f'{self.package} to start.' + ) + if self._server_start_stdout: + stdout_str = '\n'.join(self._server_start_stdout) + msg = f'{msg}\nServer process stdout:\n{stdout_str}' + return errors.ServerStartError(self._device, msg) def _run_adb_cmd(self, cmd): """Starts a long-running adb subprocess and returns it immediately.""" diff --git a/tests/mobly/controllers/android_device_lib/snippet_client_v2_test.py b/tests/mobly/controllers/android_device_lib/snippet_client_v2_test.py index cd8542a4..dbacc83b 100644 --- a/tests/mobly/controllers/android_device_lib/snippet_client_v2_test.py +++ b/tests/mobly/controllers/android_device_lib/snippet_client_v2_test.py @@ -14,9 +14,13 @@ """Unit tests for mobly.controllers.android_device_lib.snippet_client_v2.""" import socket +import sys +import threading import unittest from unittest import mock +from mobly import utils + from mobly.controllers.android_device_lib import adb from mobly.controllers.android_device_lib import errors as android_device_lib_errors from mobly.controllers.android_device_lib import snippet_client_v2 @@ -2047,6 +2051,152 @@ def test_make_conn_with_forwarded_port_continue( 3, snippet_client_v2.ConnectionHandshakeCommand.CONTINUE ) + @mock.patch('mobly.utils.stop_standing_subprocess') + @mock.patch( + 'mobly.controllers.android_device_lib.snippet_client_v2.' + 'utils.start_standing_subprocess' + ) + def test_start_server_timeout_before_protocol_line( + self, mock_start_standing_subprocess, mock_stop_standing_subprocess + ): + """Tests start_server times out cleanly when instrumentation hangs.""" + unblock = threading.Event() + mock_stop_standing_subprocess.side_effect = lambda proc: unblock.set() + lines = iter([b'ActivityManager: user locked\n']) + + def _readline(): + try: + return next(lines) + except StopIteration: + unblock.wait(5) + return b'' + + mock_proc = mock_start_standing_subprocess.return_value + mock_proc.stdout.readline.side_effect = _readline + + config = snippet_client_v2.Config(server_start_timeout_sec=0.05) + self._make_client(config=config) + with self.assertRaisesRegex( + errors.ServerStartError, + r'Timed out after 0\.05s waiting for snippet server ' + rf'{MOCK_PACKAGE_NAME} to start\.' + r'[\s\S]*ActivityManager: user locked', + ): + self.client.start_server() + + mock_stop_standing_subprocess.assert_called_once_with(mock_proc) + self.assertIsNone(self.client._proc) + + @mock.patch('mobly.utils.stop_standing_subprocess') + @mock.patch( + 'mobly.controllers.android_device_lib.snippet_client_v2.' + 'utils.start_standing_subprocess' + ) + def test_start_server_timeout_before_port_line( + self, mock_start_standing_subprocess, mock_stop_standing_subprocess + ): + """Tests start_server times out when server never reports a port.""" + unblock = threading.Event() + mock_stop_standing_subprocess.side_effect = lambda proc: unblock.set() + lines = iter([b'SNIPPET START, PROTOCOL 1 0\n']) + + def _readline(): + try: + return next(lines) + except StopIteration: + unblock.wait(5) + return b'' + + mock_proc = mock_start_standing_subprocess.return_value + mock_proc.stdout.readline.side_effect = _readline + + config = snippet_client_v2.Config(server_start_timeout_sec=0.05) + self._make_client(config=config) + with self.assertRaisesRegex( + errors.ServerStartError, + r'Timed out after 0\.05s waiting for snippet server ' + rf'{MOCK_PACKAGE_NAME} to start\.', + ): + self.client.start_server() + + mock_stop_standing_subprocess.assert_called_once_with(mock_proc) + self.assertIsNone(self.client._proc) + + @mock.patch( + 'mobly.controllers.android_device_lib.snippet_client_v2.' + 'adb.list_occupied_adb_ports', + return_value=[], + ) + @mock.patch('mobly.utils.stop_standing_subprocess') + @mock.patch( + 'mobly.controllers.android_device_lib.snippet_client_v2.' + 'utils.start_standing_subprocess' + ) + def test_initialize_timeout_stops_subprocess_once( + self, mock_start_standing_subprocess, mock_stop_standing_subprocess, _ + ): + """Tests initialize() cleans up without stopping the subprocess twice.""" + unblock = threading.Event() + mock_stop_standing_subprocess.side_effect = lambda proc: unblock.set() + mock_proc = mock_start_standing_subprocess.return_value + mock_proc.stdout.readline.side_effect = lambda: (unblock.wait(5), b'')[1] + + config = snippet_client_v2.Config(server_start_timeout_sec=0.05) + self._make_client(config=config) + with self.assertRaisesRegex( + errors.ServerStartError, + r'Timed out after 0\.05s waiting for snippet server', + ): + self.client.initialize() + + mock_stop_standing_subprocess.assert_called_once_with(mock_proc) + self.adb.mock_shell_func.assert_any_call( + f'am instrument --user {MOCK_USER_ID} -w -e action stop ' + f'{MOCK_SERVER_PATH}', + timeout=mock.ANY, + ) + + def test_start_server_timeout_with_real_subprocess(self): + """Verifies real standing subprocess unblocks readline across platforms.""" + config = snippet_client_v2.Config(server_start_timeout_sec=0.1) + self._make_client(config=config) + with mock.patch.object( + self.client, + '_run_adb_cmd', + side_effect=lambda cmd: utils.start_standing_subprocess( + [sys.executable, '-c', 'import time; time.sleep(30)'], shell=False + ), + ): + with self.assertRaisesRegex( + errors.ServerStartError, + r'Timed out after 0\.1s waiting for snippet server ' + rf'{MOCK_PACKAGE_NAME} to start\.', + ): + self.client.start_server() + self.assertIsNone(self.client._proc) + + @mock.patch( + 'mobly.controllers.android_device_lib.snippet_client_v2.' + 'utils.start_standing_subprocess' + ) + def test_start_server_timeout_validation_and_none( + self, mock_start_subprocess + ): + """Tests invalid timeout values raise ValueError and None disables timer.""" + for bad_timeout in (0, -5): + config = snippet_client_v2.Config(server_start_timeout_sec=bad_timeout) + self._make_client(config=config) + with self.assertRaisesRegex( + ValueError, 'server_start_timeout_sec must be positive' + ): + self.client.start_server() + + config = snippet_client_v2.Config(server_start_timeout_sec=None) + self._make_client(config=config) + self._mock_server_process_starting_response(mock_start_subprocess) + self.client.start_server() + self.assertEqual(self.client.device_port, 1234) + if __name__ == '__main__': unittest.main()