Skip to content

Commit c71a6b5

Browse files
author
The android_world Authors
committed
Update implementation of function for pulling files from devices to create a new temporary directory for saving the file every time the function was called.
This ensures the function is thread safe. The old implementation would create a single temporary directory at the module level. When running Android World from multiple threads, this could result in multiple instances trying to save files with the same name in the same directory, resulting in corrupt data. The new implementation avoids this problem. PiperOrigin-RevId: 836225493
1 parent 0e95d64 commit c71a6b5

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

android_world/utils/file_utils.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,6 @@ def convert_to_posix_path(*args):
5757
return str(pathlib.Path(*args).as_posix())
5858

5959

60-
# Local temporary location for files copied to or from the device.
61-
TMP_LOCAL_LOCATION = convert_to_posix_path(
62-
get_local_tmp_directory(), "android_world"
63-
)
64-
65-
6660
@dataclasses.dataclass(frozen=True)
6761
class FileWithMetadata:
6862
"""File with its metadata like change time.
@@ -391,9 +385,10 @@ def tmp_file_from_device(
391385
FileNotFoundError: If device_file does not exist.
392386
RuntimeError: If there is an adb communication error.
393387
"""
388+
tmp_directory = tempfile.mkdtemp()
394389
head, tail = os.path.split(device_file)
395390
dir_and_file_name = convert_to_posix_path(os.path.basename(head), tail)
396-
local_file = convert_to_posix_path(TMP_LOCAL_LOCATION, dir_and_file_name)
391+
local_file = convert_to_posix_path(tmp_directory, dir_and_file_name)
397392
try:
398393
# Need root access to access many directories.
399394
adb_utils.set_root_if_needed(env, timeout_sec)
@@ -415,7 +410,14 @@ def tmp_file_from_device(
415410

416411
yield local_file
417412
finally:
418-
os.remove(local_file)
413+
try:
414+
shutil.rmtree(tmp_directory)
415+
except Exception as e: # pylint: disable=broad-exception-caught
416+
logging.error(
417+
"Failed to delete temporary directory: %s with error %s",
418+
tmp_directory,
419+
e,
420+
)
419421

420422

421423
def copy_file_to_device(
@@ -439,9 +441,7 @@ def copy_file_to_device(
439441
# escaped.
440442
escaped_path = remote_file_path.replace(" ", r"\ ").replace("'", r"\'")
441443

442-
adb_utils.issue_generic_request(
443-
["shell", "chmod", "777", escaped_path], env
444-
)
444+
adb_utils.issue_generic_request(["shell", "chmod", "777", escaped_path], env)
445445
return push_response
446446

447447

0 commit comments

Comments
 (0)