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