blob: 5680a689f74ec899fce4ca6ecf97377de00a489a [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 = {
Florian Mayer887948c2019-08-07 11:20:30 +010034 'linux': '74cb40d9413d7ad756e327e09e46a8adde90db92',
35 'mac': '47045bc6abd4f9113969211f37fdd2259b0c1cc3',
Florian Mayer801349e2018-11-29 10:15:25 +000036}
37TRACE_TO_TEXT_PATH = tempfile.gettempdir()
38TRACE_TO_TEXT_BASE_URL = (
39 'https://storage.googleapis.com/perfetto/')
40
Florian Mayerbd0a62a2019-04-10 11:09:21 +010041NULL = open(os.devnull)
42NOOUT = {
43 'stdout': NULL,
44 'stderr': NULL,
45}
46
47
Florian Mayer801349e2018-11-29 10:15:25 +000048def check_hash(file_name, sha_value):
49 with open(file_name, 'rb') as fd:
50 # TODO(fmayer): Chunking.
51 file_hash = hashlib.sha1(fd.read()).hexdigest()
52 return file_hash == sha_value
53
54
55def load_trace_to_text(platform):
56 sha_value = TRACE_TO_TEXT_SHAS[platform]
57 file_name = 'trace_to_text-' + platform + '-' + sha_value
58 local_file = os.path.join(TRACE_TO_TEXT_PATH, file_name)
59
60 if os.path.exists(local_file):
61 if not check_hash(local_file, sha_value):
62 os.remove(local_file)
63 else:
64 return local_file
65
66 url = TRACE_TO_TEXT_BASE_URL + file_name
67 urllib.urlretrieve(url, local_file)
68 if not check_hash(local_file, sha_value):
69 os.remove(local_file)
70 raise ValueError("Invalid signature.")
71 os.chmod(local_file, 0o755)
72 return local_file
73
Florian Mayerc8b28692019-05-16 17:03:21 +010074PACKAGES_LIST_CFG='''data_sources {
75 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 +000081
Florian Mayer801349e2018-11-29 10:15:25 +000082CFG_IDENT = ' '
83CFG='''buffers {{
84 size_kb: 32768
85}}
86
87data_sources {{
88 config {{
89 name: "android.heapprofd"
90 heapprofd_config {{
91
Florian Mayer91b3c6d2019-04-10 13:44:37 -070092 shmem_size_bytes: {shmem_size}
Florian Mayer801349e2018-11-29 10:15:25 +000093 sampling_interval_bytes: {interval}
94{target_cfg}
Florian Mayera8312c72019-01-31 13:50:22 +000095{continuous_dump_cfg}
Florian Mayer801349e2018-11-29 10:15:25 +000096 }}
97 }}
98}}
99
100duration_ms: {duration}
Florian Mayer2aab3162019-05-03 16:02:30 +0100101write_into_file: true
Florian Mayer82610462019-04-16 10:26:07 +0100102flush_timeout_ms: 30000
Florian Mayer801349e2018-11-29 10:15:25 +0000103'''
104
Florian Mayera8312c72019-01-31 13:50:22 +0000105CONTINUOUS_DUMP = """
106 continuous_dump_config {{
107 dump_phase_ms: 0
108 dump_interval_ms: {dump_interval}
109 }}
110"""
111
Florian Mayerbb3b6822019-03-08 17:08:59 +0000112PERFETTO_CMD=('CFG=\'{cfg}\'; echo ${{CFG}} | '
113 'perfetto --txt -c - -o '
114 '/data/misc/perfetto-traces/profile-{user} -d')
Florian Mayer801349e2018-11-29 10:15:25 +0000115IS_INTERRUPTED = False
116def sigint_handler(sig, frame):
117 global IS_INTERRUPTED
118 IS_INTERRUPTED = True
119
120
Florian Mayer801349e2018-11-29 10:15:25 +0000121def main(argv):
122 parser = argparse.ArgumentParser()
123 parser.add_argument("-i", "--interval", help="Sampling interval. "
Florian Mayer607c1bc2019-02-01 11:04:58 +0000124 "Default 4096 (4KiB)", type=int, default=4096)
Florian Mayer801349e2018-11-29 10:15:25 +0000125 parser.add_argument("-d", "--duration", help="Duration of profile (ms). "
Florian Mayer0eee91b2019-05-10 10:36:16 +0100126 "Default 7 days.", type=int, default=604800000)
127 parser.add_argument("--no-start", help="Do not start heapprofd.",
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000128 action='store_true')
Florian Mayer0eee91b2019-05-10 10:36:16 +0100129 parser.add_argument("-p", "--pid", help="Comma-separated list of PIDs to "
130 "profile.", metavar="PIDS")
131 parser.add_argument("-n", "--name", help="Comma-separated list of process "
132 "names to profile.", metavar="NAMES")
Florian Mayera8312c72019-01-31 13:50:22 +0000133 parser.add_argument("-c", "--continuous-dump",
134 help="Dump interval in ms. 0 to disable continuous dump.",
135 type=int, default=0)
Florian Mayer6ae95262018-12-06 16:10:29 +0000136 parser.add_argument("--disable-selinux", action="store_true",
137 help="Disable SELinux enforcement for duration of "
Florian Mayer0eee91b2019-05-10 10:36:16 +0100138 "profile.")
Florian Mayerfe4361d2019-05-14 11:54:00 +0100139 parser.add_argument("--no-versions", action="store_true",
140 help="Do not get version information about APKs.")
Florian Mayer400e4432019-05-29 11:53:20 +0100141 parser.add_argument("--no-running", action="store_true",
142 help="Do not target already running processes.")
143 parser.add_argument("--no-startup", action="store_true",
144 help="Do not target processes that start during "
145 "the profile.")
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700146 parser.add_argument("--shmem-size", help="Size of buffer between client and "
147 "heapprofd. Default 8MiB. Needs to be a power of two "
148 "multiple of 4096, at least 8192.", type=int,
149 default=8 * 1048576)
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100150 parser.add_argument("--block-client", help="When buffer is full, block the "
Florian Mayer1a17b682019-05-09 12:02:45 +0100151 "client to wait for buffer space. Use with caution as "
Florian Mayerf40dedd2019-07-19 13:08:48 +0100152 "this can significantly slow down the client. "
153 "This is the default", action="store_true")
154 parser.add_argument("--no-block-client", help="When buffer is full, stop the "
155 "profile early.", action="store_true")
Florian Mayer7142c7c2019-05-20 18:11:41 +0100156 parser.add_argument("--idle-allocations", help="Keep track of how many "
Florian Mayer4c19b692019-07-15 16:58:38 +0100157 "bytes were unused since the last dump, per "
Florian Mayer7142c7c2019-05-20 18:11:41 +0100158 "callstack", action="store_true")
Florian Mayer8707d4d2019-07-16 11:17:46 +0100159 parser.add_argument("--dump-at-max", help="Dump the maximum memory usage"
160 "rather than at the time of the dump.",
161 action="store_true")
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100162 parser.add_argument("--simpleperf", action="store_true",
163 help="Get simpleperf profile of heapprofd. This is "
164 "only for heapprofd development.")
Florian Mayer0eee91b2019-05-10 10:36:16 +0100165 parser.add_argument("--trace-to-text-binary",
166 help="Path to local trace to text. For debugging.")
Florian Mayerfe4361d2019-05-14 11:54:00 +0100167 parser.add_argument("--print-config", action="store_true",
168 help="Print config instead of running. For debugging.")
Florian Mayer0eee91b2019-05-10 10:36:16 +0100169
Florian Mayer801349e2018-11-29 10:15:25 +0000170 args = parser.parse_args()
171
172 fail = False
Florian Mayerf40dedd2019-07-19 13:08:48 +0100173 if args.block_client and args.no_block_client:
174 print("FATAL: Both block-client and no-block-client given.",
175 file=sys.stderr)
176 fail = True
Florian Mayera774cb72019-04-29 14:20:43 +0100177 if args.pid is None and args.name is None:
178 print("FATAL: Neither PID nor NAME given.", file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000179 fail = True
180 if args.duration is None:
181 print("FATAL: No duration given.", file=sys.stderr)
182 fail = True
183 if args.interval is None:
184 print("FATAL: No interval given.", file=sys.stderr)
185 fail = True
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700186 if args.shmem_size % 4096:
187 print("FATAL: shmem-size is not a multiple of 4096.", file=sys.stderr)
188 fail = True
189 if args.shmem_size < 8192:
190 print("FATAL: shmem-size is less than 8192.", file=sys.stderr)
191 fail = True
192 if args.shmem_size & (args.shmem_size - 1):
193 print("FATAL: shmem-size is not a power of two.", file=sys.stderr)
194 fail = True
Florian Mayer0eee91b2019-05-10 10:36:16 +0100195
Florian Mayer801349e2018-11-29 10:15:25 +0000196 target_cfg = ""
Florian Mayerf40dedd2019-07-19 13:08:48 +0100197 if not args.no_block_client:
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100198 target_cfg += "block_client: true\n"
Florian Mayer7142c7c2019-05-20 18:11:41 +0100199 if args.idle_allocations:
200 target_cfg += "idle_allocations: true\n"
Florian Mayer400e4432019-05-29 11:53:20 +0100201 if args.no_startup:
202 target_cfg += "no_startup: true\n"
203 if args.no_running:
204 target_cfg += "no_running: true\n"
Florian Mayer8707d4d2019-07-16 11:17:46 +0100205 if args.dump_at_max:
206 target_cfg += "dump_at_max: true\n"
Florian Mayer801349e2018-11-29 10:15:25 +0000207 if args.pid:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100208 for pid in args.pid.split(','):
209 try:
210 pid = int(pid)
211 except ValueError:
212 print("FATAL: invalid PID %s" % pid, file=sys.stderr)
213 fail = True
Florian Mayer801349e2018-11-29 10:15:25 +0000214 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
215 if args.name:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100216 for name in args.name.split(','):
Florian Mayer801349e2018-11-29 10:15:25 +0000217 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
218
Florian Mayer0eee91b2019-05-10 10:36:16 +0100219 if fail:
220 parser.print_help()
221 return 1
222
Florian Mayer801349e2018-11-29 10:15:25 +0000223 trace_to_text_binary = args.trace_to_text_binary
224 if trace_to_text_binary is None:
225 platform = None
226 if sys.platform.startswith('linux'):
227 platform = 'linux'
228 elif sys.platform.startswith('darwin'):
229 platform = 'mac'
230 else:
231 print("Invalid platform: {}".format(sys.platform), file=sys.stderr)
Florian Mayerb6279632018-11-29 13:31:49 +0000232 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000233
234 trace_to_text_binary = load_trace_to_text(platform)
235
Florian Mayera8312c72019-01-31 13:50:22 +0000236 continuous_dump_cfg = ""
237 if args.continuous_dump:
238 continuous_dump_cfg = CONTINUOUS_DUMP.format(
239 dump_interval=args.continuous_dump)
Florian Mayera774cb72019-04-29 14:20:43 +0100240 cfg = CFG.format(interval=args.interval,
Florian Mayera8312c72019-01-31 13:50:22 +0000241 duration=args.duration, target_cfg=target_cfg,
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700242 continuous_dump_cfg=continuous_dump_cfg,
243 shmem_size=args.shmem_size)
Florian Mayerfe4361d2019-05-14 11:54:00 +0100244 if not args.no_versions:
245 cfg += PACKAGES_LIST_CFG
246
247 if args.print_config:
248 print(cfg)
249 return 0
Florian Mayer801349e2018-11-29 10:15:25 +0000250
Florian Mayer6ae95262018-12-06 16:10:29 +0000251 if args.disable_selinux:
252 enforcing = subprocess.check_output(['adb', 'shell', 'getenforce'])
253 atexit.register(subprocess.check_call,
254 ['adb', 'shell', 'su root setenforce %s' % enforcing])
255 subprocess.check_call(['adb', 'shell', 'su root setenforce 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000256
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000257 if not args.no_start:
Florian Mayer75266d52019-02-01 18:09:43 +0000258 heapprofd_prop = subprocess.check_output(
259 ['adb', 'shell', 'getprop persist.heapprofd.enable'])
260 if heapprofd_prop.strip() != '1':
261 subprocess.check_call(
262 ['adb', 'shell', 'setprop persist.heapprofd.enable 1'])
263 atexit.register(subprocess.check_call,
264 ['adb', 'shell', 'setprop persist.heapprofd.enable 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000265
Florian Mayerbb3b6822019-03-08 17:08:59 +0000266 user = subprocess.check_output(['adb', 'shell', 'whoami']).strip()
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100267
268 if args.simpleperf:
269 subprocess.check_call(
270 ['adb', 'shell',
271 'mkdir -p /data/local/tmp/heapprofd_profile && '
272 'cd /data/local/tmp/heapprofd_profile &&'
Florian Mayer37c0a5e2019-08-01 10:52:32 +0100273 '(nohup simpleperf record -g -p $(pidof heapprofd) 2>&1 &) '
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100274 '> /dev/null'])
275
Florian Mayer801349e2018-11-29 10:15:25 +0000276 perfetto_pid = subprocess.check_output(
Florian Mayerbb3b6822019-03-08 17:08:59 +0000277 ['adb', 'exec-out', PERFETTO_CMD.format(cfg=cfg, user=user)]).strip()
Florian Mayer35647422019-03-07 16:28:10 +0000278 try:
279 int(perfetto_pid.strip())
280 except ValueError:
281 print("Failed to invoke perfetto: {}".format(perfetto_pid),
282 file=sys.stderr)
283 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000284
285 old_handler = signal.signal(signal.SIGINT, sigint_handler)
286 print("Profiling active. Press Ctrl+C to terminate.")
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100287 print("You may disconnect your device.")
Florian Mayer801349e2018-11-29 10:15:25 +0000288 exists = True
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100289 device_connected = True
290 while not device_connected or (exists and not IS_INTERRUPTED):
Florian Mayer801349e2018-11-29 10:15:25 +0000291 exists = subprocess.call(
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100292 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)],
293 **NOOUT) == 0
294 device_connected = subprocess.call(['adb', 'shell', 'true'], **NOOUT) == 0
Florian Mayer801349e2018-11-29 10:15:25 +0000295 time.sleep(1)
296 signal.signal(signal.SIGINT, old_handler)
297 if IS_INTERRUPTED:
298 # Not check_call because it could have existed in the meantime.
Florian Mayer85969b92019-01-23 17:23:16 +0000299 subprocess.call(['adb', 'shell', 'kill', '-INT', perfetto_pid])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100300 if args.simpleperf:
301 subprocess.check_call(['adb', 'shell', 'killall', '-INT', 'simpleperf'])
302 print("Waiting for simpleperf to exit.")
303 while subprocess.call(
Florian Mayer37c0a5e2019-08-01 10:52:32 +0100304 ['adb', 'shell', '[ -f /proc/$(pidof simpleperf)/exe ]'],
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100305 **NOOUT) == 0:
306 time.sleep(1)
307 subprocess.check_call(['adb', 'pull', '/data/local/tmp/heapprofd_profile',
308 '/tmp'])
309 print("Pulled simpleperf profile to /tmp/heapprofd_profile")
Florian Mayer801349e2018-11-29 10:15:25 +0000310
Florian Mayerddbe31e2018-11-30 14:49:30 +0000311 # Wait for perfetto cmd to return.
312 while exists:
313 exists = subprocess.call(
314 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
315 time.sleep(1)
316
Florian Mayerbb3b6822019-03-08 17:08:59 +0000317 subprocess.check_call(['adb', 'pull',
318 '/data/misc/perfetto-traces/profile-{}'.format(user),
Florian Mayer801349e2018-11-29 10:15:25 +0000319 '/tmp/profile'], stdout=NULL)
320 trace_to_text_output = subprocess.check_output(
Florian Mayer6fc484e2019-04-10 16:07:54 +0100321 [trace_to_text_binary, 'profile', '/tmp/profile'])
Florian Mayer801349e2018-11-29 10:15:25 +0000322 profile_path = None
323 for word in trace_to_text_output.split():
324 if 'heap_profile-' in word:
325 profile_path = word
326 if profile_path is None:
327 print("Could not find trace_to_text output path.", file=sys.stderr)
328 return 1
329
330 profile_files = os.listdir(profile_path)
331 if not profile_files:
332 print("No profiles generated", file=sys.stderr)
Florian Mayer4e6e5902019-06-07 18:36:17 +0100333 print("If this is unexpected, check "
334 "https://docs.perfetto.dev/#/heapprofd?id=troubleshooting.",
335 file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000336 return 1
337
338 subprocess.check_call(['gzip'] + [os.path.join(profile_path, x) for x in
339 os.listdir(profile_path)])
Florian Mayer82f43d12019-01-17 14:37:45 +0000340
341 symlink_path = os.path.join(os.path.dirname(profile_path),
342 "heap_profile-latest")
Florian Mayer91967ee2019-05-10 16:43:50 +0100343 if os.path.lexists(symlink_path):
Florian Mayer31305512019-01-21 17:37:02 +0000344 os.unlink(symlink_path)
Florian Mayer82f43d12019-01-17 14:37:45 +0000345 os.symlink(profile_path, symlink_path)
Florian Mayer92c80d82019-09-25 14:00:01 +0100346 shutil.copyfile('/tmp/profile', os.path.join(profile_path, 'raw-trace'))
Florian Mayer82f43d12019-01-17 14:37:45 +0000347
348 print("Wrote profiles to {} (symlink {})".format(profile_path, symlink_path))
Florian Mayer801349e2018-11-29 10:15:25 +0000349 print("These can be viewed using pprof. Googlers: head to pprof/ and "
350 "upload them.")
351
352
353if __name__ == '__main__':
354 sys.exit(main(sys.argv))