blob: bc33c21ec0dee0985df757aa8fd1b9e2ef3ed86a [file] [log] [blame]
epoger@google.comf9d134d2013-09-27 15:02:44 +00001#!/usr/bin/python
2
epoger@google.com9fb6c8a2013-10-09 18:05:58 +00003"""
epoger@google.comf9d134d2013-09-27 15:02:44 +00004Copyright 2013 Google Inc.
5
6Use of this source code is governed by a BSD-style license that can be
7found in the LICENSE file.
epoger@google.comf9d134d2013-09-27 15:02:44 +00008
epoger@google.comf9d134d2013-09-27 15:02:44 +00009HTTP server for our HTML rebaseline viewer.
epoger@google.com9fb6c8a2013-10-09 18:05:58 +000010"""
epoger@google.comf9d134d2013-09-27 15:02:44 +000011
12# System-level imports
13import argparse
14import BaseHTTPServer
15import json
epoger@google.comdcb4e652013-10-11 18:45:33 +000016import logging
epoger@google.comf9d134d2013-09-27 15:02:44 +000017import os
18import posixpath
19import re
20import shutil
epoger@google.comb08c7072013-10-30 14:09:04 +000021import socket
epoger@google.comf9d134d2013-09-27 15:02:44 +000022import sys
epoger@google.com542b65f2013-10-15 20:10:33 +000023import thread
24import time
epoger@google.comdcb4e652013-10-11 18:45:33 +000025import urlparse
epoger@google.comf9d134d2013-09-27 15:02:44 +000026
27# Imports from within Skia
28#
29# We need to add the 'tools' directory, so that we can import svn.py within
30# that directory.
31# Make sure that the 'tools' dir is in the PYTHONPATH, but add it at the *end*
32# so any dirs that are already in the PYTHONPATH will be preferred.
epoger@google.comcb55f112013-10-02 19:27:35 +000033PARENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
34TRUNK_DIRECTORY = os.path.dirname(os.path.dirname(PARENT_DIRECTORY))
epoger@google.comf9d134d2013-09-27 15:02:44 +000035TOOLS_DIRECTORY = os.path.join(TRUNK_DIRECTORY, 'tools')
36if TOOLS_DIRECTORY not in sys.path:
37 sys.path.append(TOOLS_DIRECTORY)
38import svn
39
40# Imports from local dir
41import results
42
43ACTUALS_SVN_REPO = 'http://skia-autogen.googlecode.com/svn/gm-actual'
epoger@google.com542b65f2013-10-15 20:10:33 +000044EXPECTATIONS_SVN_REPO = 'http://skia.googlecode.com/svn/trunk/expectations/gm'
epoger@google.comf9d134d2013-09-27 15:02:44 +000045PATHSPLIT_RE = re.compile('/([^/]+)/(.+)')
46TRUNK_DIRECTORY = os.path.dirname(os.path.dirname(os.path.dirname(
47 os.path.realpath(__file__))))
48
49# A simple dictionary of file name extensions to MIME types. The empty string
50# entry is used as the default when no extension was given or if the extension
51# has no entry in this dictionary.
52MIME_TYPE_MAP = {'': 'application/octet-stream',
53 'html': 'text/html',
54 'css': 'text/css',
55 'png': 'image/png',
56 'js': 'application/javascript',
57 'json': 'application/json'
58 }
59
60DEFAULT_ACTUALS_DIR = '.gm-actuals'
61DEFAULT_EXPECTATIONS_DIR = os.path.join(TRUNK_DIRECTORY, 'expectations', 'gm')
62DEFAULT_PORT = 8888
63
epoger@google.comeb832592013-10-23 15:07:26 +000064_HTTP_HEADER_CONTENT_LENGTH = 'Content-Length'
65_HTTP_HEADER_CONTENT_TYPE = 'Content-Type'
66
epoger@google.comf9d134d2013-09-27 15:02:44 +000067_SERVER = None # This gets filled in by main()
68
epoger@google.comb08c7072013-10-30 14:09:04 +000069def get_routable_ip_address():
70 """Returns routable IP address of this host (the IP address of its network
71 interface that would be used for most traffic, not its localhost
72 interface). See http://stackoverflow.com/a/166589 """
73 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
74 sock.connect(('8.8.8.8', 80))
75 host = sock.getsockname()[0]
76 sock.close()
77 return host
78
79
epoger@google.comf9d134d2013-09-27 15:02:44 +000080class Server(object):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +000081 """ HTTP server for our HTML rebaseline viewer. """
epoger@google.comf9d134d2013-09-27 15:02:44 +000082
epoger@google.comf9d134d2013-09-27 15:02:44 +000083 def __init__(self,
84 actuals_dir=DEFAULT_ACTUALS_DIR,
85 expectations_dir=DEFAULT_EXPECTATIONS_DIR,
epoger@google.com542b65f2013-10-15 20:10:33 +000086 port=DEFAULT_PORT, export=False, editable=True,
87 reload_seconds=0):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +000088 """
89 Args:
90 actuals_dir: directory under which we will check out the latest actual
91 GM results
92 expectations_dir: directory under which to find GM expectations (they
93 must already be in that directory)
94 port: which TCP port to listen on for HTTP requests
95 export: whether to allow HTTP clients on other hosts to access this server
epoger@google.com542b65f2013-10-15 20:10:33 +000096 editable: whether HTTP clients are allowed to submit new baselines
97 reload_seconds: polling interval with which to check for new results;
98 if 0, don't check for new results at all
epoger@google.com9fb6c8a2013-10-09 18:05:58 +000099 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000100 self._actuals_dir = actuals_dir
101 self._expectations_dir = expectations_dir
102 self._port = port
103 self._export = export
epoger@google.com542b65f2013-10-15 20:10:33 +0000104 self._editable = editable
105 self._reload_seconds = reload_seconds
epoger@google.comf9d134d2013-09-27 15:02:44 +0000106
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000107 def is_exported(self):
108 """ Returns true iff HTTP clients on other hosts are allowed to access
109 this server. """
110 return self._export
111
epoger@google.com542b65f2013-10-15 20:10:33 +0000112 def is_editable(self):
113 """ Returns true iff HTTP clients are allowed to submit new baselines. """
114 return self._editable
epoger@google.comf9d134d2013-09-27 15:02:44 +0000115
epoger@google.com542b65f2013-10-15 20:10:33 +0000116 def reload_seconds(self):
117 """ Returns the result reload period in seconds, or 0 if we don't reload
118 results. """
119 return self._reload_seconds
120
epoger@google.comeb832592013-10-23 15:07:26 +0000121 def update_results(self):
epoger@google.com542b65f2013-10-15 20:10:33 +0000122 """ Create or update self.results, based on the expectations in
123 self._expectations_dir and the latest actuals from skia-autogen.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000124 """
epoger@google.comeb832592013-10-23 15:07:26 +0000125 with self.results_lock:
126 # self.results_lock prevents us from updating the actual GM results
127 # in multiple threads simultaneously
128 logging.info('Updating actual GM results in %s from SVN repo %s ...' % (
129 self._actuals_dir, ACTUALS_SVN_REPO))
130 actuals_repo = svn.Svn(self._actuals_dir)
131 if not os.path.isdir(self._actuals_dir):
132 os.makedirs(self._actuals_dir)
133 actuals_repo.Checkout(ACTUALS_SVN_REPO, '.')
epoger@google.com542b65f2013-10-15 20:10:33 +0000134 else:
epoger@google.comeb832592013-10-23 15:07:26 +0000135 actuals_repo.Update('.')
epoger@google.com542b65f2013-10-15 20:10:33 +0000136
epoger@google.comeb832592013-10-23 15:07:26 +0000137 # We only update the expectations dir if the server was run with a
138 # nonzero --reload argument; otherwise, we expect the user to maintain
139 # her own expectations as she sees fit.
140 #
141 # self.results_lock prevents us from updating the expected GM results
142 # in multiple threads simultaneously
143 #
144 # TODO(epoger): Use git instead of svn to check out expectations, since
145 # the Skia repo is moving to git.
146 if self._reload_seconds:
147 logging.info(
148 'Updating expected GM results in %s from SVN repo %s ...' % (
149 self._expectations_dir, EXPECTATIONS_SVN_REPO))
150 expectations_repo = svn.Svn(self._expectations_dir)
151 if not os.path.isdir(self._expectations_dir):
152 os.makedirs(self._expectations_dir)
153 expectations_repo.Checkout(EXPECTATIONS_SVN_REPO, '.')
154 else:
155 expectations_repo.Update('.')
156
157 logging.info(
158 'Parsing results from actuals in %s and expectations in %s ...' % (
159 self._actuals_dir, self._expectations_dir))
160 self.results = results.Results(
161 actuals_root=self._actuals_dir,
162 expected_root=self._expectations_dir)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000163
epoger@google.com542b65f2013-10-15 20:10:33 +0000164 def _result_reloader(self):
165 """ If --reload argument was specified, reload results at the appropriate
166 interval.
167 """
168 while self._reload_seconds:
169 time.sleep(self._reload_seconds)
epoger@google.comeb832592013-10-23 15:07:26 +0000170 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000171
epoger@google.comf9d134d2013-09-27 15:02:44 +0000172 def run(self):
epoger@google.com542b65f2013-10-15 20:10:33 +0000173 self.results_lock = thread.allocate_lock()
epoger@google.comeb832592013-10-23 15:07:26 +0000174 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000175 thread.start_new_thread(self._result_reloader, ())
176
epoger@google.comf9d134d2013-09-27 15:02:44 +0000177 if self._export:
178 server_address = ('', self._port)
epoger@google.comb08c7072013-10-30 14:09:04 +0000179 host = get_routable_ip_address()
epoger@google.com542b65f2013-10-15 20:10:33 +0000180 if self._editable:
181 logging.warning('Running with combination of "export" and "editable" '
182 'flags. Users on other machines will '
183 'be able to modify your GM expectations!')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000184 else:
epoger@google.comb08c7072013-10-30 14:09:04 +0000185 host = '127.0.0.1'
186 server_address = (host, self._port)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000187 http_server = BaseHTTPServer.HTTPServer(server_address, HTTPRequestHandler)
epoger@google.comb08c7072013-10-30 14:09:04 +0000188 logging.info('Ready for requests on http://%s:%d' % (host, http_server.server_port))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000189 http_server.serve_forever()
190
191
192class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
193 """ HTTP request handlers for various types of queries this server knows
194 how to handle (static HTML and Javascript, expected/actual results, etc.)
195 """
196 def do_GET(self):
197 """ Handles all GET requests, forwarding them to the appropriate
198 do_GET_* dispatcher. """
199 if self.path == '' or self.path == '/' or self.path == '/index.html' :
epoger@google.com045c3d32013-11-01 16:46:41 +0000200 self.redirect_to('/static/index.html')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000201 return
202 if self.path == '/favicon.ico' :
203 self.redirect_to('/static/favicon.ico')
204 return
205
206 # All requests must be of this form:
207 # /dispatcher/remainder
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000208 # where 'dispatcher' indicates which do_GET_* dispatcher to run
209 # and 'remainder' is the remaining path sent to that dispatcher.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000210 normpath = posixpath.normpath(self.path)
211 (dispatcher_name, remainder) = PATHSPLIT_RE.match(normpath).groups()
212 dispatchers = {
213 'results': self.do_GET_results,
214 'static': self.do_GET_static,
215 }
216 dispatcher = dispatchers[dispatcher_name]
217 dispatcher(remainder)
218
epoger@google.comdcb4e652013-10-11 18:45:33 +0000219 def do_GET_results(self, type):
epoger@google.comf9d134d2013-09-27 15:02:44 +0000220 """ Handle a GET request for GM results.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000221
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000222 Args:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000223 type: string indicating which set of results to return;
224 must be one of the results.RESULTS_* constants
225 """
226 logging.debug('do_GET_results: sending results of type "%s"' % type)
227 try:
228 # TODO(epoger): Rather than using a global variable for the handler
229 # to refer to the Server object, make Server a subclass of
230 # HTTPServer, and then it could be available to the handler via
231 # the handler's .server instance variable.
epoger@google.com542b65f2013-10-15 20:10:33 +0000232
233 with _SERVER.results_lock:
234 response_dict = _SERVER.results.get_results_of_type(type)
235 time_updated = _SERVER.results.get_timestamp()
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000236 response_dict['header'] = {
epoger@google.com542b65f2013-10-15 20:10:33 +0000237 # Timestamps:
238 # 1. when this data was last updated
239 # 2. when the caller should check back for new data (if ever)
240 #
241 # We only return these timestamps if the --reload argument was passed;
242 # otherwise, we have no idea when the expectations were last updated
243 # (we allow the user to maintain her own expectations as she sees fit).
244 'timeUpdated': time_updated if _SERVER.reload_seconds() else None,
245 'timeNextUpdateAvailable': (
246 (time_updated+_SERVER.reload_seconds()) if _SERVER.reload_seconds()
247 else None),
248
epoger@google.comeb832592013-10-23 15:07:26 +0000249 # The type we passed to get_results_of_type()
250 'type': type,
251
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000252 # Hash of testData, which the client must return with any edits--
253 # this ensures that the edits were made to a particular dataset.
epoger@google.com542b65f2013-10-15 20:10:33 +0000254 'dataHash': str(hash(repr(response_dict['testData']))),
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000255
256 # Whether the server will accept edits back.
epoger@google.com542b65f2013-10-15 20:10:33 +0000257 'isEditable': _SERVER.is_editable(),
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000258
259 # Whether the service is accessible from other hosts.
260 'isExported': _SERVER.is_exported(),
261 }
epoger@google.comf9d134d2013-09-27 15:02:44 +0000262 self.send_json_dict(response_dict)
epoger@google.comdcb4e652013-10-11 18:45:33 +0000263 except:
epoger@google.comf9d134d2013-09-27 15:02:44 +0000264 self.send_error(404)
epoger@google.com542b65f2013-10-15 20:10:33 +0000265 raise
epoger@google.comf9d134d2013-09-27 15:02:44 +0000266
267 def do_GET_static(self, path):
epoger@google.comcb55f112013-10-02 19:27:35 +0000268 """ Handle a GET request for a file under the 'static' directory.
269 Only allow serving of files within the 'static' directory that is a
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000270 filesystem sibling of this script.
271
272 Args:
273 path: path to file (under static directory) to retrieve
274 """
epoger@google.comdcb4e652013-10-11 18:45:33 +0000275 # Strip arguments ('?resultsToLoad=all') from the path
276 path = urlparse.urlparse(path).path
277
278 logging.debug('do_GET_static: sending file "%s"' % path)
epoger@google.comcb55f112013-10-02 19:27:35 +0000279 static_dir = os.path.realpath(os.path.join(PARENT_DIRECTORY, 'static'))
280 full_path = os.path.realpath(os.path.join(static_dir, path))
281 if full_path.startswith(static_dir):
282 self.send_file(full_path)
283 else:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000284 logging.error(
285 'Attempted do_GET_static() of path [%s] outside of static dir [%s]'
286 % (full_path, static_dir))
epoger@google.comcb55f112013-10-02 19:27:35 +0000287 self.send_error(404)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000288
epoger@google.comeb832592013-10-23 15:07:26 +0000289 def do_POST(self):
290 """ Handles all POST requests, forwarding them to the appropriate
291 do_POST_* dispatcher. """
292 # All requests must be of this form:
293 # /dispatcher
294 # where 'dispatcher' indicates which do_POST_* dispatcher to run.
295 normpath = posixpath.normpath(self.path)
296 dispatchers = {
297 '/edits': self.do_POST_edits,
298 }
299 try:
300 dispatcher = dispatchers[normpath]
301 dispatcher()
302 self.send_response(200)
303 except:
304 self.send_error(404)
305 raise
306
307 def do_POST_edits(self):
308 """ Handle a POST request with modifications to GM expectations, in this
309 format:
310
311 {
312 'oldResultsType': 'all', # type of results that the client loaded
313 # and then made modifications to
314 'oldResultsHash': 39850913, # hash of results when the client loaded them
315 # (ensures that the client and server apply
316 # modifications to the same base)
317 'modifications': [
318 {
319 'builder': 'Test-Android-Nexus10-MaliT604-Arm7-Debug',
320 'test': 'strokerect',
321 'config': 'gpu',
322 'expectedHashType': 'bitmap-64bitMD5',
323 'expectedHashDigest': '1707359671708613629',
324 },
325 ...
326 ],
327 }
328
329 Raises an Exception if there were any problems.
330 """
331 if not _SERVER.is_editable():
332 raise Exception('this server is not running in --editable mode')
333
334 content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE]
335 if content_type != 'application/json;charset=UTF-8':
336 raise Exception('unsupported %s [%s]' % (
337 _HTTP_HEADER_CONTENT_TYPE, content_type))
338
339 content_length = int(self.headers[_HTTP_HEADER_CONTENT_LENGTH])
340 json_data = self.rfile.read(content_length)
341 data = json.loads(json_data)
342 logging.debug('do_POST_edits: received new GM expectations data [%s]' %
343 data)
344
345 with _SERVER.results_lock:
346 oldResultsType = data['oldResultsType']
347 oldResults = _SERVER.results.get_results_of_type(oldResultsType)
348 oldResultsHash = str(hash(repr(oldResults['testData'])))
349 if oldResultsHash != data['oldResultsHash']:
350 raise Exception('results of type "%s" changed while the client was '
351 'making modifications. The client should reload the '
352 'results and submit the modifications again.' %
353 oldResultsType)
354 _SERVER.results.edit_expectations(data['modifications'])
355
356 # Now that the edits have been committed, update results to reflect them.
357 _SERVER.update_results()
358
epoger@google.comf9d134d2013-09-27 15:02:44 +0000359 def redirect_to(self, url):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000360 """ Redirect the HTTP client to a different url.
361
362 Args:
363 url: URL to redirect the HTTP client to
364 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000365 self.send_response(301)
366 self.send_header('Location', url)
367 self.end_headers()
368
369 def send_file(self, path):
370 """ Send the contents of the file at this path, with a mimetype based
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000371 on the filename extension.
372
373 Args:
374 path: path of file whose contents to send to the HTTP client
375 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000376 # Grab the extension if there is one
377 extension = os.path.splitext(path)[1]
378 if len(extension) >= 1:
379 extension = extension[1:]
380
381 # Determine the MIME type of the file from its extension
382 mime_type = MIME_TYPE_MAP.get(extension, MIME_TYPE_MAP[''])
383
384 # Open the file and send it over HTTP
385 if os.path.isfile(path):
386 with open(path, 'rb') as sending_file:
387 self.send_response(200)
388 self.send_header('Content-type', mime_type)
389 self.end_headers()
390 self.wfile.write(sending_file.read())
391 else:
392 self.send_error(404)
393
394 def send_json_dict(self, json_dict):
395 """ Send the contents of this dictionary in JSON format, with a JSON
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000396 mimetype.
397
398 Args:
399 json_dict: dictionary to send
400 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000401 self.send_response(200)
402 self.send_header('Content-type', 'application/json')
403 self.end_headers()
404 json.dump(json_dict, self.wfile)
405
406
407def main():
epoger@google.comdcb4e652013-10-11 18:45:33 +0000408 logging.basicConfig(level=logging.INFO)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000409 parser = argparse.ArgumentParser()
410 parser.add_argument('--actuals-dir',
411 help=('Directory into which we will check out the latest '
412 'actual GM results. If this directory does not '
413 'exist, it will be created. Defaults to %(default)s'),
414 default=DEFAULT_ACTUALS_DIR)
epoger@google.com542b65f2013-10-15 20:10:33 +0000415 parser.add_argument('--editable', action='store_true',
epoger@google.comeb832592013-10-23 15:07:26 +0000416 help=('Allow HTTP clients to submit new baselines.'))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000417 parser.add_argument('--expectations-dir',
418 help=('Directory under which to find GM expectations; '
419 'defaults to %(default)s'),
420 default=DEFAULT_EXPECTATIONS_DIR)
421 parser.add_argument('--export', action='store_true',
422 help=('Instead of only allowing access from HTTP clients '
423 'on localhost, allow HTTP clients on other hosts '
424 'to access this server. WARNING: doing so will '
425 'allow users on other hosts to modify your '
epoger@google.com542b65f2013-10-15 20:10:33 +0000426 'GM expectations, if combined with --editable.'))
epoger@google.comafaad3d2013-09-30 15:06:25 +0000427 parser.add_argument('--port', type=int,
428 help=('Which TCP port to listen on for HTTP requests; '
429 'defaults to %(default)s'),
430 default=DEFAULT_PORT)
epoger@google.com542b65f2013-10-15 20:10:33 +0000431 parser.add_argument('--reload', type=int,
432 help=('How often (a period in seconds) to update the '
433 'results. If specified, both EXPECTATIONS_DIR and '
434 'ACTUAL_DIR will be updated. '
435 'By default, we do not reload at all, and you '
436 'must restart the server to pick up new data.'),
437 default=0)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000438 args = parser.parse_args()
439 global _SERVER
epoger@google.com542b65f2013-10-15 20:10:33 +0000440 _SERVER = Server(actuals_dir=args.actuals_dir,
441 expectations_dir=args.expectations_dir,
442 port=args.port, export=args.export, editable=args.editable,
443 reload_seconds=args.reload)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000444 _SERVER.run()
445
446if __name__ == '__main__':
447 main()