blob: 09a6911aff6cac7491687edc6533ce1326f47a5f [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
25import signal
26import subprocess
27import sys
28import tempfile
29import time
30import urllib
31
32TRACE_TO_TEXT_SHAS = {
Ryan Savitskiee933072019-06-25 18:59:28 +010033 'linux': 'b91fd044422c5276f314728dca52a1d1cf43df69',
34 'mac': 'd00c9ba443c93c18ed9e712d3e699ddda72a8bd8',
Florian Mayer801349e2018-11-29 10:15:25 +000035}
36TRACE_TO_TEXT_PATH = tempfile.gettempdir()
37TRACE_TO_TEXT_BASE_URL = (
38 'https://storage.googleapis.com/perfetto/')
39
Florian Mayerbd0a62a2019-04-10 11:09:21 +010040NULL = open(os.devnull)
41NOOUT = {
42 'stdout': NULL,
43 'stderr': NULL,
44}
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
Florian Mayerc8b28692019-05-16 17:03:21 +010073PACKAGES_LIST_CFG='''data_sources {
74 config {
Florian Mayerfe4361d2019-05-14 11:54:00 +010075 name: "android.packages_list"
Florian Mayerc8b28692019-05-16 17:03:21 +010076 }
77}
Florian Mayerfe4361d2019-05-14 11:54:00 +010078'''
79
Florian Mayer801349e2018-11-29 10:15:25 +000080
Florian Mayer801349e2018-11-29 10:15:25 +000081CFG_IDENT = ' '
82CFG='''buffers {{
83 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
Florian Mayerbb3b6822019-03-08 17:08:59 +0000111PERFETTO_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
115def sigint_handler(sig, frame):
116 global IS_INTERRUPTED
117 IS_INTERRUPTED = True
118
119
Florian Mayer801349e2018-11-29 10:15:25 +0000120def main(argv):
121 parser = argparse.ArgumentParser()
122 parser.add_argument("-i", "--interval", help="Sampling interval. "
Florian Mayer607c1bc2019-02-01 11:04:58 +0000123 "Default 4096 (4KiB)", type=int, default=4096)
Florian Mayer801349e2018-11-29 10:15:25 +0000124 parser.add_argument("-d", "--duration", help="Duration of profile (ms). "
Florian Mayer0eee91b2019-05-10 10:36:16 +0100125 "Default 7 days.", type=int, default=604800000)
126 parser.add_argument("--no-start", help="Do not start heapprofd.",
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000127 action='store_true')
Florian Mayer0eee91b2019-05-10 10:36:16 +0100128 parser.add_argument("-p", "--pid", help="Comma-separated list of PIDs to "
129 "profile.", metavar="PIDS")
130 parser.add_argument("-n", "--name", help="Comma-separated list of process "
131 "names to profile.", metavar="NAMES")
Florian Mayera8312c72019-01-31 13:50:22 +0000132 parser.add_argument("-c", "--continuous-dump",
133 help="Dump interval in ms. 0 to disable continuous dump.",
134 type=int, default=0)
Florian Mayer6ae95262018-12-06 16:10:29 +0000135 parser.add_argument("--disable-selinux", action="store_true",
136 help="Disable SELinux enforcement for duration of "
Florian Mayer0eee91b2019-05-10 10:36:16 +0100137 "profile.")
Florian Mayerfe4361d2019-05-14 11:54:00 +0100138 parser.add_argument("--no-versions", action="store_true",
139 help="Do not get version information about APKs.")
Florian Mayer400e4432019-05-29 11:53:20 +0100140 parser.add_argument("--no-running", action="store_true",
141 help="Do not target already running processes.")
142 parser.add_argument("--no-startup", action="store_true",
143 help="Do not target processes that start during "
144 "the profile.")
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700145 parser.add_argument("--shmem-size", help="Size of buffer between client and "
146 "heapprofd. Default 8MiB. Needs to be a power of two "
147 "multiple of 4096, at least 8192.", type=int,
148 default=8 * 1048576)
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100149 parser.add_argument("--block-client", help="When buffer is full, block the "
Florian Mayer1a17b682019-05-09 12:02:45 +0100150 "client to wait for buffer space. Use with caution as "
Florian Mayer0eee91b2019-05-10 10:36:16 +0100151 "this can significantly slow down the client.",
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100152 action="store_true")
Florian Mayer7142c7c2019-05-20 18:11:41 +0100153 parser.add_argument("--idle-allocations", help="Keep track of how many "
Florian Mayer4c19b692019-07-15 16:58:38 +0100154 "bytes were unused since the last dump, per "
Florian Mayer7142c7c2019-05-20 18:11:41 +0100155 "callstack", action="store_true")
Florian Mayer8707d4d2019-07-16 11:17:46 +0100156 parser.add_argument("--dump-at-max", help="Dump the maximum memory usage"
157 "rather than at the time of the dump.",
158 action="store_true")
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100159 parser.add_argument("--simpleperf", action="store_true",
160 help="Get simpleperf profile of heapprofd. This is "
161 "only for heapprofd development.")
Florian Mayer0eee91b2019-05-10 10:36:16 +0100162 parser.add_argument("--trace-to-text-binary",
163 help="Path to local trace to text. For debugging.")
Florian Mayerfe4361d2019-05-14 11:54:00 +0100164 parser.add_argument("--print-config", action="store_true",
165 help="Print config instead of running. For debugging.")
Florian Mayer0eee91b2019-05-10 10:36:16 +0100166
Florian Mayer801349e2018-11-29 10:15:25 +0000167 args = parser.parse_args()
168
169 fail = False
Florian Mayera774cb72019-04-29 14:20:43 +0100170 if args.pid is None and args.name is None:
171 print("FATAL: Neither PID nor NAME given.", file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000172 fail = True
173 if args.duration is None:
174 print("FATAL: No duration given.", file=sys.stderr)
175 fail = True
176 if args.interval is None:
177 print("FATAL: No interval given.", file=sys.stderr)
178 fail = True
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700179 if args.shmem_size % 4096:
180 print("FATAL: shmem-size is not a multiple of 4096.", file=sys.stderr)
181 fail = True
182 if args.shmem_size < 8192:
183 print("FATAL: shmem-size is less than 8192.", file=sys.stderr)
184 fail = True
185 if args.shmem_size & (args.shmem_size - 1):
186 print("FATAL: shmem-size is not a power of two.", file=sys.stderr)
187 fail = True
Florian Mayer0eee91b2019-05-10 10:36:16 +0100188
Florian Mayer801349e2018-11-29 10:15:25 +0000189 target_cfg = ""
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100190 if args.block_client:
191 target_cfg += "block_client: true\n"
Florian Mayer7142c7c2019-05-20 18:11:41 +0100192 if args.idle_allocations:
193 target_cfg += "idle_allocations: true\n"
Florian Mayer400e4432019-05-29 11:53:20 +0100194 if args.no_startup:
195 target_cfg += "no_startup: true\n"
196 if args.no_running:
197 target_cfg += "no_running: true\n"
Florian Mayer8707d4d2019-07-16 11:17:46 +0100198 if args.dump_at_max:
199 target_cfg += "dump_at_max: true\n"
Florian Mayer801349e2018-11-29 10:15:25 +0000200 if args.pid:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100201 for pid in args.pid.split(','):
202 try:
203 pid = int(pid)
204 except ValueError:
205 print("FATAL: invalid PID %s" % pid, file=sys.stderr)
206 fail = True
Florian Mayer801349e2018-11-29 10:15:25 +0000207 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
208 if args.name:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100209 for name in args.name.split(','):
Florian Mayer801349e2018-11-29 10:15:25 +0000210 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
211
Florian Mayer0eee91b2019-05-10 10:36:16 +0100212 if fail:
213 parser.print_help()
214 return 1
215
Florian Mayer801349e2018-11-29 10:15:25 +0000216 trace_to_text_binary = args.trace_to_text_binary
217 if trace_to_text_binary is None:
218 platform = None
219 if sys.platform.startswith('linux'):
220 platform = 'linux'
221 elif sys.platform.startswith('darwin'):
222 platform = 'mac'
223 else:
224 print("Invalid platform: {}".format(sys.platform), file=sys.stderr)
Florian Mayerb6279632018-11-29 13:31:49 +0000225 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000226
227 trace_to_text_binary = load_trace_to_text(platform)
228
Florian Mayera8312c72019-01-31 13:50:22 +0000229 continuous_dump_cfg = ""
230 if args.continuous_dump:
231 continuous_dump_cfg = CONTINUOUS_DUMP.format(
232 dump_interval=args.continuous_dump)
Florian Mayera774cb72019-04-29 14:20:43 +0100233 cfg = CFG.format(interval=args.interval,
Florian Mayera8312c72019-01-31 13:50:22 +0000234 duration=args.duration, target_cfg=target_cfg,
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700235 continuous_dump_cfg=continuous_dump_cfg,
236 shmem_size=args.shmem_size)
Florian Mayerfe4361d2019-05-14 11:54:00 +0100237 if not args.no_versions:
238 cfg += PACKAGES_LIST_CFG
239
240 if args.print_config:
241 print(cfg)
242 return 0
Florian Mayer801349e2018-11-29 10:15:25 +0000243
Florian Mayer6ae95262018-12-06 16:10:29 +0000244 if args.disable_selinux:
245 enforcing = subprocess.check_output(['adb', 'shell', 'getenforce'])
246 atexit.register(subprocess.check_call,
247 ['adb', 'shell', 'su root setenforce %s' % enforcing])
248 subprocess.check_call(['adb', 'shell', 'su root setenforce 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000249
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000250 if not args.no_start:
Florian Mayer75266d52019-02-01 18:09:43 +0000251 heapprofd_prop = subprocess.check_output(
252 ['adb', 'shell', 'getprop persist.heapprofd.enable'])
253 if heapprofd_prop.strip() != '1':
254 subprocess.check_call(
255 ['adb', 'shell', 'setprop persist.heapprofd.enable 1'])
256 atexit.register(subprocess.check_call,
257 ['adb', 'shell', 'setprop persist.heapprofd.enable 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000258
Florian Mayerbb3b6822019-03-08 17:08:59 +0000259 user = subprocess.check_output(['adb', 'shell', 'whoami']).strip()
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100260
261 if args.simpleperf:
262 subprocess.check_call(
263 ['adb', 'shell',
264 'mkdir -p /data/local/tmp/heapprofd_profile && '
265 'cd /data/local/tmp/heapprofd_profile &&'
266 '(nohup simpleperf record -g -p $(pgrep heapprofd) 2>&1 &) '
267 '> /dev/null'])
268
Florian Mayer801349e2018-11-29 10:15:25 +0000269 perfetto_pid = subprocess.check_output(
Florian Mayerbb3b6822019-03-08 17:08:59 +0000270 ['adb', 'exec-out', PERFETTO_CMD.format(cfg=cfg, user=user)]).strip()
Florian Mayer35647422019-03-07 16:28:10 +0000271 try:
272 int(perfetto_pid.strip())
273 except ValueError:
274 print("Failed to invoke perfetto: {}".format(perfetto_pid),
275 file=sys.stderr)
276 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000277
278 old_handler = signal.signal(signal.SIGINT, sigint_handler)
279 print("Profiling active. Press Ctrl+C to terminate.")
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100280 print("You may disconnect your device.")
Florian Mayer801349e2018-11-29 10:15:25 +0000281 exists = True
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100282 device_connected = True
283 while not device_connected or (exists and not IS_INTERRUPTED):
Florian Mayer801349e2018-11-29 10:15:25 +0000284 exists = subprocess.call(
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100285 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)],
286 **NOOUT) == 0
287 device_connected = subprocess.call(['adb', 'shell', 'true'], **NOOUT) == 0
Florian Mayer801349e2018-11-29 10:15:25 +0000288 time.sleep(1)
289 signal.signal(signal.SIGINT, old_handler)
290 if IS_INTERRUPTED:
291 # Not check_call because it could have existed in the meantime.
Florian Mayer85969b92019-01-23 17:23:16 +0000292 subprocess.call(['adb', 'shell', 'kill', '-INT', perfetto_pid])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100293 if args.simpleperf:
294 subprocess.check_call(['adb', 'shell', 'killall', '-INT', 'simpleperf'])
295 print("Waiting for simpleperf to exit.")
296 while subprocess.call(
297 ['adb', 'shell', '[ -f /proc/$(pgrep simpleperf)/exe ]'],
298 **NOOUT) == 0:
299 time.sleep(1)
300 subprocess.check_call(['adb', 'pull', '/data/local/tmp/heapprofd_profile',
301 '/tmp'])
302 print("Pulled simpleperf profile to /tmp/heapprofd_profile")
Florian Mayer801349e2018-11-29 10:15:25 +0000303
Florian Mayerddbe31e2018-11-30 14:49:30 +0000304 # Wait for perfetto cmd to return.
305 while exists:
306 exists = subprocess.call(
307 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
308 time.sleep(1)
309
Florian Mayerbb3b6822019-03-08 17:08:59 +0000310 subprocess.check_call(['adb', 'pull',
311 '/data/misc/perfetto-traces/profile-{}'.format(user),
Florian Mayer801349e2018-11-29 10:15:25 +0000312 '/tmp/profile'], stdout=NULL)
313 trace_to_text_output = subprocess.check_output(
Florian Mayer6fc484e2019-04-10 16:07:54 +0100314 [trace_to_text_binary, 'profile', '/tmp/profile'])
Florian Mayer801349e2018-11-29 10:15:25 +0000315 profile_path = None
316 for word in trace_to_text_output.split():
317 if 'heap_profile-' in word:
318 profile_path = word
319 if profile_path is None:
320 print("Could not find trace_to_text output path.", file=sys.stderr)
321 return 1
322
323 profile_files = os.listdir(profile_path)
324 if not profile_files:
325 print("No profiles generated", file=sys.stderr)
Florian Mayer4e6e5902019-06-07 18:36:17 +0100326 print("If this is unexpected, check "
327 "https://docs.perfetto.dev/#/heapprofd?id=troubleshooting.",
328 file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000329 return 1
330
331 subprocess.check_call(['gzip'] + [os.path.join(profile_path, x) for x in
332 os.listdir(profile_path)])
Florian Mayer82f43d12019-01-17 14:37:45 +0000333
334 symlink_path = os.path.join(os.path.dirname(profile_path),
335 "heap_profile-latest")
Florian Mayer91967ee2019-05-10 16:43:50 +0100336 if os.path.lexists(symlink_path):
Florian Mayer31305512019-01-21 17:37:02 +0000337 os.unlink(symlink_path)
Florian Mayer82f43d12019-01-17 14:37:45 +0000338 os.symlink(profile_path, symlink_path)
339
340 print("Wrote profiles to {} (symlink {})".format(profile_path, symlink_path))
Florian Mayer801349e2018-11-29 10:15:25 +0000341 print("These can be viewed using pprof. Googlers: head to pprof/ and "
342 "upload them.")
343
344
345if __name__ == '__main__':
346 sys.exit(main(sys.argv))