blob: 583d640ef4f3f2b55a0ea853028fd6519d08b6fe [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',
Yusuke Sato43c4d992015-08-04 12:05:45 -070069 'sf_stop_bootanim',
70 'wm_boot_animation_done',
Yasuhiro Matsudaab379832015-07-03 02:08:55 +090071]
72
73
74class IntervalAdjuster(object):
75 """A helper class to take suffficient interval between iterations."""
76
77 # CPU temperature values per product used to decide interval
78 _CPU_COOL_DOWN_THRESHOLDS = {
79 'flo': 40,
80 'flounder': 40000,
81 'razor': 40,
82 'volantis': 40000,
83 }
84 # The interval between CPU temperature checks
85 _CPU_COOL_DOWN_WAIT_INTERVAL = 10
86 # The wait time used when the value of _CPU_COOL_DOWN_THRESHOLDS for
87 # the product is not defined.
88 _CPU_COOL_DOWN_WAIT_TIME_DEFAULT = 120
89
90 def __init__(self, interval, device):
91 self._interval = interval
92 self._device = device
93 self._temp_paths = device.shell(
94 ['ls', '/sys/class/thermal/thermal_zone*/temp']).splitlines()
95 self._product = device.get_prop('ro.build.product')
96 self._waited = False
97
98 def wait(self):
99 """Waits certain amount of time for CPUs cool-down."""
100 if self._interval is None:
101 self._wait_cpu_cool_down(self._product, self._temp_paths)
102 else:
103 if self._waited:
104 print 'Waiting for %d seconds' % self._interval
105 time.sleep(self._interval)
106 self._waited = True
107
108 def _get_cpu_temp(self, threshold):
109 max_temp = 0
110 for temp_path in self._temp_paths:
111 temp = int(self._device.shell(['cat', temp_path]).rstrip())
112 max_temp = max(max_temp, temp)
113 if temp >= threshold:
114 return temp
115 return max_temp
116
117 def _wait_cpu_cool_down(self, product, temp_paths):
118 threshold = IntervalAdjuster._CPU_COOL_DOWN_THRESHOLDS.get(
119 self._product)
120 if threshold is None:
121 print 'No CPU temperature threshold is set for ' + self._product
122 print ('Just wait %d seconds' %
123 IntervalAdjuster._CPU_COOL_DOWN_WAIT_TIME_DEFAULT)
124 time.sleep(IntervalAdjuster._CPU_COOL_DOWN_WAIT_TIME_DEFAULT)
125 return
126 while True:
127 temp = self._get_cpu_temp(threshold)
128 if temp < threshold:
129 logging.info('Current CPU temperature %s' % temp)
130 return
131 print 'Waiting until CPU temperature (%d) falls below %d' % (
132 temp, threshold)
133 time.sleep(IntervalAdjuster._CPU_COOL_DOWN_WAIT_INTERVAL)
134
135
136class WatchdogTimer(object):
137 """A timer that makes is_timedout() return true in |timeout| seconds."""
138 def __init__(self, timeout):
139 self._timedout = False
140
141 def notify_timeout():
142 self._timedout = True
143 self._timer = threading.Timer(timeout, notify_timeout)
Yasuhiro Matsuda59d32a72015-08-04 17:48:41 +0900144 self._timer.daemon = True
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900145 self._timer.start()
146
147 def is_timedout(self):
148 return self._timedout
149
150 def cancel(self):
151 self._timer.cancel()
152
153
154def readlines_unbuffered(proc):
155 """Read lines from |proc|'s standard out without buffering."""
156 while True:
157 buf = []
158 c = proc.stdout.read(1)
159 if c == '' and proc.poll() is not None:
160 break
161 while c != '\n':
162 if c == '' and proc.poll() is not None:
163 break
164 buf.append(c)
165 c = proc.stdout.read(1)
166 yield ''.join(buf)
167
168
169def disable_dropbox(device):
170 """Removes the files created by Dropbox and avoids creating the files."""
171 device.root()
172 device.wait()
173 device.shell(['rm', '-rf', '/system/data/dropbox'])
174 original_dropbox_max_files = device.shell(
175 ['settings', 'get', 'global', 'dropbox_max_files']).rstrip()
176 device.shell(['settings', 'put', 'global', 'dropbox_max_files', '0'])
177 return original_dropbox_max_files
178
179
180def restore_dropbox(device, original_dropbox_max_files):
181 """Restores the dropbox_max_files setting."""
182 device.root()
183 device.wait()
184 if original_dropbox_max_files == 'null':
185 device.shell(['settings', 'delete', 'global', 'dropbox_max_files'])
186 else:
187 device.shell(['settings', 'put', 'global', 'dropbox_max_files',
188 original_dropbox_max_files])
189
190
191def init_perf(device, output, record_list, tags):
192 device.wait()
193 build_type = device.get_prop('ro.build.type')
194 original_dropbox_max_files = None
195 if build_type != 'user':
196 # Workaround for Dropbox issue (http://b/20890386).
197 original_dropbox_max_files = disable_dropbox(device)
198
199 def cleanup():
200 try:
201 if record_list:
202 print_summary(record_list, tags[-1])
203 output_results(output, record_list, tags)
204 if original_dropbox_max_files is not None:
205 restore_dropbox(device, original_dropbox_max_files)
Yasuhiro Matsudaf3d0d422015-08-05 20:26:03 +0900206 except (subprocess.CalledProcessError, RuntimeError):
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900207 pass
208 atexit.register(cleanup)
209
210
Yusuke Satob6c66dc2015-07-31 08:47:48 -0700211def check_dm_verity_settings(device):
212 device.wait()
213 for partition in ['system', 'vendor']:
214 verity_mode = device.get_prop('partition.%s.verified' % partition)
215 if verity_mode is None:
216 logging.warning('dm-verity is not enabled for /%s. Did you run '
217 'adb disable-verity? That may skew the result.',
218 partition)
219
220
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900221def read_event_tags(tags_file):
222 """Reads event tags from |tags_file|."""
223 if not tags_file:
224 return _DEFAULT_EVENT_TAGS
225 tags = []
226 with open(tags_file) as f:
227 for line in f:
228 if '#' in line:
229 line = line[:line.find('#')]
230 line = line.strip()
231 if line:
232 tags.append(line)
233 return tags
234
235
236def make_event_tags_re(tags):
237 """Makes a regular expression object that matches event logs of |tags|."""
238 return re.compile(r'(?P<pid>[0-9]+) +[0-9]+ I (?P<tag>%s): (?P<time>\d+)' %
239 '|'.join(tags))
240
241
Yusuke Satoe801cc02015-08-03 15:54:36 -0700242def filter_event_tags(tags, device):
243 """Drop unknown tags not listed in device's event-log-tags file."""
244 device.wait()
245 supported_tags = set()
246 for l in device.shell(['cat', '/system/etc/event-log-tags']).splitlines():
247 tokens = l.split(' ')
248 if len(tokens) >= 2:
249 supported_tags.add(tokens[1])
250 filtered = []
251 for tag in tags:
252 if tag in supported_tags:
253 filtered.append(tag)
254 else:
255 logging.warning('Unknown tag \'%s\'. Ignoring...', tag)
256 return filtered
257
258
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900259def get_values(record, tag):
260 """Gets values that matches |tag| from |record|."""
261 keys = [key for key in record.keys() if key[0] == tag]
262 return [record[k] for k in sorted(keys)]
263
264
265def get_last_value(record, tag):
266 """Gets the last value that matches |tag| from |record|."""
267 values = get_values(record, tag)
268 if not values:
269 return 0
270 return values[-1]
271
272
273def output_results(filename, record_list, tags):
274 """Outputs |record_list| into |filename| in a TSV format."""
275 # First, count the number of the values of each tag.
276 # This is for dealing with events that occur multiple times.
277 # For instance, boot_progress_preload_start and boot_progress_preload_end
278 # are recorded twice on 64-bit system. One is for 64-bit zygote process
279 # and the other is for 32-bit zygote process.
280 values_counter = {}
281 for record in record_list:
282 for tag in tags:
283 # Some record might lack values for some tags due to unanticipated
284 # problems (e.g. timeout), so take the maximum count among all the
285 # record.
286 values_counter[tag] = max(values_counter.get(tag, 1),
287 len(get_values(record, tag)))
288
289 # Then creates labels for the data. If there are multiple values for one
290 # tag, labels for these values are numbered except the first one as
291 # follows:
292 #
293 # event_tag event_tag2 event_tag3
294 #
295 # The corresponding values are sorted in an ascending order of PID.
296 labels = []
297 for tag in tags:
298 for i in range(1, values_counter[tag] + 1):
299 labels.append('%s%s' % (tag, '' if i == 1 else str(i)))
300
301 # Finally write the data into the file.
302 with open(filename, 'w') as f:
303 f.write('\t'.join(labels) + '\n')
304 for record in record_list:
305 line = cStringIO.StringIO()
306 invalid_line = False
307 for i, tag in enumerate(tags):
308 if i != 0:
309 line.write('\t')
310 values = get_values(record, tag)
311 if len(values) < values_counter[tag]:
312 invalid_line = True
313 # Fill invalid record with 0
314 values += [0] * (values_counter[tag] - len(values))
315 line.write('\t'.join(str(t) for t in values))
316 if invalid_line:
317 logging.error('Invalid record found: ' + line.getvalue())
318 line.write('\n')
319 f.write(line.getvalue())
320 print 'Wrote: ' + filename
321
322
323def median(data):
324 """Calculates the median value from |data|."""
325 data = sorted(data)
326 n = len(data)
327 if n % 2 == 1:
328 return data[n / 2]
329 else:
330 n2 = n / 2
331 return (data[n2 - 1] + data[n2]) / 2.0
332
333
334def mean(data):
335 """Calculates the mean value from |data|."""
336 return float(sum(data)) / len(data)
337
338
339def stddev(data):
340 """Calculates the standard deviation value from |value|."""
341 m = mean(data)
342 return math.sqrt(sum((x - m) ** 2 for x in data) / len(data))
343
344
345def print_summary(record_list, end_tag):
346 """Prints the summary of |record_list|."""
347 # Filter out invalid data.
348 end_times = [get_last_value(record, end_tag) for record in record_list
349 if get_last_value(record, end_tag) != 0]
350 print 'mean: ', mean(end_times)
351 print 'median:', median(end_times)
352 print 'standard deviation:', stddev(end_times)
353
354
355def do_iteration(device, interval_adjuster, event_tags_re, end_tag):
356 """Measures the boot time once."""
357 device.wait()
358 interval_adjuster.wait()
359 device.reboot()
360 print 'Rebooted the device'
361 record = {}
362 booted = False
363 while not booted:
364 device.wait()
365 # Stop the iteration if it does not finish within 120 seconds.
366 timeout = 120
367 t = WatchdogTimer(timeout)
368 p = subprocess.Popen(
369 ['adb', 'logcat', '-b', 'events', '-v', 'threadtime'],
370 stdout=subprocess.PIPE)
371 for line in readlines_unbuffered(p):
372 if t.is_timedout():
373 print '*** Timed out ***'
374 return record
375 m = event_tags_re.search(line)
376 if not m:
377 continue
378 tag = m.group('tag')
379 event_time = int(m.group('time'))
380 pid = m.group('pid')
381 record[(tag, pid)] = event_time
382 print 'Event log recorded: %s (%s) - %d ms' % (
383 tag, pid, event_time)
384 if tag == end_tag:
385 booted = True
386 t.cancel()
387 break
388 return record
389
390
391def parse_args():
392 """Parses the command line arguments."""
393 parser = argparse.ArgumentParser(
394 description=inspect.getdoc(sys.modules[__name__]),
395 formatter_class=argparse.RawDescriptionHelpFormatter)
396 parser.add_argument('--iterations', type=int, default=5,
397 help='Number of times to repeat boot measurements.')
398 parser.add_argument('--interval', type=int,
399 help=('Duration between iterations. If this is not '
400 'set explicitly, durations are determined '
401 'adaptively based on CPUs temperature.'))
402 parser.add_argument('-o', '--output', help='File name of output data.')
403 parser.add_argument('-v', '--verbose', action='store_true',
404 help='Show verbose output.')
405 parser.add_argument('-s', '--serial', default=os.getenv('ANDROID_SERIAL'),
406 help='Adb device serial number.')
407 parser.add_argument('-t', '--tags', help='Specify the filename from which '
408 'event tags are read. Every line contains one event '
409 'tag and the last event tag is used to detect that '
410 'the device has finished booting.')
411 return parser.parse_args()
412
413
414def main():
415 args = parse_args()
416 if args.verbose:
417 logging.getLogger().setLevel(logging.INFO)
418
419 device = adb.get_device(args.serial)
420
421 if not args.output:
422 device.wait()
423 args.output = 'perf-%s-%s.tsv' % (
424 device.get_prop('ro.build.flavor'),
425 device.get_prop('ro.build.version.incremental'))
Yusuke Satob6c66dc2015-07-31 08:47:48 -0700426 check_dm_verity_settings(device)
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900427
428 record_list = []
Yusuke Satoe801cc02015-08-03 15:54:36 -0700429 event_tags = filter_event_tags(read_event_tags(args.tags), device)
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900430 init_perf(device, args.output, record_list, event_tags)
431 interval_adjuster = IntervalAdjuster(args.interval, device)
432 event_tags_re = make_event_tags_re(event_tags)
433 end_tag = event_tags[-1]
434 for i in range(args.iterations):
435 print 'Run #%d ' % i
436 record = do_iteration(
437 device, interval_adjuster, event_tags_re, end_tag)
438 record_list.append(record)
439
440
441if __name__ == '__main__':
442 main()