Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(169)

Side by Side Diff: build/android/chrome_profiler/controllers.py

Issue 290013006: adb_profile_chrome: Refactor into multiple modules and add tests (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 6 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 import json
6 import os
7 import re
8 import threading
9 import time
10 import zlib
11
12 from chrome_profiler import util
13
14 from pylib import cmd_helper
15 from pylib import pexpect
16
17
18 class ChromeTracingController(object):
19 def __init__(self, device, package_info, categories, ring_buffer):
20 self._device = device
21 self._package_info = package_info
22 self._categories = categories
23 self._ring_buffer = ring_buffer
24 self._trace_file = None
25 self._trace_interval = None
26 self._trace_start_re = \
27 re.compile(r'Logging performance trace to file')
28 self._trace_finish_re = \
29 re.compile(r'Profiler finished[.] Results are in (.*)[.]')
30 self._device.old_interface.StartMonitoringLogcat(clear=False)
31
32 def __repr__(self):
33 return 'chrome trace'
34
35 @staticmethod
36 def GetCategories(device, package_info):
37 device.old_interface.BroadcastIntent(
38 package_info.package, 'GPU_PROFILER_LIST_CATEGORIES')
39 try:
40 json_category_list = device.old_interface.WaitForLogMatch(
41 re.compile(r'{"traceCategoriesList(.*)'), None, timeout=5).group(0)
42 except pexpect.TIMEOUT:
43 raise RuntimeError('Performance trace category list marker not found. '
44 'Is the correct version of the browser running?')
45
46 record_categories = []
47 disabled_by_default_categories = []
48 json_data = json.loads(json_category_list)['traceCategoriesList']
49 for item in json_data:
50 if item.startswith('disabled-by-default'):
51 disabled_by_default_categories.append(item)
52 else:
53 record_categories.append(item)
54
55 return record_categories, disabled_by_default_categories
56
57 def StartTracing(self, interval):
58 self._trace_interval = interval
59 self._device.old_interface.SyncLogCat()
60 self._device.old_interface.BroadcastIntent(
61 self._package_info.package, 'GPU_PROFILER_START',
62 '-e categories "%s"' % ','.join(self._categories),
63 '-e continuous' if self._ring_buffer else '')
64 # Chrome logs two different messages related to tracing:
65 #
66 # 1. "Logging performance trace to file"
67 # 2. "Profiler finished. Results are in [...]"
68 #
69 # The first one is printed when tracing starts and the second one indicates
70 # that the trace file is ready to be pulled.
71 try:
72 self._device.old_interface.WaitForLogMatch(
73 self._trace_start_re, None, timeout=5)
74 except pexpect.TIMEOUT:
75 raise RuntimeError('Trace start marker not found. Is the correct version '
76 'of the browser running?')
77
78 def StopTracing(self):
79 self._device.old_interface.BroadcastIntent(
80 self._package_info.package,
81 'GPU_PROFILER_STOP')
82 self._trace_file = self._device.old_interface.WaitForLogMatch(
83 self._trace_finish_re, None, timeout=120).group(1)
84
85 def PullTrace(self):
86 # Wait a bit for the browser to finish writing the trace file.
87 time.sleep(self._trace_interval / 4 + 1)
88
89 trace_file = self._trace_file.replace('/storage/emulated/0/', '/sdcard/')
90 host_file = os.path.join(os.path.curdir, os.path.basename(trace_file))
91 self._device.old_interface.PullFileFromDevice(trace_file, host_file)
92 return host_file
93
94
95 _SYSTRACE_OPTIONS = [
96 # Compress the trace before sending it over USB.
97 '-z',
98 # Use a large trace buffer to increase the polling interval.
99 '-b', '16384'
100 ]
101
102 # Interval in seconds for sampling systrace data.
103 _SYSTRACE_INTERVAL = 15
104
105
106 class SystraceController(object):
107 def __init__(self, device, categories, ring_buffer):
108 self._device = device
109 self._categories = categories
110 self._ring_buffer = ring_buffer
111 self._done = threading.Event()
112 self._thread = None
113 self._trace_data = None
114
115 def __repr__(self):
116 return 'systrace'
117
118 @staticmethod
119 def GetCategories(device):
120 return device.old_interface.RunShellCommand('atrace --list_categories')
121
122 def StartTracing(self, _):
123 self._thread = threading.Thread(target=self._CollectData)
124 self._thread.start()
125
126 def StopTracing(self):
127 self._done.set()
128
129 def PullTrace(self):
130 self._thread.join()
131 self._thread = None
132 if self._trace_data:
133 output_name = 'systrace-%s' % util.GetTraceTimestamp()
134 with open(output_name, 'w') as out:
135 out.write(self._trace_data)
136 return output_name
137
138 def _RunATraceCommand(self, command):
139 # TODO(jbudorick) can this be made work with DeviceUtils?
140 # We use a separate interface to adb because the one from AndroidCommands
141 # isn't re-entrant.
142 device_param = (['-s', self._device.old_interface.GetDevice()]
143 if self._device.old_interface.GetDevice() else [])
144 cmd = ['adb'] + device_param + ['shell', 'atrace', '--%s' % command] + \
145 _SYSTRACE_OPTIONS + self._categories
146 return cmd_helper.GetCmdOutput(cmd)
147
148 def _CollectData(self):
149 trace_data = []
150 self._RunATraceCommand('async_start')
151 try:
152 while not self._done.is_set():
153 self._done.wait(_SYSTRACE_INTERVAL)
154 if not self._ring_buffer or self._done.is_set():
155 trace_data.append(
156 self._DecodeTraceData(self._RunATraceCommand('async_dump')))
157 finally:
158 trace_data.append(
159 self._DecodeTraceData(self._RunATraceCommand('async_stop')))
160 self._trace_data = ''.join([zlib.decompress(d) for d in trace_data])
161
162 @staticmethod
163 def _DecodeTraceData(trace_data):
164 try:
165 trace_start = trace_data.index('TRACE:')
166 except ValueError:
167 raise RuntimeError('Systrace start marker not found')
168 trace_data = trace_data[trace_start + 6:]
169
170 # Collapse CRLFs that are added by adb shell.
171 if trace_data.startswith('\r\n'):
172 trace_data = trace_data.replace('\r\n', '\n')
173
174 # Skip the initial newline.
175 return trace_data[1:]
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698