blob: 3a3f9eb7938057a5798713841d5ecb09aa7f0a5e [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 Mayer11341e82019-01-31 11:15:16 +000033 'linux': '4e52b07b2f6258643d16610ae1aae8ac73063624',
34 'mac': '0893f2892f519c6c48458bbc34a61dbed50c20a5',
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
40def check_hash(file_name, sha_value):
41 with open(file_name, 'rb') as fd:
42 # TODO(fmayer): Chunking.
43 file_hash = hashlib.sha1(fd.read()).hexdigest()
44 return file_hash == sha_value
45
46
47def load_trace_to_text(platform):
48 sha_value = TRACE_TO_TEXT_SHAS[platform]
49 file_name = 'trace_to_text-' + platform + '-' + sha_value
50 local_file = os.path.join(TRACE_TO_TEXT_PATH, file_name)
51
52 if os.path.exists(local_file):
53 if not check_hash(local_file, sha_value):
54 os.remove(local_file)
55 else:
56 return local_file
57
58 url = TRACE_TO_TEXT_BASE_URL + file_name
59 urllib.urlretrieve(url, local_file)
60 if not check_hash(local_file, sha_value):
61 os.remove(local_file)
62 raise ValueError("Invalid signature.")
63 os.chmod(local_file, 0o755)
64 return local_file
65
66
67NULL = open('/dev/null', 'r')
68
69CFG_IDENT = ' '
70CFG='''buffers {{
71 size_kb: 32768
72}}
73
74data_sources {{
75 config {{
76 name: "android.heapprofd"
77 heapprofd_config {{
78
79 all: {all}
80 sampling_interval_bytes: {interval}
81{target_cfg}
Florian Mayera8312c72019-01-31 13:50:22 +000082{continuous_dump_cfg}
Florian Mayer801349e2018-11-29 10:15:25 +000083 }}
84 }}
85}}
86
87duration_ms: {duration}
88'''
89
Florian Mayera8312c72019-01-31 13:50:22 +000090CONTINUOUS_DUMP = """
91 continuous_dump_config {{
92 dump_phase_ms: 0
93 dump_interval_ms: {dump_interval}
94 }}
95"""
96
Florian Mayer801349e2018-11-29 10:15:25 +000097PERFETTO_CMD=('CFG=\'{}\'; echo ${{CFG}} | '
Florian Mayereed89742018-12-05 10:56:22 +000098 'perfetto --txt -c - -o /data/misc/perfetto-traces/profile -d')
Florian Mayer801349e2018-11-29 10:15:25 +000099IS_INTERRUPTED = False
100def sigint_handler(sig, frame):
101 global IS_INTERRUPTED
102 IS_INTERRUPTED = True
103
104
Florian Mayer801349e2018-11-29 10:15:25 +0000105def main(argv):
106 parser = argparse.ArgumentParser()
107 parser.add_argument("-i", "--interval", help="Sampling interval. "
108 "Default 128000 (128kB)", type=int, default=128000)
109 parser.add_argument("-d", "--duration", help="Duration of profile (ms). "
Florian Mayer591fe492019-01-28 16:49:21 +0000110 "Default 7 days", type=int, default=604800000)
Florian Mayer801349e2018-11-29 10:15:25 +0000111 parser.add_argument("-a", "--all", help="Profile the whole system",
112 action='store_true')
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000113 parser.add_argument("--no-start", help="Do not start heapprofd",
114 action='store_true')
Florian Mayer801349e2018-11-29 10:15:25 +0000115 parser.add_argument("-p", "--pid", help="PIDs to profile", nargs='+',
116 type=int)
117 parser.add_argument("-n", "--name", help="Process names to profile",
118 nargs='+')
119 parser.add_argument("-t", "--trace-to-text-binary",
120 help="Path to local trace to text. For debugging.")
Florian Mayera8312c72019-01-31 13:50:22 +0000121 parser.add_argument("-c", "--continuous-dump",
122 help="Dump interval in ms. 0 to disable continuous dump.",
123 type=int, default=0)
Florian Mayer6ae95262018-12-06 16:10:29 +0000124 parser.add_argument("--disable-selinux", action="store_true",
125 help="Disable SELinux enforcement for duration of "
126 "profile")
Florian Mayer801349e2018-11-29 10:15:25 +0000127
128 args = parser.parse_args()
129
130 fail = False
131 if args.all is None and args.pid is None and args.name is None:
132 print("FATAL: Neither --all nor PID nor NAME given.", file=sys.stderr)
133 fail = True
134 if args.duration is None:
135 print("FATAL: No duration given.", file=sys.stderr)
136 fail = True
137 if args.interval is None:
138 print("FATAL: No interval given.", file=sys.stderr)
139 fail = True
140 if fail:
141 parser.print_help()
142 return 1
143 target_cfg = ""
144 if args.pid:
145 for pid in args.pid:
146 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
147 if args.name:
148 for name in args.name:
149 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
150
151 trace_to_text_binary = args.trace_to_text_binary
152 if trace_to_text_binary is None:
153 platform = None
154 if sys.platform.startswith('linux'):
155 platform = 'linux'
156 elif sys.platform.startswith('darwin'):
157 platform = 'mac'
158 else:
159 print("Invalid platform: {}".format(sys.platform), file=sys.stderr)
Florian Mayerb6279632018-11-29 13:31:49 +0000160 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000161
162 trace_to_text_binary = load_trace_to_text(platform)
163
Florian Mayera8312c72019-01-31 13:50:22 +0000164 continuous_dump_cfg = ""
165 if args.continuous_dump:
166 continuous_dump_cfg = CONTINUOUS_DUMP.format(
167 dump_interval=args.continuous_dump)
Florian Mayer801349e2018-11-29 10:15:25 +0000168 cfg = CFG.format(all=str(args.all == True).lower(), interval=args.interval,
Florian Mayera8312c72019-01-31 13:50:22 +0000169 duration=args.duration, target_cfg=target_cfg,
170 continuous_dump_cfg=continuous_dump_cfg)
Florian Mayer801349e2018-11-29 10:15:25 +0000171
Florian Mayer6ae95262018-12-06 16:10:29 +0000172 if args.disable_selinux:
173 enforcing = subprocess.check_output(['adb', 'shell', 'getenforce'])
174 atexit.register(subprocess.check_call,
175 ['adb', 'shell', 'su root setenforce %s' % enforcing])
176 subprocess.check_call(['adb', 'shell', 'su root setenforce 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000177
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000178 if not args.no_start:
179 atexit.register(subprocess.check_call,
180 ['adb', 'shell', 'su root stop heapprofd'])
181 subprocess.check_call(['adb', 'shell', 'su root start heapprofd'])
Florian Mayer801349e2018-11-29 10:15:25 +0000182
183 perfetto_pid = subprocess.check_output(
184 ['adb', 'exec-out', PERFETTO_CMD.format(cfg)]).strip()
185
186 old_handler = signal.signal(signal.SIGINT, sigint_handler)
187 print("Profiling active. Press Ctrl+C to terminate.")
188 exists = True
189 while exists and not IS_INTERRUPTED:
190 exists = subprocess.call(
191 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
192 time.sleep(1)
193 signal.signal(signal.SIGINT, old_handler)
194 if IS_INTERRUPTED:
195 # Not check_call because it could have existed in the meantime.
Florian Mayer85969b92019-01-23 17:23:16 +0000196 subprocess.call(['adb', 'shell', 'kill', '-INT', perfetto_pid])
Florian Mayer801349e2018-11-29 10:15:25 +0000197
Florian Mayerddbe31e2018-11-30 14:49:30 +0000198 # Wait for perfetto cmd to return.
199 while exists:
200 exists = subprocess.call(
201 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
202 time.sleep(1)
203
Florian Mayer801349e2018-11-29 10:15:25 +0000204 subprocess.check_call(['adb', 'pull', '/data/misc/perfetto-traces/profile',
205 '/tmp/profile'], stdout=NULL)
206 trace_to_text_output = subprocess.check_output(
207 [trace_to_text_binary, 'profile', '/tmp/profile'],
208 stderr=NULL)
209 profile_path = None
210 for word in trace_to_text_output.split():
211 if 'heap_profile-' in word:
212 profile_path = word
213 if profile_path is None:
214 print("Could not find trace_to_text output path.", file=sys.stderr)
215 return 1
216
217 profile_files = os.listdir(profile_path)
218 if not profile_files:
219 print("No profiles generated", file=sys.stderr)
220 return 1
221
222 subprocess.check_call(['gzip'] + [os.path.join(profile_path, x) for x in
223 os.listdir(profile_path)])
Florian Mayer82f43d12019-01-17 14:37:45 +0000224
225 symlink_path = os.path.join(os.path.dirname(profile_path),
226 "heap_profile-latest")
Florian Mayer31305512019-01-21 17:37:02 +0000227 if os.path.exists(symlink_path):
228 os.unlink(symlink_path)
Florian Mayer82f43d12019-01-17 14:37:45 +0000229 os.symlink(profile_path, symlink_path)
230
231 print("Wrote profiles to {} (symlink {})".format(profile_path, symlink_path))
Florian Mayer801349e2018-11-29 10:15:25 +0000232 print("These can be viewed using pprof. Googlers: head to pprof/ and "
233 "upload them.")
234
235
236if __name__ == '__main__':
237 sys.exit(main(sys.argv))