blob: 967299e88783b70d909212e4a9b9d7273e0396d5 [file] [log] [blame]
Florian Mayer801349e2018-11-29 10:15:25 +00001#!/usr/bin/env python
2
3# Copyright (C) 2017 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import argparse
22import atexit
23import hashlib
24import os
Florian Mayer92c80d82019-09-25 14:00:01 +010025import shutil
Florian Mayer801349e2018-11-29 10:15:25 +000026import signal
27import subprocess
28import sys
29import tempfile
30import time
31import urllib
32
33TRACE_TO_TEXT_SHAS = {
Primiano Tucci834fdc72019-10-04 11:33:44 +010034 'linux': '74cb40d9413d7ad756e327e09e46a8adde90db92',
35 'mac': '47045bc6abd4f9113969211f37fdd2259b0c1cc3',
Florian Mayer801349e2018-11-29 10:15:25 +000036}
37TRACE_TO_TEXT_PATH = tempfile.gettempdir()
Primiano Tucci834fdc72019-10-04 11:33:44 +010038TRACE_TO_TEXT_BASE_URL = ('https://storage.googleapis.com/perfetto/')
Florian Mayer801349e2018-11-29 10:15:25 +000039
Florian Mayerbd0a62a2019-04-10 11:09:21 +010040NULL = open(os.devnull)
41NOOUT = {
Primiano Tucci834fdc72019-10-04 11:33:44 +010042 'stdout': NULL,
43 'stderr': NULL,
Florian Mayerbd0a62a2019-04-10 11:09:21 +010044}
45
46
Florian Mayer801349e2018-11-29 10:15:25 +000047def check_hash(file_name, sha_value):
48 with open(file_name, 'rb') as fd:
49 # TODO(fmayer): Chunking.
50 file_hash = hashlib.sha1(fd.read()).hexdigest()
51 return file_hash == sha_value
52
53
54def load_trace_to_text(platform):
55 sha_value = TRACE_TO_TEXT_SHAS[platform]
56 file_name = 'trace_to_text-' + platform + '-' + sha_value
57 local_file = os.path.join(TRACE_TO_TEXT_PATH, file_name)
58
59 if os.path.exists(local_file):
60 if not check_hash(local_file, sha_value):
61 os.remove(local_file)
62 else:
63 return local_file
64
65 url = TRACE_TO_TEXT_BASE_URL + file_name
66 urllib.urlretrieve(url, local_file)
67 if not check_hash(local_file, sha_value):
68 os.remove(local_file)
69 raise ValueError("Invalid signature.")
70 os.chmod(local_file, 0o755)
71 return local_file
72
Primiano Tucci834fdc72019-10-04 11:33:44 +010073
74PACKAGES_LIST_CFG = '''data_sources {
Florian Mayerc8b28692019-05-16 17:03:21 +010075 config {
Florian Mayerfe4361d2019-05-14 11:54:00 +010076 name: "android.packages_list"
Florian Mayerc8b28692019-05-16 17:03:21 +010077 }
78}
Florian Mayerfe4361d2019-05-14 11:54:00 +010079'''
80
Florian Mayer801349e2018-11-29 10:15:25 +000081CFG_IDENT = ' '
Primiano Tucci834fdc72019-10-04 11:33:44 +010082CFG = '''buffers {{
Florian Mayer801349e2018-11-29 10:15:25 +000083 size_kb: 32768
84}}
85
86data_sources {{
87 config {{
88 name: "android.heapprofd"
89 heapprofd_config {{
90
Florian Mayer91b3c6d2019-04-10 13:44:37 -070091 shmem_size_bytes: {shmem_size}
Florian Mayer801349e2018-11-29 10:15:25 +000092 sampling_interval_bytes: {interval}
93{target_cfg}
Florian Mayera8312c72019-01-31 13:50:22 +000094{continuous_dump_cfg}
Florian Mayer801349e2018-11-29 10:15:25 +000095 }}
96 }}
97}}
98
99duration_ms: {duration}
Florian Mayer2aab3162019-05-03 16:02:30 +0100100write_into_file: true
Florian Mayer82610462019-04-16 10:26:07 +0100101flush_timeout_ms: 30000
Florian Mayer801349e2018-11-29 10:15:25 +0000102'''
103
Florian Mayera8312c72019-01-31 13:50:22 +0000104CONTINUOUS_DUMP = """
105 continuous_dump_config {{
106 dump_phase_ms: 0
107 dump_interval_ms: {dump_interval}
108 }}
109"""
110
Primiano Tucci834fdc72019-10-04 11:33:44 +0100111PERFETTO_CMD = ('CFG=\'{cfg}\'; echo ${{CFG}} | '
112 'perfetto --txt -c - -o '
113 '/data/misc/perfetto-traces/profile-{user} -d')
Florian Mayer801349e2018-11-29 10:15:25 +0000114IS_INTERRUPTED = False
Primiano Tucci834fdc72019-10-04 11:33:44 +0100115
116
Florian Mayer801349e2018-11-29 10:15:25 +0000117def sigint_handler(sig, frame):
118 global IS_INTERRUPTED
119 IS_INTERRUPTED = True
120
121
Florian Mayer801349e2018-11-29 10:15:25 +0000122def main(argv):
123 parser = argparse.ArgumentParser()
Primiano Tucci834fdc72019-10-04 11:33:44 +0100124 parser.add_argument(
125 "-i",
126 "--interval",
127 help="Sampling interval. "
128 "Default 4096 (4KiB)",
129 type=int,
130 default=4096)
131 parser.add_argument(
132 "-d",
133 "--duration",
134 help="Duration of profile (ms). "
135 "Default 7 days.",
136 type=int,
137 default=604800000)
138 parser.add_argument(
139 "--no-start", help="Do not start heapprofd.", action='store_true')
140 parser.add_argument(
141 "-p",
142 "--pid",
143 help="Comma-separated list of PIDs to "
144 "profile.",
145 metavar="PIDS")
146 parser.add_argument(
147 "-n",
148 "--name",
149 help="Comma-separated list of process "
150 "names to profile.",
151 metavar="NAMES")
152 parser.add_argument(
153 "-c",
154 "--continuous-dump",
155 help="Dump interval in ms. 0 to disable continuous dump.",
156 type=int,
157 default=0)
158 parser.add_argument(
159 "--disable-selinux",
160 action="store_true",
161 help="Disable SELinux enforcement for duration of "
162 "profile.")
163 parser.add_argument(
164 "--no-versions",
165 action="store_true",
166 help="Do not get version information about APKs.")
167 parser.add_argument(
168 "--no-running",
169 action="store_true",
170 help="Do not target already running processes.")
171 parser.add_argument(
172 "--no-startup",
173 action="store_true",
174 help="Do not target processes that start during "
175 "the profile.")
176 parser.add_argument(
177 "--shmem-size",
178 help="Size of buffer between client and "
179 "heapprofd. Default 8MiB. Needs to be a power of two "
180 "multiple of 4096, at least 8192.",
181 type=int,
182 default=8 * 1048576)
183 parser.add_argument(
184 "--block-client",
185 help="When buffer is full, block the "
186 "client to wait for buffer space. Use with caution as "
187 "this can significantly slow down the client. "
188 "This is the default",
189 action="store_true")
190 parser.add_argument(
Florian Mayere17af212019-11-13 10:04:03 +0000191 "--block-client-timeout",
192 help="If --block-client is given, do not block any allocation for "
193 "longer than this timeout (us).",
194 type=int)
195 parser.add_argument(
Primiano Tucci834fdc72019-10-04 11:33:44 +0100196 "--no-block-client",
197 help="When buffer is full, stop the "
198 "profile early.",
199 action="store_true")
200 parser.add_argument(
201 "--idle-allocations",
202 help="Keep track of how many "
203 "bytes were unused since the last dump, per "
204 "callstack",
205 action="store_true")
206 parser.add_argument(
207 "--dump-at-max",
208 help="Dump the maximum memory usage"
209 "rather than at the time of the dump.",
210 action="store_true")
211 parser.add_argument(
212 "--simpleperf",
213 action="store_true",
214 help="Get simpleperf profile of heapprofd. This is "
215 "only for heapprofd development.")
216 parser.add_argument(
217 "--trace-to-text-binary",
218 help="Path to local trace to text. For debugging.")
219 parser.add_argument(
220 "--print-config",
221 action="store_true",
222 help="Print config instead of running. For debugging.")
Florian Mayer0eee91b2019-05-10 10:36:16 +0100223
Florian Mayer801349e2018-11-29 10:15:25 +0000224 args = parser.parse_args()
225
226 fail = False
Florian Mayerf40dedd2019-07-19 13:08:48 +0100227 if args.block_client and args.no_block_client:
Primiano Tucci834fdc72019-10-04 11:33:44 +0100228 print(
229 "FATAL: Both block-client and no-block-client given.", file=sys.stderr)
Florian Mayerf40dedd2019-07-19 13:08:48 +0100230 fail = True
Florian Mayera774cb72019-04-29 14:20:43 +0100231 if args.pid is None and args.name is None:
232 print("FATAL: Neither PID nor NAME given.", file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000233 fail = True
234 if args.duration is None:
235 print("FATAL: No duration given.", file=sys.stderr)
236 fail = True
237 if args.interval is None:
238 print("FATAL: No interval given.", file=sys.stderr)
239 fail = True
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700240 if args.shmem_size % 4096:
241 print("FATAL: shmem-size is not a multiple of 4096.", file=sys.stderr)
242 fail = True
243 if args.shmem_size < 8192:
244 print("FATAL: shmem-size is less than 8192.", file=sys.stderr)
245 fail = True
246 if args.shmem_size & (args.shmem_size - 1):
247 print("FATAL: shmem-size is not a power of two.", file=sys.stderr)
248 fail = True
Florian Mayer0eee91b2019-05-10 10:36:16 +0100249
Florian Mayer801349e2018-11-29 10:15:25 +0000250 target_cfg = ""
Florian Mayerf40dedd2019-07-19 13:08:48 +0100251 if not args.no_block_client:
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100252 target_cfg += "block_client: true\n"
Florian Mayere17af212019-11-13 10:04:03 +0000253 if args.block_client_timeout:
254 target_cfg += "block_client_timeout_us: %s\n" % args.block_client_timeout
Florian Mayer7142c7c2019-05-20 18:11:41 +0100255 if args.idle_allocations:
256 target_cfg += "idle_allocations: true\n"
Florian Mayer400e4432019-05-29 11:53:20 +0100257 if args.no_startup:
258 target_cfg += "no_startup: true\n"
259 if args.no_running:
260 target_cfg += "no_running: true\n"
Florian Mayer8707d4d2019-07-16 11:17:46 +0100261 if args.dump_at_max:
262 target_cfg += "dump_at_max: true\n"
Florian Mayer801349e2018-11-29 10:15:25 +0000263 if args.pid:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100264 for pid in args.pid.split(','):
265 try:
266 pid = int(pid)
267 except ValueError:
268 print("FATAL: invalid PID %s" % pid, file=sys.stderr)
269 fail = True
Florian Mayer801349e2018-11-29 10:15:25 +0000270 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
271 if args.name:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100272 for name in args.name.split(','):
Florian Mayer801349e2018-11-29 10:15:25 +0000273 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
274
Florian Mayer0eee91b2019-05-10 10:36:16 +0100275 if fail:
276 parser.print_help()
277 return 1
278
Florian Mayer801349e2018-11-29 10:15:25 +0000279 trace_to_text_binary = args.trace_to_text_binary
280 if trace_to_text_binary is None:
281 platform = None
282 if sys.platform.startswith('linux'):
283 platform = 'linux'
284 elif sys.platform.startswith('darwin'):
285 platform = 'mac'
286 else:
287 print("Invalid platform: {}".format(sys.platform), file=sys.stderr)
Florian Mayerb6279632018-11-29 13:31:49 +0000288 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000289
290 trace_to_text_binary = load_trace_to_text(platform)
291
Florian Mayera8312c72019-01-31 13:50:22 +0000292 continuous_dump_cfg = ""
293 if args.continuous_dump:
294 continuous_dump_cfg = CONTINUOUS_DUMP.format(
295 dump_interval=args.continuous_dump)
Primiano Tucci834fdc72019-10-04 11:33:44 +0100296 cfg = CFG.format(
297 interval=args.interval,
298 duration=args.duration,
299 target_cfg=target_cfg,
300 continuous_dump_cfg=continuous_dump_cfg,
301 shmem_size=args.shmem_size)
Florian Mayerfe4361d2019-05-14 11:54:00 +0100302 if not args.no_versions:
303 cfg += PACKAGES_LIST_CFG
304
305 if args.print_config:
306 print(cfg)
307 return 0
Florian Mayer801349e2018-11-29 10:15:25 +0000308
Florian Mayer6ae95262018-12-06 16:10:29 +0000309 if args.disable_selinux:
310 enforcing = subprocess.check_output(['adb', 'shell', 'getenforce'])
Primiano Tucci834fdc72019-10-04 11:33:44 +0100311 atexit.register(
312 subprocess.check_call,
Florian Mayer6ae95262018-12-06 16:10:29 +0000313 ['adb', 'shell', 'su root setenforce %s' % enforcing])
314 subprocess.check_call(['adb', 'shell', 'su root setenforce 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000315
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000316 if not args.no_start:
Florian Mayer75266d52019-02-01 18:09:43 +0000317 heapprofd_prop = subprocess.check_output(
318 ['adb', 'shell', 'getprop persist.heapprofd.enable'])
319 if heapprofd_prop.strip() != '1':
320 subprocess.check_call(
321 ['adb', 'shell', 'setprop persist.heapprofd.enable 1'])
322 atexit.register(subprocess.check_call,
Primiano Tucci834fdc72019-10-04 11:33:44 +0100323 ['adb', 'shell', 'setprop persist.heapprofd.enable 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000324
Florian Mayerbb3b6822019-03-08 17:08:59 +0000325 user = subprocess.check_output(['adb', 'shell', 'whoami']).strip()
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100326
327 if args.simpleperf:
Primiano Tucci834fdc72019-10-04 11:33:44 +0100328 subprocess.check_call([
329 'adb', 'shell', 'mkdir -p /data/local/tmp/heapprofd_profile && '
330 'cd /data/local/tmp/heapprofd_profile &&'
331 '(nohup simpleperf record -g -p $(pidof heapprofd) 2>&1 &) '
332 '> /dev/null'
333 ])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100334
Florian Mayer801349e2018-11-29 10:15:25 +0000335 perfetto_pid = subprocess.check_output(
Primiano Tucci834fdc72019-10-04 11:33:44 +0100336 ['adb', 'exec-out',
337 PERFETTO_CMD.format(cfg=cfg, user=user)]).strip()
Florian Mayer35647422019-03-07 16:28:10 +0000338 try:
339 int(perfetto_pid.strip())
340 except ValueError:
Primiano Tucci834fdc72019-10-04 11:33:44 +0100341 print("Failed to invoke perfetto: {}".format(perfetto_pid), file=sys.stderr)
Florian Mayer35647422019-03-07 16:28:10 +0000342 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000343
344 old_handler = signal.signal(signal.SIGINT, sigint_handler)
345 print("Profiling active. Press Ctrl+C to terminate.")
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100346 print("You may disconnect your device.")
Florian Mayer801349e2018-11-29 10:15:25 +0000347 exists = True
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100348 device_connected = True
349 while not device_connected or (exists and not IS_INTERRUPTED):
Florian Mayer801349e2018-11-29 10:15:25 +0000350 exists = subprocess.call(
Primiano Tucci834fdc72019-10-04 11:33:44 +0100351 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)], **NOOUT) == 0
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100352 device_connected = subprocess.call(['adb', 'shell', 'true'], **NOOUT) == 0
Florian Mayer801349e2018-11-29 10:15:25 +0000353 time.sleep(1)
354 signal.signal(signal.SIGINT, old_handler)
355 if IS_INTERRUPTED:
356 # Not check_call because it could have existed in the meantime.
Florian Mayer85969b92019-01-23 17:23:16 +0000357 subprocess.call(['adb', 'shell', 'kill', '-INT', perfetto_pid])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100358 if args.simpleperf:
359 subprocess.check_call(['adb', 'shell', 'killall', '-INT', 'simpleperf'])
360 print("Waiting for simpleperf to exit.")
361 while subprocess.call(
Primiano Tucci834fdc72019-10-04 11:33:44 +0100362 ['adb', 'shell', '[ -f /proc/$(pidof simpleperf)/exe ]'], **NOOUT) == 0:
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100363 time.sleep(1)
Primiano Tucci834fdc72019-10-04 11:33:44 +0100364 subprocess.check_call(
365 ['adb', 'pull', '/data/local/tmp/heapprofd_profile', '/tmp'])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100366 print("Pulled simpleperf profile to /tmp/heapprofd_profile")
Florian Mayer801349e2018-11-29 10:15:25 +0000367
Florian Mayerddbe31e2018-11-30 14:49:30 +0000368 # Wait for perfetto cmd to return.
369 while exists:
370 exists = subprocess.call(
371 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
372 time.sleep(1)
373
Primiano Tucci834fdc72019-10-04 11:33:44 +0100374 subprocess.check_call([
375 'adb', 'pull', '/data/misc/perfetto-traces/profile-{}'.format(user),
376 '/tmp/profile'
377 ],
378 stdout=NULL)
Florian Mayer801349e2018-11-29 10:15:25 +0000379 trace_to_text_output = subprocess.check_output(
Florian Mayer6fc484e2019-04-10 16:07:54 +0100380 [trace_to_text_binary, 'profile', '/tmp/profile'])
Florian Mayer801349e2018-11-29 10:15:25 +0000381 profile_path = None
382 for word in trace_to_text_output.split():
383 if 'heap_profile-' in word:
384 profile_path = word
385 if profile_path is None:
386 print("Could not find trace_to_text output path.", file=sys.stderr)
387 return 1
388
389 profile_files = os.listdir(profile_path)
390 if not profile_files:
391 print("No profiles generated", file=sys.stderr)
Matthew Clarkson63028d62019-10-10 15:48:23 +0100392 print(
393 "If this is unexpected, check "
394 "https://docs.perfetto.dev/#/heapprofd?id=troubleshooting.",
395 file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000396 return 1
397
Primiano Tucci834fdc72019-10-04 11:33:44 +0100398 subprocess.check_call(
399 ['gzip'] +
400 [os.path.join(profile_path, x) for x in os.listdir(profile_path)])
Florian Mayer82f43d12019-01-17 14:37:45 +0000401
Primiano Tucci834fdc72019-10-04 11:33:44 +0100402 symlink_path = os.path.join(
403 os.path.dirname(profile_path), "heap_profile-latest")
Florian Mayer91967ee2019-05-10 16:43:50 +0100404 if os.path.lexists(symlink_path):
Florian Mayer31305512019-01-21 17:37:02 +0000405 os.unlink(symlink_path)
Florian Mayer82f43d12019-01-17 14:37:45 +0000406 os.symlink(profile_path, symlink_path)
Florian Mayer92c80d82019-09-25 14:00:01 +0100407 shutil.copyfile('/tmp/profile', os.path.join(profile_path, 'raw-trace'))
Florian Mayer82f43d12019-01-17 14:37:45 +0000408
409 print("Wrote profiles to {} (symlink {})".format(profile_path, symlink_path))
Florian Mayer801349e2018-11-29 10:15:25 +0000410 print("These can be viewed using pprof. Googlers: head to pprof/ and "
411 "upload them.")
412
413
414if __name__ == '__main__':
415 sys.exit(main(sys.argv))