blob: c2360bb47c8f133e3f88e3a5fe55106e6f9740de [file] [log] [blame]
Lalit Maganti439cea32021-06-18 18:20:49 +01001#!/usr/bin/env python3
2# Copyright (C) 2021 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import argparse
17import http.server
18import os
19import socketserver
20import sys
21import webbrowser
22
23
24class ANSI:
25 END = '\033[0m'
26 BOLD = '\033[1m'
27 RED = '\033[91m'
28 BLACK = '\033[30m'
29 BLUE = '\033[94m'
30 BG_YELLOW = '\033[43m'
31 BG_BLUE = '\033[44m'
32
33
34# HTTP Server used to open the trace in the browser.
35class HttpHandler(http.server.SimpleHTTPRequestHandler):
36
37 def end_headers(self):
38 self.send_header('Access-Control-Allow-Origin', '*')
39 return super().end_headers()
40
41 def do_GET(self):
42 self.server.last_request = self.path
43 return super().do_GET()
44
45 def do_POST(self):
46 self.send_error(404, "File not found")
47
48
49def prt(msg, colors=ANSI.END):
50 print(colors + msg + ANSI.END)
51
52
53def open_trace_in_browser(path):
54 # We reuse the HTTP+RPC port because it's the only one allowed by the CSP.
55 PORT = 9001
56 os.chdir(os.path.dirname(path))
57 fname = os.path.basename(path)
58 socketserver.TCPServer.allow_reuse_address = True
59 with socketserver.TCPServer(('127.0.0.1', PORT), HttpHandler) as httpd:
60 webbrowser.open_new_tab(
61 'https://ui.perfetto.dev/#!/?url=http://127.0.0.1:%d/%s' %
62 (PORT, fname))
63 while httpd.__dict__.get('last_request') != '/' + fname:
64 httpd.handle_request()
65
66
67def main():
68 examples = '\n'.join([
69 ANSI.BOLD + 'Usage:' + ANSI.END, ' -i path/trace_file_name'
70 ])
71 parser = argparse.ArgumentParser(
72 epilog=examples, formatter_class=argparse.RawTextHelpFormatter)
73
74 help = 'Input trace filename'
75 parser.add_argument('-i', '--trace', help=help)
76
77 args = parser.parse_args()
78 trace_file = args.trace
79
80 if trace_file is None:
81 prt('Please specify trace file name with -i/--trace argument', ANSI.RED)
82 sys.exit(1)
83 elif not os.path.exists(trace_file):
84 prt('%s not found ' % trace_file, ANSI.RED)
85 sys.exit(1)
86
87 prt('Opening the trace (%s) in the browser' % trace_file)
88 open_trace_in_browser(trace_file)
89
90
91if __name__ == '__main__':
92 sys.exit(main())