| #!/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. | |
| # | |
| import argparse | |
| import datetime | |
| import logging | |
| import os | |
| import time | |
| import sys | |
| from concurrent.futures import ThreadPoolExecutor | |
| from typing import Dict | |
| from android_device import AndroidDevice | |
| from adb import Adb | |
| from run_config import get_run_config_unlocked | |
| from utils.inplace_updater import MultithreadedInPlaceUpdater | |
| from runnables.apply_device_configs.device_configs import ( | |
| AVAILABLE_DEVICE_CONFIGS) | |
| from runnables.run_system_probe.available_system_probes import ( | |
| AVAILABLE_SYSTEM_PROBES) | |
| from runnables.run_workload.workloads.available_workloads import ( | |
| AVAILABLE_WORKLOADS) | |
| from utils.utils import make_and_write_file | |
| from utils.utils_results import write_all_results, write_device_details_file | |
| def _arg_key_value(devices: str) -> Dict[str, str]: | |
| devices_dict = {} | |
| for device in devices.split(","): | |
| try: | |
| key, value = device.split("/") | |
| except ValueError as e: | |
| raise argparse.ArgumentTypeError( | |
| f"Invalid --devices argument: '{device}'. " | |
| "Expected format --devices=d1name/d1serial," | |
| f"d2name/d2serial. Error: {e}" | |
| ) from e | |
| devices_dict[key] = value | |
| return devices_dict | |
| def _get_parsed_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description=( | |
| "A simple script to demonstrate argparse. Reads and displays " | |
| "lines from a file." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--skip-device-configs", | |
| action="store_true", | |
| help=( | |
| "Skip applying device configs. Only recommended for active " | |
| "development of amemdiff." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--single-device-mode", | |
| action="store_true", | |
| help=( | |
| "The second device serial will be prompted for, allowing for " | |
| "the program to pause before continuing." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "-dc", "--device-configs", | |
| type=lambda s: s.split(","), | |
| required=False, | |
| help=( | |
| "Comma separated list of chosen device configs. Uses " | |
| "all by default. Available device configs: " + | |
| # pylint: disable=consider-iterating-dictionary | |
| ", ".join(dc for dc in AVAILABLE_DEVICE_CONFIGS.keys()) | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--disable-device-configs", | |
| type=lambda s: s.split(","), | |
| required=False, | |
| help=( | |
| "Comma separated list of device configs to disable. E.g., " | |
| "--disable-device-configs=StayAwakeEnabled" | |
| ), | |
| ) | |
| parser.add_argument( | |
| "-wl", "--workloads", | |
| type=lambda s: s.split(","), | |
| required=False, | |
| help=( | |
| "Comma separated list of chosen workloads. Uses " | |
| "SteadyStateWorkload by default. Available workloads: " + | |
| # pylint: disable=consider-iterating-dictionary | |
| ", ".join(dc for dc in AVAILABLE_WORKLOADS.keys()) | |
| ), | |
| ) | |
| parser.add_argument( | |
| "-sp", "--system-probes", | |
| type=lambda s: s.split(","), | |
| required=False, | |
| help=( | |
| "Comma separated list of chosen system probes. Uses " | |
| "all by default. Available system probes: " + | |
| # pylint: disable=consider-iterating-dictionary | |
| ", ".join(dc for dc in AVAILABLE_SYSTEM_PROBES.keys()) | |
| ), | |
| ) | |
| parser.add_argument( | |
| "-d", "--devices", | |
| type=_arg_key_value, | |
| required=True, | |
| help=( | |
| "Comma separated key/value pair of adb devices. The " | |
| "key will be used as the device name and the value " | |
| "will be used as the ADB socket addresses. E.g., " | |
| "`-d=4kb/localhost:12345,16kb/localhost:54321`." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "-nd", "--number-of-devices", | |
| type=int, | |
| required=False, | |
| default=2, | |
| help="The number of devices to run analysis across.", | |
| ) | |
| parser.add_argument( | |
| "-n", "--runs-per-workload", | |
| type=int, | |
| required=False, | |
| default=4, | |
| help="N runs for each device for each workload.", | |
| ) | |
| parser.add_argument( | |
| "-nr", "--num-reboots", | |
| type=int, | |
| required=False, | |
| default=5, | |
| help="N reboots per device. Workloads will run after each reboot.", | |
| ) | |
| parser.add_argument( | |
| "-o", "--output-directory", | |
| type=str, | |
| required=False, | |
| default="data_out", | |
| help="The output directory to store results within.", | |
| ) | |
| parser.add_argument( | |
| "--showmap-process-name", | |
| type=str, | |
| required=False, | |
| default="system_server", | |
| help=( | |
| "Process names with which showmap should fetch memory " | |
| "details for. Uses system_server if not available." | |
| ), | |
| ) | |
| return parser.parse_args() | |
| def _print_execution_time( | |
| start_time: float, | |
| progress_updater: MultithreadedInPlaceUpdater, | |
| ) -> None: | |
| end_time = time.time() | |
| elapsed_time = end_time - start_time | |
| if elapsed_time >= 60: | |
| minutes = elapsed_time / 60 | |
| progress_updater.update( | |
| 0, f"Done. Total execution time: {minutes:.2f} minutes." | |
| ) | |
| else: | |
| progress_updater.update( | |
| 0, f"Done. Total execution time: {elapsed_time:.2f} seconds." | |
| ) | |
| def _set_up_logger(output_directory: str) -> logging.Logger: | |
| # Configure logging | |
| log_file = os.path.join(output_directory, "amemdiff.log") | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s [%(levelname)s] %(message)s", | |
| handlers=[ | |
| logging.FileHandler(log_file), | |
| ] | |
| ) | |
| return logging.getLogger("amemdiff") | |
| def main(args: argparse.Namespace): | |
| """Main entrypoint to amemdiff.""" | |
| start_time = time.time() | |
| # Init Android devices. | |
| if len(args.devices) != 2: | |
| sys.exit( | |
| f"{len(args.devices)} device(s) found. Please specify " | |
| "two devices. E.g., -d=firstDevice/0.0.0.0:1234," | |
| "secondDevice/0.0.0.0:1234." | |
| ) | |
| output_directory = os.path.join( | |
| args.output_directory, | |
| datetime.datetime.now().strftime("%Y%m%d_%H%M%S") | |
| ) | |
| os.makedirs(output_directory, exist_ok=True) | |
| logger = _set_up_logger(output_directory) | |
| logger.info("Starting amemdiff analysis...") | |
| # Process device configs, allowing for configs to be disabled. | |
| if args.disable_device_configs: | |
| to_disable = set(args.disable_device_configs) | |
| enabled_configs = args.device_configs | |
| if not enabled_configs: | |
| enabled_configs = list(AVAILABLE_DEVICE_CONFIGS.keys()) | |
| args.device_configs = [ | |
| c for c in enabled_configs if c not in to_disable | |
| ] | |
| # Fetch the run configuration. | |
| run_config = get_run_config_unlocked(args) | |
| # Initialize progress updater | |
| progress_updater = MultithreadedInPlaceUpdater(total_threads=len(args.devices) + 1) | |
| progress_updater.update(0, f"Starting analysis for {len(args.devices)} devices...") | |
| android_devices = [] | |
| adb = Adb() | |
| for i, (device_name, serial) in enumerate(args.devices.items()): | |
| android_devices.append( | |
| AndroidDevice( | |
| db_lock=run_config.db_lock, | |
| db_connection=run_config.database_connection, | |
| device_name=device_name, | |
| serial=serial, | |
| adb=adb, | |
| progress_updater=progress_updater, | |
| device_index=i + 1, | |
| logger=logger, | |
| ) | |
| ) | |
| if args.single_device_mode and len(android_devices) > 1: | |
| android_devices[1].serial = "" | |
| # Run analysis. | |
| if args.single_device_mode: | |
| for device in android_devices: | |
| device.fetch_and_store_memory_data(run_config) | |
| else: | |
| with ThreadPoolExecutor(max_workers=len(android_devices)) as executor: | |
| futures = [ | |
| executor.submit(device.fetch_and_store_memory_data, run_config) | |
| for device in android_devices | |
| ] | |
| for future in futures: | |
| future.result() | |
| # Write results. | |
| logger.info("Writing result files...") | |
| make_and_write_file( | |
| output_directory, | |
| "run_config.txt", | |
| str(run_config), | |
| ) | |
| write_all_results( | |
| output_directory=output_directory, | |
| database_connection=run_config.database_connection, | |
| db_lock=run_config.db_lock, | |
| ) | |
| write_device_details_file( | |
| output_directory=output_directory, | |
| database_connection=run_config.database_connection, | |
| db_lock=run_config.db_lock, | |
| ) | |
| _print_execution_time(start_time, progress_updater) | |
| run_config.database_connection.close() | |
| logging.shutdown() | |
| if __name__ == "__main__": | |
| parsed_args = _get_parsed_args() | |
| main(parsed_args) |