Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ def create_output_excerpts(self, test_info):
service to the call to `create_output_excerpts`.

Use `AndroidDevice#generate_filename` to get the proper filenames for
excerpts.
excerpts. Services that stream output into an append-only host file can use
:class:`~mobly.utils.IncrementalFileCopier` to copy newly appended content
on each call.

This is usually called at the end of: `setup_class`, `teardown_test`,
or `teardown_class`.
Expand Down
78 changes: 30 additions & 48 deletions mobly/controllers/android_device_lib/services/logcat.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import logging
import os
import shutil
import time
from typing import Any, Callable, Optional, Pattern, Sequence, Set, Union

Expand Down Expand Up @@ -80,9 +79,9 @@ def __init__(self, android_device, configs=None):
super().__init__(android_device, configs)
self._ad = android_device
self._adb_logcat_process = None
self._adb_logcat_file_obj = None
self.adb_logcat_file_path = None
self._processor = None
self._excerpt_copier = None
self._last_connection_time = None
# Kernel boot id observed by the most recent `start()`; None until the
# service has started once (or if the id could not be read).
Expand All @@ -101,6 +100,18 @@ def _get_processor(self) -> logcat_processor.LogcatProcessor:
)
return self._processor

def _ensure_excerpt_copier(self) -> Optional[utils.IncrementalFileCopier]:
if not self.adb_logcat_file_path:
return None
if (
self._excerpt_copier is None
or self._excerpt_copier.source_path != self.adb_logcat_file_path
):
self._excerpt_copier = utils.IncrementalFileCopier(
self.adb_logcat_file_path, ignore_existing_content=True
)
return self._excerpt_copier

def _enable_logpersist(self):
"""Attempts to enable logpersist daemon to persist logs."""
# Logpersist is only allowed on rootable devices because of excessive
Expand Down Expand Up @@ -358,20 +369,12 @@ def create_output_excerpts(self, test_info):
self.OUTPUT_FILE_TYPE, test_info, 'txt'
)
excerpt_file_path = os.path.join(dest_path, filename)
with open(
excerpt_file_path,
'w',
encoding='utf-8',
errors='replace',
# When newline is '', line endings are read without conversion.
newline='',
) as out:
# Devices may accidentally go offline during test,
# check not None before copying.
if self._adb_logcat_file_obj:
# Copies from the current offset (where the previous excerpt ended)
# to EOF in large chunks instead of line-by-line in Python.
shutil.copyfileobj(self._adb_logcat_file_obj, out)
copier = self._ensure_excerpt_copier()
if copier is not None:
copier.copy_new(excerpt_file_path)
else:
with open(excerpt_file_path, 'wb'):
pass
self._ad.log.debug('logcat excerpt created at: %s', excerpt_file_path)
return [excerpt_file_path]

Expand Down Expand Up @@ -424,35 +427,15 @@ def update_config(self, new_config):
self._config = new_config
self._processor = None

def _open_logcat_file(self):
"""Creates a file object that points to the beginning of the logcat file.

Wait for the logcat file to be created by the subprocess if it doesn't
exist.
"""
if not self._adb_logcat_file_obj:
deadline = time.perf_counter() + CREATE_LOGCAT_FILE_TIMEOUT_SEC
while not os.path.exists(self.adb_logcat_file_path):
if time.perf_counter() > deadline:
raise Error(
self._ad, 'Timeout while waiting for logcat file to be created.'
)
time.sleep(1)
self._adb_logcat_file_obj = open(
self.adb_logcat_file_path, # pytype: disable=wrong-arg-types
'r',
encoding='utf-8',
errors='replace',
# When newline is '', line endings are read without conversion.
newline='',
)
self._adb_logcat_file_obj.seek(0, os.SEEK_END)

def _close_logcat_file(self):
"""Closes and resets the logcat file object, if it exists."""
if self._adb_logcat_file_obj:
self._adb_logcat_file_obj.close()
self._adb_logcat_file_obj = None
def _wait_for_logcat_file(self):
"""Waits for the logcat file to be created by the subprocess."""
deadline = time.perf_counter() + CREATE_LOGCAT_FILE_TIMEOUT_SEC
while not os.path.exists(self.adb_logcat_file_path):
if time.perf_counter() > deadline:
raise Error(
self._ad, 'Timeout while waiting for logcat file to be created.'
)
time.sleep(1)

def start(self):
"""Starts a standing adb logcat collection.
Expand Down Expand Up @@ -488,7 +471,7 @@ def start(self):
elif self._config.clear_log:
self.clear_adb_log()
self._start(dump_buffer=rebooted)
self._open_logcat_file()
self._wait_for_logcat_file()

def _start(self, dump_buffer=False):
"""Starts the actual subprocess logic of starting logcat.
Expand All @@ -499,14 +482,14 @@ def _start(self, dump_buffer=False):
"""
self._enable_logpersist()
if self._config.output_file_path:
self._close_logcat_file()
self.adb_logcat_file_path = self._config.output_file_path
if not self.adb_logcat_file_path:
f_name = self._ad.generate_filename(
self.OUTPUT_FILE_TYPE, extension_name='txt'
)
logcat_file_path = os.path.join(self._ad.log_path, f_name)
self.adb_logcat_file_path = logcat_file_path
self._ensure_excerpt_copier()
self._processor = logcat_processor.LogcatProcessor(
self.adb_logcat_file_path,
timeout_error_cls=lambda msg: LogcatTimeoutError(self._ad, msg),
Expand Down Expand Up @@ -537,7 +520,6 @@ def _start(self, dump_buffer=False):

def stop(self):
"""Stops the adb logcat service."""
self._close_logcat_file()
self._stop()

def _stop(self):
Expand Down
134 changes: 134 additions & 0 deletions mobly/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import base64
import codecs
import concurrent.futures
import datetime
import inspect
Expand All @@ -22,6 +23,7 @@
import random
import re
import shlex
import shutil
import signal
import string
import subprocess
Expand Down Expand Up @@ -721,3 +723,135 @@ def find_subclass_in_module(base_class, module):
% (base_class.__name__, [subclass.__name__ for subclass in subclasses])
)
return subclasses[0]


class IncrementalFileCopier:
"""Incrementally copies newly appended data from a growing file.

`IncrementalFileCopier` tracks a source file path and a read byte offset so
callers can repeatedly copy only the bytes appended since the previous call —
for example, splitting a continuous serial, SSH, daemon, or telemetry output
stream into per-step, per-phase, or per-test files.

No file descriptor is kept open between calls, so the copier requires no
explicit cleanup and does not interfere with external processes appending to,
rotating, or recreating the source file.

Examples:
Copy newly appended output after each step into separate files::

copier = utils.IncrementalFileCopier('/tmp/serial_console.log')
run_step_one()
copier.copy_new('/tmp/step_1_serial.log')
run_step_two()
copier.copy_new('/tmp/step_2_serial.log')

Attach to an existing file while skipping content written earlier::

copier = utils.IncrementalFileCopier(
'/var/log/daemon.log', ignore_existing_content=True
)
trigger_action()
copier.copy_new('/tmp/action_daemon.log')

Copy newly appended chunks of a binary stream without text decoding::

copier = utils.IncrementalFileCopier('/tmp/hci_snoop.bin', encoding=None)
copier.copy_new('/tmp/segment_1.bin')
"""

def __init__(
self,
source_path: str | os.PathLike[str],
ignore_existing_content: bool = False,
encoding: str | None = 'utf-8',
errors: str = 'replace',
) -> None:
"""Initializes an `IncrementalFileCopier` for `source_path`.

Args:
source_path: Path to the file to read from. The file does not need to
exist yet when the copier is created.
ignore_existing_content: If True, initializes the read offset to the
current size of `source_path` so pre-existing content is skipped. If
False, starts reading from byte 0.
encoding: Text encoding used to decode and write copied content, or None
to copy raw bytes without decoding.
errors: Error handling scheme passed to the incremental decoder when
`encoding` is set (for example, `'replace'`, `'ignore'`, or `'strict'`).
"""
self._source_path = os.fspath(source_path)
self._encoding = encoding
self._errors = errors
self._offset = self._current_size() if ignore_existing_content else 0

@property
def source_path(self) -> str:
"""Path of the source file tracked by this copier."""
return self._source_path

@property
def offset(self) -> int:
"""Current byte offset from which the next `copy_new` call will read."""
return self._offset

def _current_size(self) -> int:
try:
return os.path.getsize(self._source_path)
except OSError:
return 0

def advance_to_end(self) -> None:
"""Advances `offset` to the current end of `source_path`.

Any uncopied bytes currently in `source_path` will be skipped by subsequent
`copy_new` calls.
"""
self._offset = self._current_size()

def reset(self) -> None:
"""Resets `offset` to 0 so the next call reads from the start of the file."""
self._offset = 0

def copy_new(self, dest_path: str | os.PathLike[str]) -> int:
"""Copies content appended to `source_path` since the last call.

Parent directories of `dest_path` are created automatically. If
`source_path` does not exist yet, an empty file is created at `dest_path`.
If `source_path` was truncated or recreated smaller than `offset`, `offset`
resets to 0 before reading. When `encoding` is set, original line endings
(`\\n` and `\\r\\n`) are preserved verbatim.

Args:
dest_path: Destination file path for the newly appended data.

Returns:
The number of source bytes read from `source_path`.
"""
dest_str = os.fspath(dest_path)
parent_dir = os.path.dirname(dest_str)
if parent_dir:
create_dir(parent_dir)
if not os.path.exists(self._source_path):
with open(dest_str, 'wb'):
pass
return 0
with open(self._source_path, 'rb') as src:
if os.fstat(src.fileno()).st_size < self._offset:
self._offset = 0
start_offset = self._offset
src.seek(start_offset)
if self._encoding is None:
with open(dest_str, 'wb') as dst:
shutil.copyfileobj(src, dst)
else:
decoder = codecs.getincrementaldecoder(self._encoding)(
errors=self._errors
)
with open(dest_str, 'w', encoding=self._encoding, newline='') as dst:
while chunk := src.read(65536):
dst.write(decoder.decode(chunk, final=False))
if tail := decoder.decode(b'', final=True):
dst.write(tail)
self._offset = src.tell()
return self._offset - start_offset
Loading
Loading