Skip to content

Commit

Permalink
Using tcp:0 in adb forward to pick available host port in snippet cli…
Browse files Browse the repository at this point in the history
…ent (#904)

This avoids a race condition where the port picked by `portpicker` becomes occupied before adb can forward it.
  • Loading branch information
mhaoli authored Dec 15, 2023
1 parent 8ad26db commit 6c5d666
Show file tree
Hide file tree
Showing 2 changed files with 158 additions and 104 deletions.
14 changes: 11 additions & 3 deletions mobly/controllers/android_device_lib/snippet_client_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,17 @@ def make_connection(self):

def _forward_device_port(self):
"""Forwards the device port to a host port."""
if not self.host_port:
self.host_port = utils.get_available_host_port()
self._adb.forward([f'tcp:{self.host_port}', f'tcp:{self.device_port}'])
if self.host_port and self.host_port in adb.list_occupied_adb_ports():
raise errors.Error(
self._device,
f'Cannot forward to host port {self.host_port} because adb has'
' forwarded another device port to it.',
)

host_port = self.host_port or 0
# Example stdout: b'12345\n'
stdout = self._adb.forward([f'tcp:{host_port}', f'tcp:{self.device_port}'])
self.host_port = int(stdout.strip())

def create_socket_connection(self):
"""Creates a socket connection to the server.
Expand Down
Loading

0 comments on commit 6c5d666

Please sign in to comment.