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 logging 16import webapp2 17import urllib 18 19from google.appengine.api import urlfetch 20from google.appengine.api import memcache 21from config import GERRIT_HOST, GERRIT_PROJECT 22''' Makes anonymous GET-only requests to Gerrit. 23 24Solves the lack of CORS headers from AOSP gerrit.''' 25 26 27def req_cached(url): 28 '''Used for requests that return immutable data, avoid hitting Gerrit 500''' 29 resp = memcache.get(url) 30 if resp is not None: 31 return 200, resp 32 result = urlfetch.fetch(url) 33 if result.status_code == 200: 34 memcache.add(url, result.content, 3600 * 24) 35 return result.status_code, result.content 36 37 38class GerritCommitsHandler(webapp2.RequestHandler): 39 40 def get(self, sha1): 41 project = urllib.quote(GERRIT_PROJECT, '') 42 url = 'https://%s/projects/%s/commits/%s' % (GERRIT_HOST, project, sha1) 43 status, content = req_cached(url) 44 self.response.status_int = status 45 self.response.write(content[4:]) # 4: -> Strip Gerrit XSSI chars. 46 47 48class GerritLogHandler(webapp2.RequestHandler): 49 50 def get(self, first, second): 51 url = 'https://%s/%s/+log/%s..%s?format=json' % (GERRIT_HOST.replace( 52 '-review', ''), GERRIT_PROJECT, first, second) 53 status, content = req_cached(url) 54 self.response.status_int = status 55 self.response.write(content[4:]) # 4: -> Strip Gerrit XSSI chars. 56 57 58class GerritChangesHandler(webapp2.RequestHandler): 59 60 def get(self): 61 url = 'https://%s/changes/?q=project:%s+' % (GERRIT_HOST, GERRIT_PROJECT) 62 url += self.request.query_string 63 result = urlfetch.fetch(url) 64 self.response.headers['Content-Type'] = 'text/plain' 65 self.response.status_int = result.status_code 66 if (result.status_code == 200): 67 self.response.write(result.content[4:]) # 4: -> Strip Gerrit XSSI chars. 68 else: 69 self.response.write('HTTP error %s' % result.status_code) 70 71 72app = webapp2.WSGIApplication([ 73 ('/gerrit/commits/([a-f0-9]+)', GerritCommitsHandler), 74 ('/gerrit/log/([a-f0-9]+)..([a-f0-9]+)', GerritLogHandler), 75 ('/gerrit/changes/', GerritChangesHandler), 76], 77 debug=True) 78