xref: /aosp_15_r20/external/perfetto/infra/perfetto-get.appspot.com/main.py (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1# Copyright (C) 2019 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import base64
16import requests
17import time
18
19from collections import namedtuple
20from flask import Flask, make_response, redirect
21
22BASE = 'https://android.googlesource.com/platform/external/perfetto.git/' \
23       '+/main/%s?format=TEXT'
24
25RESOURCES = {
26    'tracebox': 'tools/tracebox',
27    'traceconv': 'tools/traceconv',
28    'trace_processor': 'tools/trace_processor',
29}
30
31CACHE_TTL = 3600  # 1 h
32
33CacheEntry = namedtuple('CacheEntry', ['contents', 'expiration'])
34cache = {}
35
36app = Flask(__name__)
37
38
39def DeleteStaleCacheEntries():
40  now = time.time()
41  for url, entry in list(cache.items()):
42    if now > entry.expiration:
43      cache.pop(url, None)
44
45
46@app.route('/')
47def root():
48  return redirect('https://www.perfetto.dev/', code=301)
49
50
51@app.route('/<string:resource>')
52def fetch_artifact(resource):
53  hdrs = {'Content-Type': 'text/plain'}
54  resource = resource.lower()
55  if resource not in RESOURCES:
56    return make_response('Resource "%s" not found' % resource, 404, hdrs)
57  url = BASE % RESOURCES[resource]
58  DeleteStaleCacheEntries()
59  entry = cache.get(url)
60  contents = entry.contents if entry is not None else None
61  if not contents:
62    req = requests.get(url)
63    if req.status_code != 200:
64      err_str = 'http error %d while fetching %s' % (req.status_code, url)
65      return make_response(err_str, req.status_code, hdrs)
66    contents = base64.b64decode(req.text)
67    cache[url] = CacheEntry(contents, time.time() + CACHE_TTL)
68  hdrs = {'Content-Disposition': 'attachment; filename="%s"' % resource}
69  return make_response(contents, 200, hdrs)
70