blob: 8f2096aa879079eea4d325510a2e0c2092f909a6 [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)
144 self._timer.start()
145
146 def is_timedout(self):
147 return self._timedout
148
149 def cancel(self):
150 self._timer.cancel()
151
152
153def readlines_unbuffered(proc):
154 """Read lines from |proc|'s standard out without buffering."""
155 while True:
156 buf = []
157 c = proc.stdout.read(1)
158 if c == '' and proc.poll() is not None:
159 break
160 while c != '\n':
161 if c == '' and proc.poll() is not None:
162 break
163 buf.append(c)
164 c = proc.stdout.read(1)
165 yield ''.join(buf)
166
167
168def disable_dropbox(device):
169 """Removes the files created by Dropbox and avoids creating the files."""
170 device.root()
171 device.wait()
172 device.shell(['rm', '-rf', '/system/data/dropbox'])
173 original_dropbox_max_files = device.shell(
174 ['settings', 'get', 'global', 'dropbox_max_files']).rstrip()
175 device.shell(['settings', 'put', 'global', 'dropbox_max_files', '0'])
176 return original_dropbox_max_files
177
178
179def restore_dropbox(device, original_dropbox_max_files):
180 """Restores the dropbox_max_files setting."""
181 device.root()
182 device.wait()
183 if original_dropbox_max_files == 'null':
184 device.shell(['settings', 'delete', 'global', 'dropbox_max_files'])
185 else:
186 device.shell(['settings', 'put', 'global', 'dropbox_max_files',
187 original_dropbox_max_files])
188
189
190def init_perf(device, output, record_list, tags):
191 device.wait()
192 build_type = device.get_prop('ro.build.type')
193 original_dropbox_max_files = None
194 if build_type != 'user':
195 # Workaround for Dropbox issue (http://b/20890386).
196 original_dropbox_max_files = disable_dropbox(device)
197
198 def cleanup():
199 try:
200 if record_list:
201 print_summary(record_list, tags[-1])
202 output_results(output, record_list, tags)
203 if original_dropbox_max_files is not None:
204 restore_dropbox(device, original_dropbox_max_files)
205 except subprocess.CalledProcessError, RuntimeError:
206 pass
207 atexit.register(cleanup)
208
209
Yusuke Satob6c66dc2015-07-31 08:47:48 -0700210def check_dm_verity_settings(device):
211 device.wait()
212 for partition in ['system', 'vendor']:
213 verity_mode = device.get_prop('partition.%s.verified' % partition)
214 if verity_mode is None:
215 logging.warning('dm-verity is not enabled for /%s. Did you run '
216 'adb disable-verity? That may skew the result.',
217 partition)
218
219
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900220def read_event_tags(tags_file):
221 """Reads event tags from |tags_file|."""
222 if not tags_file:
223 return _DEFAULT_EVENT_TAGS
224 tags = []
225 with open(tags_file) as f:
226 for line in f:
227 if '#' in line:
228 line = line[:line.find('#')]
229 line = line.strip()
230 if line:
231 tags.append(line)
232 return tags
233
234
235def make_event_tags_re(tags):
236 """Makes a regular expression object that matches event logs of |tags|."""
237 return re.compile(r'(?P<pid>[0-9]+) +[0-9]+ I (?P<tag>%s): (?P<time>\d+)' %
238 '|'.join(tags))
239
240
Yusuke Satoe801cc02015-08-03 15:54:36 -0700241def filter_event_tags(tags, device):
242 """Drop unknown tags not listed in device's event-log-tags file."""
243 device.wait()
244 supported_tags = set()
245 for l in device.shell(['cat', '/system/etc/event-log-tags']).splitlines():
246 tokens = l.split(' ')
247 if len(tokens) >= 2:
248 supported_tags.add(tokens[1])
249 filtered = []
250 for tag in tags:
251 if tag in supported_tags:
252 filtered.append(tag)
253 else:
254 logging.warning('Unknown tag \'%s\'. Ignoring...', tag)
255 return filtered
256
257
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900258def get_values(record, tag):
259 """Gets values that matches |tag| from |record|."""
260 keys = [key for key in record.keys() if key[0] == tag]
261 return [record[k] for k in sorted(keys)]
262
263
264def get_last_value(record, tag):
265 """Gets the last value that matches |tag| from |record|."""
266 values = get_values(record, tag)
267 if not values:
268 return 0
269 return values[-1]
270
271
272def output_results(filename, record_list, tags):
273 """Outputs |record_list| into |filename| in a TSV format."""
274 # First, count the number of the values of each tag.
275 # This is for dealing with events that occur multiple times.
276 # For instance, boot_progress_preload_start and boot_progress_preload_end
277 # are recorded twice on 64-bit system. One is for 64-bit zygote process
278 # and the other is for 32-bit zygote process.
279 values_counter = {}
280 for record in record_list:
281 for tag in tags:
282 # Some record might lack values for some tags due to unanticipated
283 # problems (e.g. timeout), so take the maximum count among all the
284 # record.
285 values_counter[tag] = max(values_counter.get(tag, 1),
286 len(get_values(record, tag)))
287
288 # Then creates labels for the data. If there are multiple values for one
289 # tag, labels for these values are numbered except the first one as
290 # follows:
291 #
292 # event_tag event_tag2 event_tag3
293 #
294 # The corresponding values are sorted in an ascending order of PID.
295 labels = []
296 for tag in tags:
297 for i in range(1, values_counter[tag] + 1):
298 labels.append('%s%s' % (tag, '' if i == 1 else str(i)))
299
300 # Finally write the data into the file.
301 with open(filename, 'w') as f:
302 f.write('\t'.join(labels) + '\n')
303 for record in record_list:
304 line = cStringIO.StringIO()
305 invalid_line = False
306 for i, tag in enumerate(tags):
307 if i != 0:
308 line.write('\t')
309 values = get_values(record, tag)
310 if len(values) < values_counter[tag]:
311 invalid_line = True
312 # Fill invalid record with 0
313 values += [0] * (values_counter[tag] - len(values))
314 line.write('\t'.join(str(t) for t in values))
315 if invalid_line:
316 logging.error('Invalid record found: ' + line.getvalue())
317 line.write('\n')
318 f.write(line.getvalue())
319 print 'Wrote: ' + filename
320
321
322def median(data):
323 """Calculates the median value from |data|."""
324 data = sorted(data)
325 n = len(data)
326 if n % 2 == 1:
327 return data[n / 2]
328 else:
329 n2 = n / 2
330 return (data[n2 - 1] + data[n2]) / 2.0
331
332
333def mean(data):
334 """Calculates the mean value from |data|."""
335 return float(sum(data)) / len(data)
336
337
338def stddev(data):
339 """Calculates the standard deviation value from |value|."""
340 m = mean(data)
341 return math.sqrt(sum((x - m) ** 2 for x in data) / len(data))
342
343
344def print_summary(record_list, end_tag):
345 """Prints the summary of |record_list|."""
346 # Filter out invalid data.
347 end_times = [get_last_value(record, end_tag) for record in record_list
348 if get_last_value(record, end_tag) != 0]
349 print 'mean: ', mean(end_times)
350 print 'median:', median(end_times)
351 print 'standard deviation:', stddev(end_times)
352
353
354def do_iteration(device, interval_adjuster, event_tags_re, end_tag):
355 """Measures the boot time once."""
356 device.wait()
357 interval_adjuster.wait()
358 device.reboot()
359 print 'Rebooted the device'
360 record = {}
361 booted = False
362 while not booted:
363 device.wait()
364 # Stop the iteration if it does not finish within 120 seconds.
365 timeout = 120
366 t = WatchdogTimer(timeout)
367 p = subprocess.Popen(
368 ['adb', 'logcat', '-b', 'events', '-v', 'threadtime'],
369 stdout=subprocess.PIPE)
370 for line in readlines_unbuffered(p):
371 if t.is_timedout():
372 print '*** Timed out ***'
373 return record
374 m = event_tags_re.search(line)
375 if not m:
376 continue
377 tag = m.group('tag')
378 event_time = int(m.group('time'))
379 pid = m.group('pid')
380 record[(tag, pid)] = event_time
381 print 'Event log recorded: %s (%s) - %d ms' % (
382 tag, pid, event_time)
383 if tag == end_tag:
384 booted = True
385 t.cancel()
386 break
387 return record
388
389
390def parse_args():
391 """Parses the command line arguments."""
392 parser = argparse.ArgumentParser(
393 description=inspect.getdoc(sys.modules[__name__]),
394 formatter_class=argparse.RawDescriptionHelpFormatter)
395 parser.add_argument('--iterations', type=int, default=5,
396 help='Number of times to repeat boot measurements.')
397 parser.add_argument('--interval', type=int,
398 help=('Duration between iterations. If this is not '
399 'set explicitly, durations are determined '
400 'adaptively based on CPUs temperature.'))
401 parser.add_argument('-o', '--output', help='File name of output data.')
402 parser.add_argument('-v', '--verbose', action='store_true',
403 help='Show verbose output.')
404 parser.add_argument('-s', '--serial', default=os.getenv('ANDROID_SERIAL'),
405 help='Adb device serial number.')
406 parser.add_argument('-t', '--tags', help='Specify the filename from which '
407 'event tags are read. Every line contains one event '
408 'tag and the last event tag is used to detect that '
409 'the device has finished booting.')
410 return parser.parse_args()
411
412
413def main():
414 args = parse_args()
415 if args.verbose:
416 logging.getLogger().setLevel(logging.INFO)
417
418 device = adb.get_device(args.serial)
419
420 if not args.output:
421 device.wait()
422 args.output = 'perf-%s-%s.tsv' % (
423 device.get_prop('ro.build.flavor'),
424 device.get_prop('ro.build.version.incremental'))
Yusuke Satob6c66dc2015-07-31 08:47:48 -0700425 check_dm_verity_settings(device)
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900426
427 record_list = []
Yusuke Satoe801cc02015-08-03 15:54:36 -0700428 event_tags = filter_event_tags(read_event_tags(args.tags), device)
Yasuhiro Matsudaab379832015-07-03 02:08:55 +0900429 init_perf(device, args.output, record_list, event_tags)
430 interval_adjuster = IntervalAdjuster(args.interval, device)
431 event_tags_re = make_event_tags_re(event_tags)
432 end_tag = event_tags[-1]
433 for i in range(args.iterations):
434 print 'Run #%d ' % i
435 record = do_iteration(
436 device, interval_adjuster, event_tags_re, end_tag)
437 record_list.append(record)
438
439
440if __name__ == '__main__':
441 main()