xref: /aosp_15_r20/external/perfetto/tools/open_trace_in_ui (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1#!/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', self.server.allow_origin)
39    self.send_header('Cache-Control', 'no-cache')
40    super().end_headers()
41
42  def do_GET(self):
43    if self.path != '/' + self.server.expected_fname:
44      self.send_error(404, 'File not found')
45      return
46
47    self.server.fname_get_completed = True
48    super().do_GET()
49
50  def do_POST(self):
51    self.send_error(404, 'File not found')
52
53
54def prt(msg, colors=ANSI.END):
55  print(colors + msg + ANSI.END)
56
57
58def open_trace(path, open_browser, origin):
59  # We reuse the HTTP+RPC port because it's the only one allowed by the CSP.
60  PORT = 9001
61  path = os.path.abspath(path)
62  os.chdir(os.path.dirname(path))
63  fname = os.path.basename(path)
64  socketserver.TCPServer.allow_reuse_address = True
65  with socketserver.TCPServer(('127.0.0.1', PORT), HttpHandler) as httpd:
66    address = f'{origin}/#!/?url=http://127.0.0.1:{PORT}/{fname}&referrer=open_trace_in_ui'
67    if open_browser:
68      webbrowser.open_new_tab(address)
69    else:
70      print(f'Open URL in browser: {address}')
71
72    httpd.expected_fname = fname
73    httpd.fname_get_completed = None
74    httpd.allow_origin = origin
75    while httpd.fname_get_completed is None:
76      httpd.handle_request()
77
78
79def main():
80  examples = '\n'.join([
81      ANSI.BOLD + 'Examples:' + ANSI.END,
82      '  tools/open_trace_in_ui trace.pftrace',
83  ])
84  parser = argparse.ArgumentParser(
85      epilog=examples, formatter_class=argparse.RawTextHelpFormatter)
86
87  parser.add_argument('positional_trace', metavar='trace', nargs='?')
88  parser.add_argument(
89      '-n', '--no-open-browser', action='store_true', default=False)
90  parser.add_argument('--origin', default='https://ui.perfetto.dev')
91  parser.add_argument(
92      '-i', '--trace', help='input filename (overrides positional argument)')
93
94  args = parser.parse_args()
95  open_browser = not args.no_open_browser
96
97  trace_file = None
98  if args.positional_trace is not None:
99    trace_file = args.positional_trace
100  if args.trace is not None:
101    trace_file = args.trace
102
103  if trace_file is None:
104    prt('Please specify trace file name', ANSI.RED)
105    sys.exit(1)
106  elif not os.path.exists(trace_file):
107    prt('%s not found ' % trace_file, ANSI.RED)
108    sys.exit(1)
109
110  prt('Opening the trace (%s) in the browser' % trace_file)
111  open_trace(trace_file, open_browser, args.origin)
112
113
114if __name__ == '__main__':
115  sys.exit(main())
116