1# 2# Copyright (C) 2024 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# 16# Implementation taken from external/perfetto/tools/record_android_trace. 17# 18 19import webbrowser 20import socketserver 21import http.server 22import os 23 24 25class HttpHandler(http.server.SimpleHTTPRequestHandler): 26 27 def end_headers(self): 28 self.send_header("Access-Control-Allow-Origin", self.server.allow_origin) 29 self.send_header("Cache-Control", "no-cache") 30 super().end_headers() 31 32 def do_GET(self): 33 if self.path != "/" + self.server.expected_fname: 34 self.send_error(404, "File not found") 35 return 36 self.server.fname_get_completed = True 37 super().do_GET() 38 39 def do_POST(self): 40 self.send_error(404, "File not found") 41 42 def log_message(self, format, *args): 43 pass 44 45 46def open_trace(path, origin): 47 PORT = 9001 48 path = os.path.abspath(path) 49 os.chdir(os.path.dirname(path)) 50 fname = os.path.basename(path) 51 socketserver.TCPServer.allow_reuse_address = True 52 with socketserver.TCPServer(("127.0.0.1", PORT), HttpHandler) as httpd: 53 address = (f"{origin}/#!/?url=http://127.0.0.1:" 54 f"{PORT}/{fname}&referrer=open_trace_in_ui") 55 webbrowser.open_new_tab(address) 56 httpd.expected_fname = fname 57 httpd.fname_get_completed = None 58 httpd.allow_origin = origin 59 while httpd.fname_get_completed is None: 60 httpd.handle_request() 61