blob: 942c807a6e7c4df43acc89a7315d6713a0181423 [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 Mayerb0155492019-02-20 10:39:14 -080033 'linux': '4ab1d18e69bc70e211d27064505ed547aa82f919',
Florian Mayer8ecd6ee2019-02-20 11:32:59 -080034 'mac': '2ba325f95c08e8cd5a78e04fa85ee7f2a97c847e',
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
73
Florian Mayer801349e2018-11-29 10:15:25 +000074CFG_IDENT = ' '
75CFG='''buffers {{
76 size_kb: 32768
77}}
78
79data_sources {{
80 config {{
Florian Mayere21646d2019-04-02 16:39:16 +010081 name: "android.packages_list"
82 }}
83}}
84
85data_sources {{
86 config {{
Florian Mayer801349e2018-11-29 10:15:25 +000087 name: "android.heapprofd"
88 heapprofd_config {{
89
90 all: {all}
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}
100'''
101
Florian Mayera8312c72019-01-31 13:50:22 +0000102CONTINUOUS_DUMP = """
103 continuous_dump_config {{
104 dump_phase_ms: 0
105 dump_interval_ms: {dump_interval}
106 }}
107"""
108
Florian Mayerbb3b6822019-03-08 17:08:59 +0000109PERFETTO_CMD=('CFG=\'{cfg}\'; echo ${{CFG}} | '
110 'perfetto --txt -c - -o '
111 '/data/misc/perfetto-traces/profile-{user} -d')
Florian Mayer801349e2018-11-29 10:15:25 +0000112IS_INTERRUPTED = False
113def sigint_handler(sig, frame):
114 global IS_INTERRUPTED
115 IS_INTERRUPTED = True
116
117
Florian Mayer801349e2018-11-29 10:15:25 +0000118def main(argv):
119 parser = argparse.ArgumentParser()
120 parser.add_argument("-i", "--interval", help="Sampling interval. "
Florian Mayer607c1bc2019-02-01 11:04:58 +0000121 "Default 4096 (4KiB)", type=int, default=4096)
Florian Mayer801349e2018-11-29 10:15:25 +0000122 parser.add_argument("-d", "--duration", help="Duration of profile (ms). "
Florian Mayer591fe492019-01-28 16:49:21 +0000123 "Default 7 days", type=int, default=604800000)
Florian Mayer801349e2018-11-29 10:15:25 +0000124 parser.add_argument("-a", "--all", help="Profile the whole system",
125 action='store_true')
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000126 parser.add_argument("--no-start", help="Do not start heapprofd",
127 action='store_true')
Florian Mayer801349e2018-11-29 10:15:25 +0000128 parser.add_argument("-p", "--pid", help="PIDs to profile", nargs='+',
129 type=int)
130 parser.add_argument("-n", "--name", help="Process names to profile",
131 nargs='+')
132 parser.add_argument("-t", "--trace-to-text-binary",
133 help="Path to local trace to text. For debugging.")
Florian Mayera8312c72019-01-31 13:50:22 +0000134 parser.add_argument("-c", "--continuous-dump",
135 help="Dump interval in ms. 0 to disable continuous dump.",
136 type=int, default=0)
Florian Mayer6ae95262018-12-06 16:10:29 +0000137 parser.add_argument("--disable-selinux", action="store_true",
138 help="Disable SELinux enforcement for duration of "
139 "profile")
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 Mayer801349e2018-11-29 10:15:25 +0000144
145 args = parser.parse_args()
146
147 fail = False
148 if args.all is None and args.pid is None and args.name is None:
149 print("FATAL: Neither --all nor PID nor NAME given.", file=sys.stderr)
150 fail = True
151 if args.duration is None:
152 print("FATAL: No duration given.", file=sys.stderr)
153 fail = True
154 if args.interval is None:
155 print("FATAL: No interval given.", file=sys.stderr)
156 fail = True
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700157 if args.shmem_size % 4096:
158 print("FATAL: shmem-size is not a multiple of 4096.", file=sys.stderr)
159 fail = True
160 if args.shmem_size < 8192:
161 print("FATAL: shmem-size is less than 8192.", file=sys.stderr)
162 fail = True
163 if args.shmem_size & (args.shmem_size - 1):
164 print("FATAL: shmem-size is not a power of two.", file=sys.stderr)
165 fail = True
Florian Mayer801349e2018-11-29 10:15:25 +0000166 if fail:
167 parser.print_help()
168 return 1
169 target_cfg = ""
170 if args.pid:
171 for pid in args.pid:
172 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
173 if args.name:
174 for name in args.name:
175 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
176
177 trace_to_text_binary = args.trace_to_text_binary
178 if trace_to_text_binary is None:
179 platform = None
180 if sys.platform.startswith('linux'):
181 platform = 'linux'
182 elif sys.platform.startswith('darwin'):
183 platform = 'mac'
184 else:
185 print("Invalid platform: {}".format(sys.platform), file=sys.stderr)
Florian Mayerb6279632018-11-29 13:31:49 +0000186 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000187
188 trace_to_text_binary = load_trace_to_text(platform)
189
Florian Mayera8312c72019-01-31 13:50:22 +0000190 continuous_dump_cfg = ""
191 if args.continuous_dump:
192 continuous_dump_cfg = CONTINUOUS_DUMP.format(
193 dump_interval=args.continuous_dump)
Florian Mayer801349e2018-11-29 10:15:25 +0000194 cfg = CFG.format(all=str(args.all == True).lower(), interval=args.interval,
Florian Mayera8312c72019-01-31 13:50:22 +0000195 duration=args.duration, target_cfg=target_cfg,
Florian Mayer91b3c6d2019-04-10 13:44:37 -0700196 continuous_dump_cfg=continuous_dump_cfg,
197 shmem_size=args.shmem_size)
Florian Mayer801349e2018-11-29 10:15:25 +0000198
Florian Mayer6ae95262018-12-06 16:10:29 +0000199 if args.disable_selinux:
200 enforcing = subprocess.check_output(['adb', 'shell', 'getenforce'])
201 atexit.register(subprocess.check_call,
202 ['adb', 'shell', 'su root setenforce %s' % enforcing])
203 subprocess.check_call(['adb', 'shell', 'su root setenforce 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000204
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000205 if not args.no_start:
Florian Mayer75266d52019-02-01 18:09:43 +0000206 heapprofd_prop = subprocess.check_output(
207 ['adb', 'shell', 'getprop persist.heapprofd.enable'])
208 if heapprofd_prop.strip() != '1':
209 subprocess.check_call(
210 ['adb', 'shell', 'setprop persist.heapprofd.enable 1'])
211 atexit.register(subprocess.check_call,
212 ['adb', 'shell', 'setprop persist.heapprofd.enable 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000213
Florian Mayerbb3b6822019-03-08 17:08:59 +0000214 user = subprocess.check_output(['adb', 'shell', 'whoami']).strip()
Florian Mayer801349e2018-11-29 10:15:25 +0000215 perfetto_pid = subprocess.check_output(
Florian Mayerbb3b6822019-03-08 17:08:59 +0000216 ['adb', 'exec-out', PERFETTO_CMD.format(cfg=cfg, user=user)]).strip()
Florian Mayer35647422019-03-07 16:28:10 +0000217 try:
218 int(perfetto_pid.strip())
219 except ValueError:
220 print("Failed to invoke perfetto: {}".format(perfetto_pid),
221 file=sys.stderr)
222 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000223
224 old_handler = signal.signal(signal.SIGINT, sigint_handler)
225 print("Profiling active. Press Ctrl+C to terminate.")
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100226 print("You may disconnect your device.")
Florian Mayer801349e2018-11-29 10:15:25 +0000227 exists = True
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100228 device_connected = True
229 while not device_connected or (exists and not IS_INTERRUPTED):
Florian Mayer801349e2018-11-29 10:15:25 +0000230 exists = subprocess.call(
Florian Mayerbd0a62a2019-04-10 11:09:21 +0100231 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)],
232 **NOOUT) == 0
233 device_connected = subprocess.call(['adb', 'shell', 'true'], **NOOUT) == 0
Florian Mayer801349e2018-11-29 10:15:25 +0000234 time.sleep(1)
235 signal.signal(signal.SIGINT, old_handler)
236 if IS_INTERRUPTED:
237 # Not check_call because it could have existed in the meantime.
Florian Mayer85969b92019-01-23 17:23:16 +0000238 subprocess.call(['adb', 'shell', 'kill', '-INT', perfetto_pid])
Florian Mayer801349e2018-11-29 10:15:25 +0000239
Florian Mayerddbe31e2018-11-30 14:49:30 +0000240 # Wait for perfetto cmd to return.
241 while exists:
242 exists = subprocess.call(
243 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
244 time.sleep(1)
245
Florian Mayerbb3b6822019-03-08 17:08:59 +0000246 subprocess.check_call(['adb', 'pull',
247 '/data/misc/perfetto-traces/profile-{}'.format(user),
Florian Mayer801349e2018-11-29 10:15:25 +0000248 '/tmp/profile'], stdout=NULL)
249 trace_to_text_output = subprocess.check_output(
Florian Mayer6fc484e2019-04-10 16:07:54 +0100250 [trace_to_text_binary, 'profile', '/tmp/profile'])
Florian Mayer801349e2018-11-29 10:15:25 +0000251 profile_path = None
252 for word in trace_to_text_output.split():
253 if 'heap_profile-' in word:
254 profile_path = word
255 if profile_path is None:
256 print("Could not find trace_to_text output path.", file=sys.stderr)
257 return 1
258
259 profile_files = os.listdir(profile_path)
260 if not profile_files:
261 print("No profiles generated", file=sys.stderr)
262 return 1
263
264 subprocess.check_call(['gzip'] + [os.path.join(profile_path, x) for x in
265 os.listdir(profile_path)])
Florian Mayer82f43d12019-01-17 14:37:45 +0000266
267 symlink_path = os.path.join(os.path.dirname(profile_path),
268 "heap_profile-latest")
Florian Mayer31305512019-01-21 17:37:02 +0000269 if os.path.exists(symlink_path):
270 os.unlink(symlink_path)
Florian Mayer82f43d12019-01-17 14:37:45 +0000271 os.symlink(profile_path, symlink_path)
272
273 print("Wrote profiles to {} (symlink {})".format(profile_path, symlink_path))
Florian Mayer801349e2018-11-29 10:15:25 +0000274 print("These can be viewed using pprof. Googlers: head to pprof/ and "
275 "upload them.")
276
277
278if __name__ == '__main__':
279 sys.exit(main(sys.argv))