blob: 6de0fbefc5e71fee3e9231392a05fcf27c23d854 [file] [edit]
#!/usr/bin/env python3
#
# Copyright (C) 2025 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
import time
import logging
import sqlite3
import threading
import subprocess
from typing import Optional, Final, List, TYPE_CHECKING
from adb import Adb, AdbError
from runnables.apply_device_configs import runnable_apply_device_configs
from runnables.prompt_device_serial import runnable_prompt_device_serial
from runnables.run_system_probe import runnable_run_system_probe
from runnables.run_workload import runnable_run_workload
from utils.inplace_updater import MultithreadedInPlaceUpdater
if TYPE_CHECKING:
from run_config import RunConfig
REBOOT_SETTLE_PERIOD_SECONDS: Final[int] = 300
class AndroidDevice:
"""A connected android device and its interactions."""
def __init__(
self,
*,
db_lock: threading.Lock,
db_connection: sqlite3.Connection,
device_name: str,
serial: str,
adb: Adb,
progress_updater: MultithreadedInPlaceUpdater,
device_index: int,
logger: logging.Logger,
) -> None:
"""Initializes the AndroidDevice object."""
self.device_name = device_name
self._serial = ""
self._environ_prepared = False
self.page_size: int = 0
self.build_fingerprint = ""
self._adb = adb
self.progress_updater = progress_updater
self.device_index = device_index
self.logger = logger
# Serial setter triggers ADBs command to fetch device details.
self.serial = serial
self.db_lock = db_lock
self.db_connection = db_connection
self._record_device_details_in_sqlite_db()
self.post_boot_logcat_log: Optional[str] = None
self.reboot_settle_period_seconds: int = REBOOT_SETTLE_PERIOD_SECONDS
self.device_progress: int = 0
self.device_progress_total: int = 0
@property
def serial(self) -> str:
"""The serial of the android device."""
return self._serial
@serial.setter
def serial(self, serial: str):
self._serial = serial
if self._serial:
self._set_page_size()
self._set_build_fingerprint()
def update_progress(
self,
message: str,
):
self.progress_updater.update(
self.device_index, f"[{self.device_name}] {message}",
self.device_progress,
self.device_progress_total,
)
self.logger.info("[%s] %s", self.device_name, message)
def _set_page_size(self) -> None:
try:
result = self.adb_command(["shell", "getconf", "PAGESIZE"])
self.page_size = int(result.stdout)
except (AdbError, ValueError):
self.page_size = 0
def _set_build_fingerprint(self) -> None:
try:
result = self.adb_command(
["shell", "getprop", "ro.build.fingerprint"])
self.build_fingerprint = result.stdout.strip()
except AdbError:
self.build_fingerprint = ""
def _record_device_details_in_sqlite_db(self):
with self.db_lock:
cursor = self.db_connection.cursor()
cursor.execute(
"""\
CREATE TABLE IF NOT EXISTS device_details (
id INTEGER PRIMARY KEY,
device_name TEXT NOT NULL,
serial TEXT,
page_size INTEGER,
build_fingerprint TEXT
)""")
cursor.execute(
"""\
INSERT INTO device_details (
device_name,
serial,
page_size,
build_fingerprint
) VALUES (?, ?, ?, ?)
""",
(
self.device_name,
self.serial,
self.page_size,
self.build_fingerprint,
))
self.db_connection.commit()
def __str__(self) -> str:
return (
"AndroidDevice(\n"
f"\tdevice_name={self.device_name},\n"
f"\tserial='{self.serial}',\n"
f"\tpage_size={self.page_size}, \n"
f"\tbuild_fingerprint={self.build_fingerprint}, \n"
f")"
)
def adb_command(
self,
command: List[str],
**kwargs,
) -> subprocess.CompletedProcess:
"""Runs an adb command for this device."""
return self._adb.adb_command(command, device=self, **kwargs)
def fastboot_command(
self,
command: List[str],
**kwargs,
) -> subprocess.CompletedProcess:
"""Runs a fastboot command."""
return self._adb.fastboot_command(command, self, **kwargs)
def root(self) -> None:
"""Restart adbd with root permissions for this device."""
self._adb.root(self)
def get_state(self) -> str:
"""Gets the device state."""
return self._adb.get_state(self)
def wait_for_device(self, timeout: int = 300) -> None:
"""Waits for the device to be available."""
self._adb.wait_for_device(self, timeout=timeout)
def reboot(self) -> None:
"""Reboots the device."""
self.adb_command(["reboot"], check=False)
self.adb_command(["wait-for-device"], check=False)
def record_logcat_logs(self) -> None:
"""Records logcat logs."""
self.root()
self.post_boot_logcat_log = self.adb_command(
["shell", "logcat", "-b", "kernel", "-d"], check=False,
).stdout
def fetch_and_store_memory_data(self, run_config: RunConfig) -> None:
"""Runs specified workloads, system probes to generate results."""
from runnables.runnable_data import RunnableData # pylint: disable=import-outside-toplevel
runnable_data = RunnableData()
runnable_data.android_device = self
runnable_data.run_config = run_config
runnable_prompt_device_serial.process(runnable_data)
runnable_apply_device_configs.process(runnable_data)
self.device_progress = 0
num_reboots = runnable_data.run_config_not_null.num_reboots
num_samples = (
runnable_data.run_config_not_null.runs_per_workload)
num_workloads = len(
runnable_data.run_config_not_null.workloads)
num_system_probes = len(runnable_data.run_config_not_null.system_probes)
# For R reboots, take S samples, across W workloads, across SP
# system probes. We want each reboot, sample, and workload to count
# toward progress and thus we need to calculate the number of those
# as well.
# Total Progress = R + S + W + SP
# reboot
# └─ sample
# └─ workload
# └─ system probe
sp_progress = (
num_reboots * num_samples * num_workloads * num_system_probes)
w_progress = num_reboots * num_samples * num_workloads
s_progress = num_reboots * num_samples
r_progress = num_reboots
self.device_progress_total = (
sp_progress + w_progress + s_progress + r_progress)
self.update_progress(
"Starting analysis",
)
for reboot_count in range(1, num_reboots+1):
self.update_progress(
"Preparing for analysis by rebooting the device. "
f"Reboot {reboot_count} of {num_reboots}.",
)
self.reboot()
self.device_progress += 1 # R (reboot) progress
self.record_logcat_logs()
self.update_progress(
"Reboot complete. Waiting for device to "
f"settle ({self.reboot_settle_period_seconds}s).",
)
time.sleep(self.reboot_settle_period_seconds)
runnable_data.reboot_count = reboot_count
# Ensure ADB has root after reboot.
while True:
try:
self.root()
break
except AdbError as e:
self.logger.error(f"Failed to set root after reboot: {e}")
# pylint: disable=bad-builtin
input(
"Please check device connection and "
"press Enter to retry..."
)
for workload in runnable_data.run_config_not_null.workloads:
for probe_sample_count in range(1, num_samples+1):
self.device_progress += 1 # S (sample) progress
runnable_data.workload = workload
runnable_data.probe_sample_count = probe_sample_count
# Run workload.
self.update_progress(
f"Running {workload.name}",
)
runnable_run_workload.process(runnable_data)
self.device_progress += 1 # W (workload) progress
# Run system probes.
self.update_progress(
f"{workload.name} complete. Gathering memory "
f"data across {num_system_probes} system probes."
)
runnable_run_system_probe.process(runnable_data)
# SP (system probe) progress
self.device_progress += num_system_probes
# Post process (typically just close the app).
runnable_run_workload.post_process(runnable_data)
# end for _
# end for workload
# end for reboot_count
self.device_progress = self.device_progress_total
self.update_progress("Done.")