From 5e91e19cbe041e9c7b7e829f48c3b863f3d10e1d Mon Sep 17 00:00:00 2001 From: Ang Li Date: Wed, 11 Nov 2026 20:12:05 +0000 Subject: [PATCH] Recover offline TCP adb transports during root_adb and handle_reboot On TCP-connected Android devices (host:port), restarting adbd via adb root severs the TCP socket and can leave the host adb server transport stuck offline indefinitely. Retrying adb root alone cannot recover a dead TCP transport. Disconnect and reconnect TCP transports before retrying failed adb root calls and when wait-for-device times out after adb root. Also ensure AndroidDevice.handle_reboot restarts stopped services in its finally block even if root_adb raises. --- mobly/controllers/android_device.py | 43 ++++++- mobly/controllers/android_device_lib/adb.py | 50 +++++++- .../android_device_lib/adb_test.py | 112 ++++++++++++++++++ .../mobly/controllers/android_device_test.py | 108 +++++++++++++++++ 4 files changed, 305 insertions(+), 8 deletions(-) diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py index c0e4845a..25b7b272 100644 --- a/mobly/controllers/android_device.py +++ b/mobly/controllers/android_device.py @@ -753,9 +753,23 @@ def handle_reboot( self._build_info = None self._is_rootable = None self._is_rebooting = False - if self.is_rootable: - self.root_adb() - self.services.start_services(live_service_names) + root_err = None + try: + if self.is_rootable: + self.root_adb() + except Exception as err: # pylint: disable=broad-except + root_err = err + raise + finally: + if root_err is None: + self.services.start_services(live_service_names) + else: + try: + self.services.start_services(live_service_names) + except Exception: # pylint: disable=broad-except + self.log.exception( + 'Failed to restart services after root_adb failure.' + ) @contextlib.contextmanager def handle_usb_disconnect(self): @@ -927,6 +941,27 @@ def load_config(self, config): setattr(self, k, v) self.add_device_info(k, v) + def _wait_for_device_after_root(self): + """Waits for adb to return after `adb root`, reconnecting TCP if stuck.""" + if adb.is_tcp_device(self.serial): + try: + self.adb.wait_for_device(timeout=adb.ADB_ROOT_ATTEMPT_TIMEOUT_SEC) + return + except (adb.AdbError, adb.AdbTimeoutError): + self.log.debug( + 'TCP adb transport offline after `adb root`; reconnecting %s.', + self.serial, + ) + with contextlib.suppress(adb.AdbError, adb.AdbTimeoutError): + self.adb.disconnect( + self.serial, timeout=adb.ADB_ROOT_ATTEMPT_TIMEOUT_SEC + ) + with contextlib.suppress(adb.AdbError, adb.AdbTimeoutError): + self.adb.connect( + self.serial, timeout=adb.ADB_ROOT_ATTEMPT_TIMEOUT_SEC + ) + self.adb.wait_for_device(timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND) + def root_adb(self): """Change adb to root mode for this device if allowed. @@ -936,7 +971,7 @@ def root_adb(self): self.adb.root() # `root` causes the device to temporarily disappear from adb. # So we need to wait for the device to come back before proceeding. - self.adb.wait_for_device(timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND) + self._wait_for_device_after_root() def load_snippet(self, name, package, config=None): """Starts the snippet apk with the given package name and connects. diff --git a/mobly/controllers/android_device_lib/adb.py b/mobly/controllers/android_device_lib/adb.py index 006758ee..de78b3e4 100644 --- a/mobly/controllers/android_device_lib/adb.py +++ b/mobly/controllers/android_device_lib/adb.py @@ -118,6 +118,14 @@ def is_adb_available(): return shutil.which('adb') is not None +def is_tcp_device(serial: str) -> bool: + """Returns True if `serial` identifies a `host:port` TCP adb endpoint.""" + if not serial or serial.startswith('usb:'): + return False + host, sep, port = serial.rpartition(':') + return bool(sep and host and port.isdigit()) + + def list_occupied_adb_ports(): """Lists all the host ports occupied by adb forward. @@ -354,20 +362,22 @@ def current_user_id(self) -> int: # Multi-user is not supported in SDK < 21, only user 0 exists. return 0 - def connect(self, address) -> bytes: + def connect(self, address, timeout=None) -> bytes: """Executes the `adb connect` command with proper status checking. Args: address: string, the address of the Android instance to connect to. + timeout: float, optional number of seconds to wait before timing out. Returns: The stdout content. Raises: AdbError: if the connection failed. + AdbTimeoutError: if the command timed out. """ stdout = self._exec_adb_cmd( - 'connect', address, shell=False, timeout=None, stderr=None + 'connect', address, shell=False, timeout=timeout, stderr=None ) if PATTERN_ADB_CONNECT_SUCCESS.match(stdout.decode('utf-8')) is None: raise AdbError( @@ -521,16 +531,46 @@ def instrument( 'shell', instrumentation_command, shell=False, handler=handler ) + def _reconnect_tcp_device(self) -> None: + """Re-establishes a TCP adb transport that went offline.""" + logging.debug('Reconnecting TCP adb transport for %s.', self.serial) + try: + self._exec_adb_cmd( + 'disconnect', + self.serial, + shell=False, + timeout=ADB_ROOT_ATTEMPT_TIMEOUT_SEC, + stderr=None, + ) + except (AdbError, AdbTimeoutError): + pass + try: + self.connect(self.serial, timeout=ADB_ROOT_ATTEMPT_TIMEOUT_SEC) + self._exec_adb_cmd( + 'wait-for-device', + args=None, + shell=False, + timeout=ADB_ROOT_ATTEMPT_TIMEOUT_SEC, + stderr=None, + ) + except (AdbError, AdbTimeoutError) as err: + logging.debug( + 'TCP adb reconnect for %s did not succeed: %s', self.serial, err + ) + def root(self) -> bytes: """Enables ADB root mode on the device. This method will retry to execute the command `adb root` when an AdbError occurs, since sometimes the error `adb: unable to connect for root: closed` is raised when executing `adb root` immediately after - the device is booted to OS. + the device is booted to OS. For TCP-connected devices (`host:port`), + retrying `adb root` alone cannot recover a severed TCP transport left + `offline`, so the transport is disconnected and reconnected before + retrying. Returns: - A string that is the stdout of root command. + A byte string that is the stdout of root command. Raises: AdbError: If the command exit code is not 0. @@ -562,6 +602,8 @@ def root(self) -> bytes: # Buffer between "adb root" commands. time.sleep(retry_interval) retry_interval *= 2 + if is_tcp_device(self.serial): + self._reconnect_tcp_device() else: raise e diff --git a/tests/mobly/controllers/android_device_lib/adb_test.py b/tests/mobly/controllers/android_device_lib/adb_test.py index 0f23e126..3f099f0e 100755 --- a/tests/mobly/controllers/android_device_lib/adb_test.py +++ b/tests/mobly/controllers/android_device_lib/adb_test.py @@ -936,6 +936,118 @@ def test_root_success_with_retry_after_timeout( self.assertEqual(mock_sleep.call_count, 1) mock_sleep.assert_called_with(10) + def test_is_tcp_device(self): + self.assertTrue(adb.is_tcp_device('localhost:14016')) + self.assertTrue(adb.is_tcp_device('127.0.0.1:5555')) + self.assertTrue(adb.is_tcp_device('[::1]:5555')) + self.assertFalse(adb.is_tcp_device('')) + self.assertFalse(adb.is_tcp_device('HT75B1A00123')) + self.assertFalse(adb.is_tcp_device('emulator-5554')) + self.assertFalse(adb.is_tcp_device('usb:1-2')) + self.assertFalse(adb.is_tcp_device(':5555')) + self.assertFalse(adb.is_tcp_device('localhost:abc')) + + @mock.patch('time.sleep', return_value=mock.MagicMock()) + @mock.patch.object(adb.AdbProxy, '_exec_cmd') + def test_root_tcp_device_reconnects_after_timeout( + self, mock_exec_cmd, mock_sleep + ): + serial = 'localhost:14016' + mock_exec_cmd.side_effect = [ + adb.AdbTimeoutError(['adb', '-s', serial, 'root'], 5, serial), + adb.AdbError( + ['adb', '-s', serial, 'disconnect', serial], + b'', + b"error: no such device 'localhost:14016'\n", + 1, + serial, + ), + f'connected to {serial}\n'.encode('utf-8'), + b'', + MOCK_ROOT_SUCCESS_OUTPUT, + ] + output = adb.AdbProxy(serial).root() + self.assertEqual(output, MOCK_ROOT_SUCCESS_OUTPUT) + self.assertEqual( + mock_exec_cmd.call_args_list, + [ + mock.call( + ['adb', '-s', serial, 'root'], + shell=False, + timeout=5, + stderr=None, + ), + mock.call( + ['adb', '-s', serial, 'disconnect', serial], + shell=False, + timeout=5, + stderr=None, + ), + mock.call( + ['adb', '-s', serial, 'connect', serial], + shell=False, + timeout=5, + stderr=None, + ), + mock.call( + ['adb', '-s', serial, 'wait-for-device'], + shell=False, + timeout=5, + stderr=None, + ), + mock.call( + ['adb', '-s', serial, 'root'], + shell=False, + timeout=5, + stderr=None, + ), + ], + ) + mock_sleep.assert_called_once_with(10) + + @mock.patch('time.sleep', return_value=mock.MagicMock()) + @mock.patch.object(adb.AdbProxy, '_exec_cmd') + def test_root_tcp_device_continues_retry_when_reconnect_fails( + self, mock_exec_cmd, mock_sleep + ): + serial = 'localhost:14016' + offline_err = adb.AdbError( + ['adb', '-s', serial, 'root'], + b'', + b'adb: unable to connect for root: device offline\n', + 1, + serial, + ) + mock_exec_cmd.side_effect = [ + offline_err, + b'', + b'Connection refused\n', + offline_err, + b'', + f'connected to {serial}\n'.encode('utf-8'), + b'', + MOCK_ROOT_SUCCESS_OUTPUT, + ] + output = adb.AdbProxy(serial).root() + self.assertEqual(output, MOCK_ROOT_SUCCESS_OUTPUT) + self.assertEqual(mock_sleep.call_args_list, [mock.call(10), mock.call(20)]) + + @mock.patch('time.sleep', return_value=mock.MagicMock()) + @mock.patch.object(adb.AdbProxy, '_exec_cmd') + def test_root_usb_bus_serial_does_not_reconnect_tcp( + self, mock_exec_cmd, mock_sleep + ): + serial = 'usb:1-2' + mock_exec_cmd.side_effect = [ + adb.AdbError( + ['adb', '-s', serial, 'root'], b'', MOCK_ROOT_ERROR_OUTPUT, 1 + ), + MOCK_ROOT_SUCCESS_OUTPUT, + ] + output = adb.AdbProxy(serial).root() + self.assertEqual(output, MOCK_ROOT_SUCCESS_OUTPUT) + self.assertEqual(mock_exec_cmd.call_count, 2) + def test_has_shell_command_called_correctly(self): with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd: mock_exec_cmd.return_value = MOCK_DEFAULT_COMMAND_OUTPUT diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py index 1486d590..ba69daa0 100755 --- a/tests/mobly/controllers/android_device_test.py +++ b/tests/mobly/controllers/android_device_test.py @@ -2229,6 +2229,114 @@ def test_AndroidDevice_reboot_custom_timeout( ad.reboot(boot_completion_timeout=60) mock_wait.assert_called_once_with(timeout=60) + @mock.patch( + 'mobly.controllers.android_device_lib.adb.AdbProxy', + return_value=mock_android_device.MockAdbProxy('localhost:14016'), + ) + @mock.patch( + 'mobly.controllers.android_device_lib.fastboot.FastbootProxy', + return_value=mock_android_device.MockFastbootProxy('localhost:14016'), + ) + def test_AndroidDevice_root_adb_reconnects_tcp_when_wait_times_out( + self, FastbootProxy, MockAdbProxy + ): + serial = 'localhost:14016' + ad = android_device.AndroidDevice(serial=serial) + ad.adb.root = mock.MagicMock(return_value=b'restarting adbd as root\n') + ad.adb.disconnect = mock.MagicMock( + side_effect=adb.AdbError( + ['adb', 'disconnect'], b'', b'error: no such device\n', 1, serial + ) + ) + ad.adb.connect = mock.MagicMock( + return_value=f'connected to {serial}\n'.encode('utf-8') + ) + ad.adb.wait_for_device = mock.MagicMock( + side_effect=[ + adb.AdbTimeoutError(['adb', 'wait-for-device'], 5, serial), + b'', + ] + ) + + ad.root_adb() + + ad.adb.disconnect.assert_called_once_with( + serial, timeout=adb.ADB_ROOT_ATTEMPT_TIMEOUT_SEC + ) + ad.adb.connect.assert_called_once_with( + serial, timeout=adb.ADB_ROOT_ATTEMPT_TIMEOUT_SEC + ) + self.assertEqual( + ad.adb.wait_for_device.call_args_list, + [ + mock.call(timeout=adb.ADB_ROOT_ATTEMPT_TIMEOUT_SEC), + mock.call( + timeout=android_device.DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND + ), + ], + ) + + @mock.patch( + 'mobly.controllers.android_device_lib.adb.AdbProxy', + return_value=mock_android_device.MockAdbProxy('localhost:14016'), + ) + @mock.patch( + 'mobly.controllers.android_device_lib.fastboot.FastbootProxy', + return_value=mock_android_device.MockFastbootProxy('localhost:14016'), + ) + @mock.patch('mobly.utils.start_standing_subprocess', return_value='process') + @mock.patch('mobly.utils.stop_standing_subprocess') + @mock.patch.object(logcat.Logcat, '_open_logcat_file') + def test_AndroidDevice_handle_reboot_restarts_services_when_root_adb_raises( + self, + open_logcat_mock, + stop_proc_mock, + start_proc_mock, + FastbootProxy, + MockAdbProxy, + ): + ad = android_device.AndroidDevice(serial='localhost:14016') + ad.services.start_all() + root_err = adb.AdbError( + ['adb', 'root'], + b'', + b'adb: unable to connect for root: device offline\n', + 1, + ) + with mock.patch.object(ad, 'root_adb', side_effect=root_err): + with self.assertRaises(adb.AdbError) as ctx: + with ad.handle_reboot(): + self.assertFalse(ad.services.is_any_alive) + self.assertIs(ctx.exception, root_err) + self.assertTrue(ad.services.is_any_alive) + + @mock.patch( + 'mobly.controllers.android_device_lib.adb.AdbProxy', + return_value=mock_android_device.MockAdbProxy('localhost:14016'), + ) + @mock.patch( + 'mobly.controllers.android_device_lib.fastboot.FastbootProxy', + return_value=mock_android_device.MockFastbootProxy('localhost:14016'), + ) + def test_AndroidDevice_handle_reboot_preserves_root_error_on_service_error( + self, FastbootProxy, MockAdbProxy + ): + ad = android_device.AndroidDevice(serial='localhost:14016') + root_err = adb.AdbError(['adb', 'root'], b'', b'device offline\n', 1) + with ( + mock.patch.object(ad, 'root_adb', side_effect=root_err), + mock.patch.object( + ad.services, + 'start_services', + side_effect=RuntimeError('service start failed'), + ) as mock_start_services, + ): + with self.assertRaises(adb.AdbError) as ctx: + with ad.handle_reboot(): + pass + self.assertIs(ctx.exception, root_err) + mock_start_services.assert_called_once() + def test_AndroidDevice_getattr_without_services(self): ad = android_device.AndroidDevice.__new__(android_device.AndroidDevice) with self.assertRaisesRegex(AttributeError, 'services'):