Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: ftrace support #130

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 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
39 changes: 28 additions & 11 deletions benchkit/adb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,34 @@ class AndroidDebugBridge: # TODO add commlayer for "host"

def __init__(
self,
ip_addr: str,
port: int = 5555,
identifier: str,
# ip_addr: str,
# port: int = 5555,
keep_connected: bool = False,
wait_connected: bool = False,
expected_os: Optional[str] = None,
) -> None:
self._ip = ip_addr
self._port = port
self.identifier = identifier
# self._ip = ip_addr
# self._port = port
self._keep_connected = keep_connected
self._wait_connected = wait_connected
self._expected_os = expected_os

@staticmethod
def from_device(
device: ADBDevice,
keep_connected: bool = False,
wait_connected: bool = False,
expected_os: Optional[str] = None,
) -> "AndroidDebugBridge":
return AndroidDebugBridge(
identifier=device.identifier,
keep_connected=keep_connected,
wait_connected=wait_connected,
expected_os=expected_os,
)

def __enter__(self) -> "AndroidDebugBridge":
if not self.is_connected():
self._connect_daemon()
Expand All @@ -74,14 +90,15 @@ def __exit__(self, exc_type, exc_value, exc_tb) -> None:
if not self._keep_connected and self.is_connected():
self._disconnect()

@property
def identifier(self) -> str:
"""Get adb identifier of current device.
# TODO: this may or may not be enabled again, right now I don't see an easy way to connect to non-ip devices?
# @property
# def identifier(self) -> str:
# """Get adb identifier of current device.

Returns:
str: adb identifier of current device.
"""
return _identifier_from(ip_addr=self._ip, port=self._port)
# Returns:
# str: adb identifier of current device.
# """
# return _identifier_from(ip_addr=self._ip, port=self._port)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why can't this just return self.identifier?


def is_connected(self) -> bool:
"""Returns whether the device is connected to adb.
Expand Down
1 change: 1 addition & 0 deletions tests/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tmp/
144 changes: 144 additions & 0 deletions tests/test_android_ftrace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""
Module to test reading ftrace from android devices
"""

import time

from typing import List, Mapping
from benchkit.adb import AndroidDebugBridge


TRACE_BUFFER_SIZE_KB: int = 96000
DEVICE_DUMP_PATH: str = "/sdcard/tmp/ftrace_dump"
HOST_DUMP_PATH: str = "./tests/tmp/ftrace_dump"
EXAMPLE_WEBSITE: str = "https://github.com/open-s4c/benchkit"
HOST_SLEEP_TIME: float = 5


def enable_tracing(bridge: AndroidDebugBridge) -> None:
# per category tracing
bridge.shell_out("echo 1 > /sys/kernel/tracing/events/irq/enable")
# per event tracing
bridge.shell_out("echo 1 > /sys/kernel/tracing/events/sched/sched_wakeup/enable")


def disable_tracing(bridge: AndroidDebugBridge) -> None:
bridge.shell_out("echo 0 > /sys/kernel/tracing/events/irq/enable")
bridge.shell_out("echo 0 > /sys/kernel/tracing/events/sched/sched_wakeup/enable")


def start_tracing(bridge: AndroidDebugBridge) -> None:
bridge.shell_out("echo 1 > /sys/kernel/tracing/tracing_on")


def stop_tracing(bridge: AndroidDebugBridge) -> None:
bridge.shell_out("echo 0 > /sys/kernel/tracing/tracing_on")


def dump_trace(bridge: AndroidDebugBridge, output: str) -> None:
bridge.shell_out(f"rm {output} || true") # delete file or ignore rm if fails (file not exists)
bridge.shell_out(f"cat /sys/kernel/tracing/trace > {output}")


def clear_trace_buffer(bridge: AndroidDebugBridge) -> None:
bridge.shell_out("cat /dev/null > /sys/kernel/tracing/trace")


def set_trace_buffer_size(bridge: AndroidDebugBridge, size_kb: int) -> None:
bridge.shell_out(f"echo {size_kb} > /sys/kernel/tracing/buffer_size_kb")


def open_website(bridge: AndroidDebugBridge, url: str) -> None:
bridge.shell_out(f"am start -a android.intent.action.VIEW -d \"{url}\" com.android.chrome")


def collect_spans(file: str) -> List[Mapping]:
events = []
event_stack = []

# TODO: fix this parsing, it seems to be incorrect
with open(file, "r") as f:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be able to use the perfetto trace processor. https://perfetto.dev/docs/analysis/trace-processor-python
Did you try it out already and ran into issues?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no i did not, but this looks like a very promising idea, I'll try it out.

for line in f:
if "tracing_mark_write" in line:
line = line.strip()
parts = line.split('tracing_mark_write:')
timestamp: float
if len(parts) == 2:
header, content = parts
# Extract timestamp
header_parts = header.strip().split()
if len(header_parts) >= 1:
timestamp_str = header_parts[-1].rstrip(':')
try:
timestamp = float(timestamp_str)
except ValueError:
# Skip lines with invalid timestamp
continue
content = content.strip()
if content.startswith('B|'):
# Begin event
parts = content.split('|', 2)
if len(parts) == 3:
_, pid, event_name = parts
event = {'name': event_name, 'start_time': timestamp, 'pid': pid}
event_stack.append(event)
else:
# Invalid format, skip
continue
elif content.startswith('E'):
# End event
if event_stack:
event = event_stack.pop()
event_name = event['name']
start_time = event['start_time']
pid = event.get('pid', '')
duration = timestamp - start_time
event['end_time'] = timestamp
event['duration'] = duration
events.append(event)
else:
# No matching begin event
continue
else:
# Instant event or other data
event = {'timestamp': timestamp, 'content': content}
events.append(event)
else:
# Invalid header format
continue

return events


def main() -> None:
device = AndroidDebugBridge._devices()[0]
bridge = AndroidDebugBridge.from_device(device)

enable_tracing(bridge)
set_trace_buffer_size(bridge, TRACE_BUFFER_SIZE_KB)
clear_trace_buffer(bridge)
start_tracing(bridge)

# demo code
bridge.screen_tap(50, 50)
open_website(bridge, EXAMPLE_WEBSITE)
time.sleep(2)
bridge.push_button_home()

time.sleep(HOST_SLEEP_TIME)

stop_tracing(bridge)
disable_tracing(bridge)
dump_trace(bridge, DEVICE_DUMP_PATH)

bridge.pull(DEVICE_DUMP_PATH, HOST_DUMP_PATH)

events = collect_spans(HOST_DUMP_PATH)
for event in events:
print(event)


if __name__ == "__main__":
main()