blob: d70591465517ad4af917f63b1dc03ed66271f55b [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(
191 "--no-block-client",
192 help="When buffer is full, stop the "
193 "profile early.",
194 action="store_true")
195 parser.add_argument(
196 "--idle-allocations",
197 help="Keep track of how many "
198 "bytes were unused since the last dump, per "
199 "callstack",
200 action="store_true")
201 parser.add_argument(
202 "--dump-at-max",
203 help="Dump the maximum memory usage"
204 "rather than at the time of the dump.",
205 action="store_true")
206 parser.add_argument(
207 "--simpleperf",
208 action="store_true",
209 help="Get simpleperf profile of heapprofd. This is "
210 "only for heapprofd development.")
211 parser.add_argument(
212 "--trace-to-text-binary",
213 help="Path to local trace to text. For debugging.")
214 parser.add_argument(
215 "--print-config",
216 action="store_true",
217 help="Print config instead of running. For debugging.")
Florian Mayer0eee91b2019-05-10 10:36:16 +0100218
Florian Mayer801349e2018-11-29 10:15:25 +0000219 args = parser.parse_args()
220
221 fail = False
Florian Mayerf40dedd2019-07-19 13:08:48 +0100222 if args.block_client and args.no_block_client:
Primiano Tucci834fdc72019-10-04 11:33:44 +0100223 print(
224 "FATAL: Both block-client and no-block-client given.", file=sys.stderr)
Florian Mayerf40dedd2019-07-19 13:08:48 +0100225 fail = True
Florian Mayera774cb72019-04-29 14:20:43 +0100226 if args.pid is None and args.name is None:
227 print("FATAL: Neither PID nor NAME given.", file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000228 fail = True
229 if args.duration is None:
230 print("FATAL: No duration given.", file=sys.stderr)
231 fail = True
232 if args.interval is None:
233 print("FATAL: No interval given.", file=sys.stderr)
234 fail = True
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700235 if args.shmem_size % 4096:
236 print("FATAL: shmem-size is not a multiple of 4096.", file=sys.stderr)
237 fail = True
238 if args.shmem_size < 8192:
239 print("FATAL: shmem-size is less than 8192.", file=sys.stderr)
240 fail = True
241 if args.shmem_size & (args.shmem_size - 1):
242 print("FATAL: shmem-size is not a power of two.", file=sys.stderr)
243 fail = True
Florian Mayer0eee91b2019-05-10 10:36:16 +0100244
Florian Mayer801349e2018-11-29 10:15:25 +0000245 target_cfg = ""
Florian Mayerf40dedd2019-07-19 13:08:48 +0100246 if not args.no_block_client:
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100247 target_cfg += "block_client: true\n"
Florian Mayer7142c7c2019-05-20 18:11:41 +0100248 if args.idle_allocations:
249 target_cfg += "idle_allocations: true\n"
Florian Mayer400e4432019-05-29 11:53:20 +0100250 if args.no_startup:
251 target_cfg += "no_startup: true\n"
252 if args.no_running:
253 target_cfg += "no_running: true\n"
Florian Mayer8707d4d2019-07-16 11:17:46 +0100254 if args.dump_at_max:
255 target_cfg += "dump_at_max: true\n"
Florian Mayer801349e2018-11-29 10:15:25 +0000256 if args.pid:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100257 for pid in args.pid.split(','):
258 try:
259 pid = int(pid)
260 except ValueError:
261 print("FATAL: invalid PID %s" % pid, file=sys.stderr)
262 fail = True
Florian Mayer801349e2018-11-29 10:15:25 +0000263 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
264 if args.name:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100265 for name in args.name.split(','):
Florian Mayer801349e2018-11-29 10:15:25 +0000266 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
267
Florian Mayer0eee91b2019-05-10 10:36:16 +0100268 if fail:
269 parser.print_help()
270 return 1
271
Florian Mayer801349e2018-11-29 10:15:25 +0000272 trace_to_text_binary = args.trace_to_text_binary
273 if trace_to_text_binary is None:
274 platform = None
275 if sys.platform.startswith('linux'):
276 platform = 'linux'
277 elif sys.platform.startswith('darwin'):
278 platform = 'mac'
279 else:
280 print("Invalid platform: {}".format(sys.platform), file=sys.stderr)
Florian Mayerb6279632018-11-29 13:31:49 +0000281 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000282
283 trace_to_text_binary = load_trace_to_text(platform)
284
Florian Mayera8312c72019-01-31 13:50:22 +0000285 continuous_dump_cfg = ""
286 if args.continuous_dump:
287 continuous_dump_cfg = CONTINUOUS_DUMP.format(
288 dump_interval=args.continuous_dump)
Primiano Tucci834fdc72019-10-04 11:33:44 +0100289 cfg = CFG.format(
290 interval=args.interval,
291 duration=args.duration,
292 target_cfg=target_cfg,
293 continuous_dump_cfg=continuous_dump_cfg,
294 shmem_size=args.shmem_size)
Florian Mayerfe4361d2019-05-14 11:54:00 +0100295 if not args.no_versions:
296 cfg += PACKAGES_LIST_CFG
297
298 if args.print_config:
299 print(cfg)
300 return 0
Florian Mayer801349e2018-11-29 10:15:25 +0000301
Florian Mayer6ae95262018-12-06 16:10:29 +0000302 if args.disable_selinux:
303 enforcing = subprocess.check_output(['adb', 'shell', 'getenforce'])
Primiano Tucci834fdc72019-10-04 11:33:44 +0100304 atexit.register(
305 subprocess.check_call,
Florian Mayer6ae95262018-12-06 16:10:29 +0000306 ['adb', 'shell', 'su root setenforce %s' % enforcing])
307 subprocess.check_call(['adb', 'shell', 'su root setenforce 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000308
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000309 if not args.no_start:
Florian Mayer75266d52019-02-01 18:09:43 +0000310 heapprofd_prop = subprocess.check_output(
311 ['adb', 'shell', 'getprop persist.heapprofd.enable'])
312 if heapprofd_prop.strip() != '1':
313 subprocess.check_call(
314 ['adb', 'shell', 'setprop persist.heapprofd.enable 1'])
315 atexit.register(subprocess.check_call,
Primiano Tucci834fdc72019-10-04 11:33:44 +0100316 ['adb', 'shell', 'setprop persist.heapprofd.enable 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000317
Florian Mayerbb3b6822019-03-08 17:08:59 +0000318 user = subprocess.check_output(['adb', 'shell', 'whoami']).strip()
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100319
320 if args.simpleperf:
Primiano Tucci834fdc72019-10-04 11:33:44 +0100321 subprocess.check_call([
322 'adb', 'shell', 'mkdir -p /data/local/tmp/heapprofd_profile && '
323 'cd /data/local/tmp/heapprofd_profile &&'
324 '(nohup simpleperf record -g -p $(pidof heapprofd) 2>&1 &) '
325 '> /dev/null'
326 ])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100327
Florian Mayer801349e2018-11-29 10:15:25 +0000328 perfetto_pid = subprocess.check_output(
Primiano Tucci834fdc72019-10-04 11:33:44 +0100329 ['adb', 'exec-out',
330 PERFETTO_CMD.format(cfg=cfg, user=user)]).strip()
Florian Mayer35647422019-03-07 16:28:10 +0000331 try:
332 int(perfetto_pid.strip())
333 except ValueError:
Primiano Tucci834fdc72019-10-04 11:33:44 +0100334 print("Failed to invoke perfetto: {}".format(perfetto_pid), file=sys.stderr)
Florian Mayer35647422019-03-07 16:28:10 +0000335 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000336
337 old_handler = signal.signal(signal.SIGINT, sigint_handler)
338 print("Profiling active. Press Ctrl+C to terminate.")
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100339 print("You may disconnect your device.")
Florian Mayer801349e2018-11-29 10:15:25 +0000340 exists = True
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100341 device_connected = True
342 while not device_connected or (exists and not IS_INTERRUPTED):
Florian Mayer801349e2018-11-29 10:15:25 +0000343 exists = subprocess.call(
Primiano Tucci834fdc72019-10-04 11:33:44 +0100344 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)], **NOOUT) == 0
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100345 device_connected = subprocess.call(['adb', 'shell', 'true'], **NOOUT) == 0
Florian Mayer801349e2018-11-29 10:15:25 +0000346 time.sleep(1)
347 signal.signal(signal.SIGINT, old_handler)
348 if IS_INTERRUPTED:
349 # Not check_call because it could have existed in the meantime.
Florian Mayer85969b92019-01-23 17:23:16 +0000350 subprocess.call(['adb', 'shell', 'kill', '-INT', perfetto_pid])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100351 if args.simpleperf:
352 subprocess.check_call(['adb', 'shell', 'killall', '-INT', 'simpleperf'])
353 print("Waiting for simpleperf to exit.")
354 while subprocess.call(
Primiano Tucci834fdc72019-10-04 11:33:44 +0100355 ['adb', 'shell', '[ -f /proc/$(pidof simpleperf)/exe ]'], **NOOUT) == 0:
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100356 time.sleep(1)
Primiano Tucci834fdc72019-10-04 11:33:44 +0100357 subprocess.check_call(
358 ['adb', 'pull', '/data/local/tmp/heapprofd_profile', '/tmp'])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100359 print("Pulled simpleperf profile to /tmp/heapprofd_profile")
Florian Mayer801349e2018-11-29 10:15:25 +0000360
Florian Mayerddbe31e2018-11-30 14:49:30 +0000361 # Wait for perfetto cmd to return.
362 while exists:
363 exists = subprocess.call(
364 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
365 time.sleep(1)
366
Primiano Tucci834fdc72019-10-04 11:33:44 +0100367 subprocess.check_call([
368 'adb', 'pull', '/data/misc/perfetto-traces/profile-{}'.format(user),
369 '/tmp/profile'
370 ],
371 stdout=NULL)
Florian Mayer801349e2018-11-29 10:15:25 +0000372 trace_to_text_output = subprocess.check_output(
Florian Mayer6fc484e2019-04-10 16:07:54 +0100373 [trace_to_text_binary, 'profile', '/tmp/profile'])
Florian Mayer801349e2018-11-29 10:15:25 +0000374 profile_path = None
375 for word in trace_to_text_output.split():
376 if 'heap_profile-' in word:
377 profile_path = word
378 if profile_path is None:
379 print("Could not find trace_to_text output path.", file=sys.stderr)
380 return 1
381
382 profile_files = os.listdir(profile_path)
383 if not profile_files:
384 print("No profiles generated", file=sys.stderr)
Florian Mayer4e6e5902019-06-07 18:36:17 +0100385 print("If this is unexpected, check "
386 "https://docs.perfetto.dev/#/heapprofd?id=troubleshooting.",
387 file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000388 return 1
389
Primiano Tucci834fdc72019-10-04 11:33:44 +0100390 subprocess.check_call(
391 ['gzip'] +
392 [os.path.join(profile_path, x) for x in os.listdir(profile_path)])
Florian Mayer82f43d12019-01-17 14:37:45 +0000393
Primiano Tucci834fdc72019-10-04 11:33:44 +0100394 symlink_path = os.path.join(
395 os.path.dirname(profile_path), "heap_profile-latest")
Florian Mayer91967ee2019-05-10 16:43:50 +0100396 if os.path.lexists(symlink_path):
Florian Mayer31305512019-01-21 17:37:02 +0000397 os.unlink(symlink_path)
Florian Mayer82f43d12019-01-17 14:37:45 +0000398 os.symlink(profile_path, symlink_path)
Florian Mayer92c80d82019-09-25 14:00:01 +0100399 shutil.copyfile('/tmp/profile', os.path.join(profile_path, 'raw-trace'))
Florian Mayer82f43d12019-01-17 14:37:45 +0000400
401 print("Wrote profiles to {} (symlink {})".format(profile_path, symlink_path))
Florian Mayer801349e2018-11-29 10:15:25 +0000402 print("These can be viewed using pprof. Googlers: head to pprof/ and "
403 "upload them.")
404
405
406if __name__ == '__main__':
407 sys.exit(main(sys.argv))