blob: c0693abdcc033a1ceb09a1e090ad9b2414ef3c7c [file] [log] [blame]
Yasuhiro Matsudaab379832015-07-03 02:08:55 +09001#!/usr/bin/env python
2# Copyright (C) 2015 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Record the event logs during boot and output them to a file.
16
17This script repeats the record of each event log during Android boot specified
18times. By default, interval between measurements is adjusted in such a way that
19CPUs are cooled down sufficiently to avoid boot time slowdown caused by CPU
20thermal throttling. The result is output in a tab-separated value format.
21
22Examples:
23
24Repeat measurements 10 times. Interval between iterations is adjusted based on
25CPU temperature of the device.
26
27$ ./perfboot.py --iterations=10
28
29Repeat measurements 20 times. 60 seconds interval is taken between each
30iteration.
31
32$ ./perfboot.py --iterations=20 --interval=60
33
34Repeat measurements 20 times, show verbose output, output the result to
35data.tsv, and read event tags from eventtags.txt.
36
37$ ./perfboot.py --iterations=30 -v --output=data.tsv --tags=eventtags.txt
38"""
39
40import argparse
41import atexit
42import cStringIO
43import inspect
44import logging
45import math
46import os
47import re
48import subprocess
49import sys
50import threading
51import time
52
53sys.path.append(os.path.dirname(os.path.dirname(__file__)))
54import adb
55
56# The default event tags to record.
57_DEFAULT_EVENT_TAGS = [
58 'boot_progress_start',
59 'boot_progress_preload_start',
60 'boot_progress_preload_end',
61 'boot_progress_system_run',
62 'boot_progress_pms_start',
63 'boot_progress_pms_system_scan_start',
64 'boot_progress_pms_data_scan_start',
65 'boot_progress_pms_scan_end',
66 'boot_progress_pms_ready',
67 'boot_progress_ams_ready',
68 'boot_progress_enable_screen',
69]
70
71
72class IntervalAdjuster(object):
73 """A helper class to take suffficient interval between iterations."""
74
75 # CPU temperature values per product used to decide interval
76 _CPU_COOL_DOWN_THRESHOLDS = {
77 'flo': 40,
78 'flounder': 40000,
79 'razor': 40,
80 'volantis': 40000,
81 }
82 # The interval between CPU temperature checks
83 _CPU_COOL_DOWN_WAIT_INTERVAL = 10
84 # The wait time used when the value of _CPU_COOL_DOWN_THRESHOLDS for
85 # the product is not defined.
86 _CPU_COOL_DOWN_WAIT_TIME_DEFAULT = 120
87
88 def __init__(self, interval, device):
89 self._interval = interval
90 self._device = device
91 self._temp_paths = device.shell(
92 ['ls', '/sys/class/thermal/thermal_zone*/temp']).splitlines()
93 self._product = device.get_prop('ro.build.product')
94 self._waited = False
95
96 def wait(self):
97 """Waits certain amount of time for CPUs cool-down."""
98 if self._interval is None:
99 self._wait_cpu_cool_down(self._product, self._temp_paths)
100 else:
101 if self._waited:
102 print 'Waiting for %d seconds' % self._interval
103 time.sleep(self._interval)
104 self._waited = True
105
106 def _get_cpu_temp(self, threshold):
107 max_temp = 0
108 for temp_path in self._temp_paths:
109 temp = int(self._device.shell(['cat', temp_path]).rstrip())
110 max_temp = max(max_temp, temp)
111 if temp >= threshold:
112 return temp
113 return max_temp
114
115 def _wait_cpu_cool_down(self, product, temp_paths):
116 threshold = IntervalAdjuster._CPU_COOL_DOWN_THRESHOLDS.get(
117 self._product)
118 if threshold is None:
119 print 'No CPU temperature threshold is set for ' + self._product
120 print ('Just wait %d seconds' %
121 IntervalAdjuster._CPU_COOL_DOWN_WAIT_TIME_DEFAULT)
122 time.sleep(IntervalAdjuster._CPU_COOL_DOWN_WAIT_TIME_DEFAULT)
123 return
124 while True:
125 temp = self._get_cpu_temp(threshold)
126 if temp < threshold:
127 logging.info('Current CPU temperature %s' % temp)
128 return
129 print 'Waiting until CPU temperature (%d) falls below %d' % (
130 temp, threshold)
131 time.sleep(IntervalAdjuster._CPU_COOL_DOWN_WAIT_INTERVAL)
132
133
134class WatchdogTimer(object):
135 """A timer that makes is_timedout() return true in |timeout| seconds."""
136 def __init__(self, timeout):
137 self._timedout = False
138
139 def notify_timeout():
140 self._timedout = True
141 self._timer = threading.Timer(timeout, notify_timeout)
Yasuhiro Matsuda59d32a72015-08-04 17:48:41 +0900142 self._timer.daemon = True
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900143 self._timer.start()
144
145 def is_timedout(self):
146 return self._timedout
147
148 def cancel(self):
149 self._timer.cancel()
150
151
152def readlines_unbuffered(proc):
153 """Read lines from |proc|'s standard out without buffering."""
154 while True:
155 buf = []
156 c = proc.stdout.read(1)
157 if c == '' and proc.poll() is not None:
158 break
159 while c != '\n':
160 if c == '' and proc.poll() is not None:
161 break
162 buf.append(c)
163 c = proc.stdout.read(1)
164 yield ''.join(buf)
165
166
167def disable_dropbox(device):
168 """Removes the files created by Dropbox and avoids creating the files."""
169 device.root()
170 device.wait()
171 device.shell(['rm', '-rf', '/system/data/dropbox'])
172 original_dropbox_max_files = device.shell(
173 ['settings', 'get', 'global', 'dropbox_max_files']).rstrip()
174 device.shell(['settings', 'put', 'global', 'dropbox_max_files', '0'])
175 return original_dropbox_max_files
176
177
178def restore_dropbox(device, original_dropbox_max_files):
179 """Restores the dropbox_max_files setting."""
180 device.root()
181 device.wait()
182 if original_dropbox_max_files == 'null':
183 device.shell(['settings', 'delete', 'global', 'dropbox_max_files'])
184 else:
185 device.shell(['settings', 'put', 'global', 'dropbox_max_files',
186 original_dropbox_max_files])
187
188
189def init_perf(device, output, record_list, tags):
190 device.wait()
191 build_type = device.get_prop('ro.build.type')
192 original_dropbox_max_files = None
193 if build_type != 'user':
194 # Workaround for Dropbox issue (http://b/20890386).
195 original_dropbox_max_files = disable_dropbox(device)
196
197 def cleanup():
198 try:
199 if record_list:
200 print_summary(record_list, tags[-1])
201 output_results(output, record_list, tags)
202 if original_dropbox_max_files is not None:
203 restore_dropbox(device, original_dropbox_max_files)
204 except subprocess.CalledProcessError, RuntimeError:
205 pass
206 atexit.register(cleanup)
207
208
209def read_event_tags(tags_file):
210 """Reads event tags from |tags_file|."""
211 if not tags_file:
212 return _DEFAULT_EVENT_TAGS
213 tags = []
214 with open(tags_file) as f:
215 for line in f:
216 if '#' in line:
217 line = line[:line.find('#')]
218 line = line.strip()
219 if line:
220 tags.append(line)
221 return tags
222
223
224def make_event_tags_re(tags):
225 """Makes a regular expression object that matches event logs of |tags|."""
226 return re.compile(r'(?P<pid>[0-9]+) +[0-9]+ I (?P<tag>%s): (?P<time>\d+)' %
227 '|'.join(tags))
228
229
230def get_values(record, tag):
231 """Gets values that matches |tag| from |record|."""
232 keys = [key for key in record.keys() if key[0] == tag]
233 return [record[k] for k in sorted(keys)]
234
235
236def get_last_value(record, tag):
237 """Gets the last value that matches |tag| from |record|."""
238 values = get_values(record, tag)
239 if not values:
240 return 0
241 return values[-1]
242
243
244def output_results(filename, record_list, tags):
245 """Outputs |record_list| into |filename| in a TSV format."""
246 # First, count the number of the values of each tag.
247 # This is for dealing with events that occur multiple times.
248 # For instance, boot_progress_preload_start and boot_progress_preload_end
249 # are recorded twice on 64-bit system. One is for 64-bit zygote process
250 # and the other is for 32-bit zygote process.
251 values_counter = {}
252 for record in record_list:
253 for tag in tags:
254 # Some record might lack values for some tags due to unanticipated
255 # problems (e.g. timeout), so take the maximum count among all the
256 # record.
257 values_counter[tag] = max(values_counter.get(tag, 1),
258 len(get_values(record, tag)))
259
260 # Then creates labels for the data. If there are multiple values for one
261 # tag, labels for these values are numbered except the first one as
262 # follows:
263 #
264 # event_tag event_tag2 event_tag3
265 #
266 # The corresponding values are sorted in an ascending order of PID.
267 labels = []
268 for tag in tags:
269 for i in range(1, values_counter[tag] + 1):
270 labels.append('%s%s' % (tag, '' if i == 1 else str(i)))
271
272 # Finally write the data into the file.
273 with open(filename, 'w') as f:
274 f.write('\t'.join(labels) + '\n')
275 for record in record_list:
276 line = cStringIO.StringIO()
277 invalid_line = False
278 for i, tag in enumerate(tags):
279 if i != 0:
280 line.write('\t')
281 values = get_values(record, tag)
282 if len(values) < values_counter[tag]:
283 invalid_line = True
284 # Fill invalid record with 0
285 values += [0] * (values_counter[tag] - len(values))
286 line.write('\t'.join(str(t) for t in values))
287 if invalid_line:
288 logging.error('Invalid record found: ' + line.getvalue())
289 line.write('\n')
290 f.write(line.getvalue())
291 print 'Wrote: ' + filename
292
293
294def median(data):
295 """Calculates the median value from |data|."""
296 data = sorted(data)
297 n = len(data)
298 if n % 2 == 1:
299 return data[n / 2]
300 else:
301 n2 = n / 2
302 return (data[n2 - 1] + data[n2]) / 2.0
303
304
305def mean(data):
306 """Calculates the mean value from |data|."""
307 return float(sum(data)) / len(data)
308
309
310def stddev(data):
311 """Calculates the standard deviation value from |value|."""
312 m = mean(data)
313 return math.sqrt(sum((x - m) ** 2 for x in data) / len(data))
314
315
316def print_summary(record_list, end_tag):
317 """Prints the summary of |record_list|."""
318 # Filter out invalid data.
319 end_times = [get_last_value(record, end_tag) for record in record_list
320 if get_last_value(record, end_tag) != 0]
321 print 'mean: ', mean(end_times)
322 print 'median:', median(end_times)
323 print 'standard deviation:', stddev(end_times)
324
325
326def do_iteration(device, interval_adjuster, event_tags_re, end_tag):
327 """Measures the boot time once."""
328 device.wait()
329 interval_adjuster.wait()
330 device.reboot()
331 print 'Rebooted the device'
332 record = {}
333 booted = False
334 while not booted:
335 device.wait()
336 # Stop the iteration if it does not finish within 120 seconds.
337 timeout = 120
338 t = WatchdogTimer(timeout)
339 p = subprocess.Popen(
340 ['adb', 'logcat', '-b', 'events', '-v', 'threadtime'],
341 stdout=subprocess.PIPE)
342 for line in readlines_unbuffered(p):
343 if t.is_timedout():
344 print '*** Timed out ***'
345 return record
346 m = event_tags_re.search(line)
347 if not m:
348 continue
349 tag = m.group('tag')
350 event_time = int(m.group('time'))
351 pid = m.group('pid')
352 record[(tag, pid)] = event_time
353 print 'Event log recorded: %s (%s) - %d ms' % (
354 tag, pid, event_time)
355 if tag == end_tag:
356 booted = True
357 t.cancel()
358 break
359 return record
360
361
362def parse_args():
363 """Parses the command line arguments."""
364 parser = argparse.ArgumentParser(
365 description=inspect.getdoc(sys.modules[__name__]),
366 formatter_class=argparse.RawDescriptionHelpFormatter)
367 parser.add_argument('--iterations', type=int, default=5,
368 help='Number of times to repeat boot measurements.')
369 parser.add_argument('--interval', type=int,
370 help=('Duration between iterations. If this is not '
371 'set explicitly, durations are determined '
372 'adaptively based on CPUs temperature.'))
373 parser.add_argument('-o', '--output', help='File name of output data.')
374 parser.add_argument('-v', '--verbose', action='store_true',
375 help='Show verbose output.')
376 parser.add_argument('-s', '--serial', default=os.getenv('ANDROID_SERIAL'),
377 help='Adb device serial number.')
378 parser.add_argument('-t', '--tags', help='Specify the filename from which '
379 'event tags are read. Every line contains one event '
380 'tag and the last event tag is used to detect that '
381 'the device has finished booting.')
382 return parser.parse_args()
383
384
385def main():
386 args = parse_args()
387 if args.verbose:
388 logging.getLogger().setLevel(logging.INFO)
389
390 device = adb.get_device(args.serial)
391
392 if not args.output:
393 device.wait()
394 args.output = 'perf-%s-%s.tsv' % (
395 device.get_prop('ro.build.flavor'),
396 device.get_prop('ro.build.version.incremental'))
397
398 record_list = []
399 event_tags = read_event_tags(args.tags)
400 init_perf(device, args.output, record_list, event_tags)
401 interval_adjuster = IntervalAdjuster(args.interval, device)
402 event_tags_re = make_event_tags_re(event_tags)
403 end_tag = event_tags[-1]
404 for i in range(args.iterations):
405 print 'Run #%d ' % i
406 record = do_iteration(
407 device, interval_adjuster, event_tags_re, end_tag)
408 record_list.append(record)
409
410
411if __name__ == '__main__':
412 main()