blob: 3ef51f288351f779d21834488c9c18deec61b381 [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
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 {{
Florian Mayere21646d2019-04-02 16:39:16 +010076 name: "android.packages_list"
77 }}
78}}
79
80data_sources {{
81 config {{
Florian Mayer801349e2018-11-29 10:15:25 +000082 name: "android.heapprofd"
83 heapprofd_config {{
84
85 all: {all}
86 sampling_interval_bytes: {interval}
87{target_cfg}
Florian Mayera8312c72019-01-31 13:50:22 +000088{continuous_dump_cfg}
Florian Mayer801349e2018-11-29 10:15:25 +000089 }}
90 }}
91}}
92
93duration_ms: {duration}
94'''
95
Florian Mayera8312c72019-01-31 13:50:22 +000096CONTINUOUS_DUMP = """
97 continuous_dump_config {{
98 dump_phase_ms: 0
99 dump_interval_ms: {dump_interval}
100 }}
101"""
102
Florian Mayerbb3b6822019-03-08 17:08:59 +0000103PERFETTO_CMD=('CFG=\'{cfg}\'; echo ${{CFG}} | '
104 'perfetto --txt -c - -o '
105 '/data/misc/perfetto-traces/profile-{user} -d')
Florian Mayer801349e2018-11-29 10:15:25 +0000106IS_INTERRUPTED = False
107def sigint_handler(sig, frame):
108 global IS_INTERRUPTED
109 IS_INTERRUPTED = True
110
111
Florian Mayer801349e2018-11-29 10:15:25 +0000112def main(argv):
113 parser = argparse.ArgumentParser()
114 parser.add_argument("-i", "--interval", help="Sampling interval. "
Florian Mayer607c1bc2019-02-01 11:04:58 +0000115 "Default 4096 (4KiB)", type=int, default=4096)
Florian Mayer801349e2018-11-29 10:15:25 +0000116 parser.add_argument("-d", "--duration", help="Duration of profile (ms). "
Florian Mayer591fe492019-01-28 16:49:21 +0000117 "Default 7 days", type=int, default=604800000)
Florian Mayer801349e2018-11-29 10:15:25 +0000118 parser.add_argument("-a", "--all", help="Profile the whole system",
119 action='store_true')
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000120 parser.add_argument("--no-start", help="Do not start heapprofd",
121 action='store_true')
Florian Mayer801349e2018-11-29 10:15:25 +0000122 parser.add_argument("-p", "--pid", help="PIDs to profile", nargs='+',
123 type=int)
124 parser.add_argument("-n", "--name", help="Process names to profile",
125 nargs='+')
126 parser.add_argument("-t", "--trace-to-text-binary",
127 help="Path to local trace to text. For debugging.")
Florian Mayera8312c72019-01-31 13:50:22 +0000128 parser.add_argument("-c", "--continuous-dump",
129 help="Dump interval in ms. 0 to disable continuous dump.",
130 type=int, default=0)
Florian Mayer6ae95262018-12-06 16:10:29 +0000131 parser.add_argument("--disable-selinux", action="store_true",
132 help="Disable SELinux enforcement for duration of "
133 "profile")
Florian Mayer801349e2018-11-29 10:15:25 +0000134
135 args = parser.parse_args()
136
137 fail = False
138 if args.all is None and args.pid is None and args.name is None:
139 print("FATAL: Neither --all nor PID nor NAME given.", file=sys.stderr)
140 fail = True
141 if args.duration is None:
142 print("FATAL: No duration given.", file=sys.stderr)
143 fail = True
144 if args.interval is None:
145 print("FATAL: No interval given.", file=sys.stderr)
146 fail = True
147 if fail:
148 parser.print_help()
149 return 1
150 target_cfg = ""
151 if args.pid:
152 for pid in args.pid:
153 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
154 if args.name:
155 for name in args.name:
156 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
157
158 trace_to_text_binary = args.trace_to_text_binary
159 if trace_to_text_binary is None:
160 platform = None
161 if sys.platform.startswith('linux'):
162 platform = 'linux'
163 elif sys.platform.startswith('darwin'):
164 platform = 'mac'
165 else:
166 print("Invalid platform: {}".format(sys.platform), file=sys.stderr)
Florian Mayerb6279632018-11-29 13:31:49 +0000167 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000168
169 trace_to_text_binary = load_trace_to_text(platform)
170
Florian Mayera8312c72019-01-31 13:50:22 +0000171 continuous_dump_cfg = ""
172 if args.continuous_dump:
173 continuous_dump_cfg = CONTINUOUS_DUMP.format(
174 dump_interval=args.continuous_dump)
Florian Mayer801349e2018-11-29 10:15:25 +0000175 cfg = CFG.format(all=str(args.all == True).lower(), interval=args.interval,
Florian Mayera8312c72019-01-31 13:50:22 +0000176 duration=args.duration, target_cfg=target_cfg,
177 continuous_dump_cfg=continuous_dump_cfg)
Florian Mayer801349e2018-11-29 10:15:25 +0000178
Florian Mayer6ae95262018-12-06 16:10:29 +0000179 if args.disable_selinux:
180 enforcing = subprocess.check_output(['adb', 'shell', 'getenforce'])
181 atexit.register(subprocess.check_call,
182 ['adb', 'shell', 'su root setenforce %s' % enforcing])
183 subprocess.check_call(['adb', 'shell', 'su root setenforce 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000184
Florian Mayer33ceb8d2019-01-11 14:51:28 +0000185 if not args.no_start:
Florian Mayer75266d52019-02-01 18:09:43 +0000186 heapprofd_prop = subprocess.check_output(
187 ['adb', 'shell', 'getprop persist.heapprofd.enable'])
188 if heapprofd_prop.strip() != '1':
189 subprocess.check_call(
190 ['adb', 'shell', 'setprop persist.heapprofd.enable 1'])
191 atexit.register(subprocess.check_call,
192 ['adb', 'shell', 'setprop persist.heapprofd.enable 0'])
Florian Mayer801349e2018-11-29 10:15:25 +0000193
Florian Mayerbb3b6822019-03-08 17:08:59 +0000194 user = subprocess.check_output(['adb', 'shell', 'whoami']).strip()
Florian Mayer801349e2018-11-29 10:15:25 +0000195 perfetto_pid = subprocess.check_output(
Florian Mayerbb3b6822019-03-08 17:08:59 +0000196 ['adb', 'exec-out', PERFETTO_CMD.format(cfg=cfg, user=user)]).strip()
Florian Mayer35647422019-03-07 16:28:10 +0000197 try:
198 int(perfetto_pid.strip())
199 except ValueError:
200 print("Failed to invoke perfetto: {}".format(perfetto_pid),
201 file=sys.stderr)
202 return 1
Florian Mayer801349e2018-11-29 10:15:25 +0000203
204 old_handler = signal.signal(signal.SIGINT, sigint_handler)
205 print("Profiling active. Press Ctrl+C to terminate.")
206 exists = True
207 while exists and not IS_INTERRUPTED:
208 exists = subprocess.call(
209 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
210 time.sleep(1)
211 signal.signal(signal.SIGINT, old_handler)
212 if IS_INTERRUPTED:
213 # Not check_call because it could have existed in the meantime.
Florian Mayer85969b92019-01-23 17:23:16 +0000214 subprocess.call(['adb', 'shell', 'kill', '-INT', perfetto_pid])
Florian Mayer801349e2018-11-29 10:15:25 +0000215
Florian Mayerddbe31e2018-11-30 14:49:30 +0000216 # Wait for perfetto cmd to return.
217 while exists:
218 exists = subprocess.call(
219 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
220 time.sleep(1)
221
Florian Mayerbb3b6822019-03-08 17:08:59 +0000222 subprocess.check_call(['adb', 'pull',
223 '/data/misc/perfetto-traces/profile-{}'.format(user),
Florian Mayer801349e2018-11-29 10:15:25 +0000224 '/tmp/profile'], stdout=NULL)
225 trace_to_text_output = subprocess.check_output(
226 [trace_to_text_binary, 'profile', '/tmp/profile'],
227 stderr=NULL)
228 profile_path = None
229 for word in trace_to_text_output.split():
230 if 'heap_profile-' in word:
231 profile_path = word
232 if profile_path is None:
233 print("Could not find trace_to_text output path.", file=sys.stderr)
234 return 1
235
236 profile_files = os.listdir(profile_path)
237 if not profile_files:
238 print("No profiles generated", file=sys.stderr)
239 return 1
240
241 subprocess.check_call(['gzip'] + [os.path.join(profile_path, x) for x in
242 os.listdir(profile_path)])
Florian Mayer82f43d12019-01-17 14:37:45 +0000243
244 symlink_path = os.path.join(os.path.dirname(profile_path),
245 "heap_profile-latest")
Florian Mayer31305512019-01-21 17:37:02 +0000246 if os.path.exists(symlink_path):
247 os.unlink(symlink_path)
Florian Mayer82f43d12019-01-17 14:37:45 +0000248 os.symlink(profile_path, symlink_path)
249
250 print("Wrote profiles to {} (symlink {})".format(profile_path, symlink_path))
Florian Mayer801349e2018-11-29 10:15:25 +0000251 print("These can be viewed using pprof. Googlers: head to pprof/ and "
252 "upload them.")
253
254
255if __name__ == '__main__':
256 sys.exit(main(sys.argv))