blob: e1e7d723fdb4dabe9761fdf967191cb92d58936d [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 = {
Florian Mayer854d22f2019-04-17 15:39:47 +010033 'linux': 'a8171d85c5964ccafe457142dbb7df68ca8da543',
34 'mac': '268c2fc096039566979d16c1a7a99eabef0d9682',
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 Mayer91b3c6d2019-04-10 13:44:37 -0700140 parser.add_argument("--shmem-size", help="Size of buffer between client and "
141 "heapprofd. Default 8MiB. Needs to be a power of two "
142 "multiple of 4096, at least 8192.", type=int,
143 default=8 * 1048576)
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100144 parser.add_argument("--block-client", help="When buffer is full, block the "
Florian Mayer1a17b682019-05-09 12:02:45 +0100145 "client to wait for buffer space. Use with caution as "
Florian Mayer0eee91b2019-05-10 10:36:16 +0100146 "this can significantly slow down the client.",
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100147 action="store_true")
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100148 parser.add_argument("--simpleperf", action="store_true",
149 help="Get simpleperf profile of heapprofd. This is "
150 "only for heapprofd development.")
Florian Mayer0eee91b2019-05-10 10:36:16 +0100151 parser.add_argument("--trace-to-text-binary",
152 help="Path to local trace to text. For debugging.")
Florian Mayerfe4361d2019-05-14 11:54:00 +0100153 parser.add_argument("--print-config", action="store_true",
154 help="Print config instead of running. For debugging.")
Florian Mayer0eee91b2019-05-10 10:36:16 +0100155
Florian Mayer801349e2018-11-29 10:15:25 +0000156 args = parser.parse_args()
157
158 fail = False
Florian Mayera774cb72019-04-29 14:20:43 +0100159 if args.pid is None and args.name is None:
160 print("FATAL: Neither PID nor NAME given.", file=sys.stderr)
Florian Mayer801349e2018-11-29 10:15:25 +0000161 fail = True
162 if args.duration is None:
163 print("FATAL: No duration given.", file=sys.stderr)
164 fail = True
165 if args.interval is None:
166 print("FATAL: No interval given.", file=sys.stderr)
167 fail = True
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700168 if args.shmem_size % 4096:
169 print("FATAL: shmem-size is not a multiple of 4096.", file=sys.stderr)
170 fail = True
171 if args.shmem_size < 8192:
172 print("FATAL: shmem-size is less than 8192.", file=sys.stderr)
173 fail = True
174 if args.shmem_size & (args.shmem_size - 1):
175 print("FATAL: shmem-size is not a power of two.", file=sys.stderr)
176 fail = True
Florian Mayer0eee91b2019-05-10 10:36:16 +0100177
Florian Mayer801349e2018-11-29 10:15:25 +0000178 target_cfg = ""
Florian Mayerd6bdb6f2019-05-03 17:53:58 +0100179 if args.block_client:
180 target_cfg += "block_client: true\n"
Florian Mayer801349e2018-11-29 10:15:25 +0000181 if args.pid:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100182 for pid in args.pid.split(','):
183 try:
184 pid = int(pid)
185 except ValueError:
186 print("FATAL: invalid PID %s" % pid, file=sys.stderr)
187 fail = True
Florian Mayer801349e2018-11-29 10:15:25 +0000188 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
189 if args.name:
Florian Mayer0eee91b2019-05-10 10:36:16 +0100190 for name in args.name.split(','):
Florian Mayer801349e2018-11-29 10:15:25 +0000191 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
192
Florian Mayer0eee91b2019-05-10 10:36:16 +0100193 if fail:
194 parser.print_help()
195 return 1
196
Florian Mayer801349e2018-11-29 10:15:25 +0000197 trace_to_text_binary = args.trace_to_text_binary
198 if trace_to_text_binary is None:
199 platform = None
200 if sys.platform.startswith('linux'):
201 platform = 'linux'
202 elif sys.platform.startswith('darwin'):
203 platform = 'mac'
204 else:
205 print("Invalid platform: {}".format(sys.platform), file=sys.stderr)
Florian Mayerb6279632018-11-29 13:31:49 +0000206 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000207
208 trace_to_text_binary = load_trace_to_text(platform)
209
Florian Mayera8312c72019-01-31 13:50:22 +0000210 continuous_dump_cfg = ""
211 if args.continuous_dump:
212 continuous_dump_cfg = CONTINUOUS_DUMP.format(
213 dump_interval=args.continuous_dump)
Florian Mayera774cb72019-04-29 14:20:43 +0100214 cfg = CFG.format(interval=args.interval,
Florian Mayera8312c72019-01-31 13:50:22 +0000215 duration=args.duration, target_cfg=target_cfg,
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700216 continuous_dump_cfg=continuous_dump_cfg,
217 shmem_size=args.shmem_size)
Florian Mayerfe4361d2019-05-14 11:54:00 +0100218 if not args.no_versions:
219 cfg += PACKAGES_LIST_CFG
220
221 if args.print_config:
222 print(cfg)
223 return 0
Florian Mayer801349e2018-11-29 10:15:25 +0000224
Florian Mayer6ae95262018-12-06 16:10:29 +0000225 if args.disable_selinux:
226 enforcing = subprocess.check_output(['adb', 'shell', 'getenforce'])
227 atexit.register(subprocess.check_call,
228 ['adb', 'shell', 'su root setenforce %s' % enforcing])
229 subprocess.check_call(['adb', 'shell', 'su root setenforce 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000230
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000231 if not args.no_start:
Florian Mayer75266d52019-02-01 18:09:43 +0000232 heapprofd_prop = subprocess.check_output(
233 ['adb', 'shell', 'getprop persist.heapprofd.enable'])
234 if heapprofd_prop.strip() != '1':
235 subprocess.check_call(
236 ['adb', 'shell', 'setprop persist.heapprofd.enable 1'])
237 atexit.register(subprocess.check_call,
238 ['adb', 'shell', 'setprop persist.heapprofd.enable 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000239
Florian Mayerbb3b6822019-03-08 17:08:59 +0000240 user = subprocess.check_output(['adb', 'shell', 'whoami']).strip()
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100241
242 if args.simpleperf:
243 subprocess.check_call(
244 ['adb', 'shell',
245 'mkdir -p /data/local/tmp/heapprofd_profile && '
246 'cd /data/local/tmp/heapprofd_profile &&'
247 '(nohup simpleperf record -g -p $(pgrep heapprofd) 2>&1 &) '
248 '> /dev/null'])
249
Florian Mayer801349e2018-11-29 10:15:25 +0000250 perfetto_pid = subprocess.check_output(
Florian Mayerbb3b6822019-03-08 17:08:59 +0000251 ['adb', 'exec-out', PERFETTO_CMD.format(cfg=cfg, user=user)]).strip()
Florian Mayer35647422019-03-07 16:28:10 +0000252 try:
253 int(perfetto_pid.strip())
254 except ValueError:
255 print("Failed to invoke perfetto: {}".format(perfetto_pid),
256 file=sys.stderr)
257 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000258
259 old_handler = signal.signal(signal.SIGINT, sigint_handler)
260 print("Profiling active. Press Ctrl+C to terminate.")
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100261 print("You may disconnect your device.")
Florian Mayer801349e2018-11-29 10:15:25 +0000262 exists = True
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100263 device_connected = True
264 while not device_connected or (exists and not IS_INTERRUPTED):
Florian Mayer801349e2018-11-29 10:15:25 +0000265 exists = subprocess.call(
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100266 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)],
267 **NOOUT) == 0
268 device_connected = subprocess.call(['adb', 'shell', 'true'], **NOOUT) == 0
Florian Mayer801349e2018-11-29 10:15:25 +0000269 time.sleep(1)
270 signal.signal(signal.SIGINT, old_handler)
271 if IS_INTERRUPTED:
272 # Not check_call because it could have existed in the meantime.
Florian Mayer85969b92019-01-23 17:23:16 +0000273 subprocess.call(['adb', 'shell', 'kill', '-INT', perfetto_pid])
Florian Mayer2b8a3b22019-05-02 18:35:38 +0100274 if args.simpleperf:
275 subprocess.check_call(['adb', 'shell', 'killall', '-INT', 'simpleperf'])
276 print("Waiting for simpleperf to exit.")
277 while subprocess.call(
278 ['adb', 'shell', '[ -f /proc/$(pgrep simpleperf)/exe ]'],
279 **NOOUT) == 0:
280 time.sleep(1)
281 subprocess.check_call(['adb', 'pull', '/data/local/tmp/heapprofd_profile',
282 '/tmp'])
283 print("Pulled simpleperf profile to /tmp/heapprofd_profile")
Florian Mayer801349e2018-11-29 10:15:25 +0000284
Florian Mayerddbe31e2018-11-30 14:49:30 +0000285 # Wait for perfetto cmd to return.
286 while exists:
287 exists = subprocess.call(
288 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
289 time.sleep(1)
290
Florian Mayerbb3b6822019-03-08 17:08:59 +0000291 subprocess.check_call(['adb', 'pull',
292 '/data/misc/perfetto-traces/profile-{}'.format(user),
Florian Mayer801349e2018-11-29 10:15:25 +0000293 '/tmp/profile'], stdout=NULL)
294 trace_to_text_output = subprocess.check_output(
Florian Mayer6fc484e2019-04-10 16:07:54 +0100295 [trace_to_text_binary, 'profile', '/tmp/profile'])
Florian Mayer801349e2018-11-29 10:15:25 +0000296 profile_path = None
297 for word in trace_to_text_output.split():
298 if 'heap_profile-' in word:
299 profile_path = word
300 if profile_path is None:
301 print("Could not find trace_to_text output path.", file=sys.stderr)
302 return 1
303
304 profile_files = os.listdir(profile_path)
305 if not profile_files:
306 print("No profiles generated", file=sys.stderr)
307 return 1
308
309 subprocess.check_call(['gzip'] + [os.path.join(profile_path, x) for x in
310 os.listdir(profile_path)])
Florian Mayer82f43d12019-01-17 14:37:45 +0000311
312 symlink_path = os.path.join(os.path.dirname(profile_path),
313 "heap_profile-latest")
Florian Mayer91967ee2019-05-10 16:43:50 +0100314 if os.path.lexists(symlink_path):
Florian Mayer31305512019-01-21 17:37:02 +0000315 os.unlink(symlink_path)
Florian Mayer82f43d12019-01-17 14:37:45 +0000316 os.symlink(profile_path, symlink_path)
317
318 print("Wrote profiles to {} (symlink {})".format(profile_path, symlink_path))
Florian Mayer801349e2018-11-29 10:15:25 +0000319 print("These can be viewed using pprof. Googlers: head to pprof/ and "
320 "upload them.")
321
322
323if __name__ == '__main__':
324 sys.exit(main(sys.argv))