blob: a0f31f8ce866f85e976d88a847dff81a4a4f95d5 [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__))))
epoger@google.com9dddf6f2013-11-08 16:25:25 +000048GENERATED_IMAGES_ROOT = os.path.join(PARENT_DIRECTORY, 'static',
49 'generated-images')
epoger@google.comf9d134d2013-09-27 15:02:44 +000050
51# A simple dictionary of file name extensions to MIME types. The empty string
52# entry is used as the default when no extension was given or if the extension
53# has no entry in this dictionary.
54MIME_TYPE_MAP = {'': 'application/octet-stream',
55 'html': 'text/html',
56 'css': 'text/css',
57 'png': 'image/png',
58 'js': 'application/javascript',
59 'json': 'application/json'
60 }
61
62DEFAULT_ACTUALS_DIR = '.gm-actuals'
63DEFAULT_EXPECTATIONS_DIR = os.path.join(TRUNK_DIRECTORY, 'expectations', 'gm')
64DEFAULT_PORT = 8888
65
epoger@google.comeb832592013-10-23 15:07:26 +000066_HTTP_HEADER_CONTENT_LENGTH = 'Content-Length'
67_HTTP_HEADER_CONTENT_TYPE = 'Content-Type'
68
epoger@google.comf9d134d2013-09-27 15:02:44 +000069_SERVER = None # This gets filled in by main()
70
epoger@google.comb08c7072013-10-30 14:09:04 +000071def get_routable_ip_address():
72 """Returns routable IP address of this host (the IP address of its network
73 interface that would be used for most traffic, not its localhost
74 interface). See http://stackoverflow.com/a/166589 """
75 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
76 sock.connect(('8.8.8.8', 80))
77 host = sock.getsockname()[0]
78 sock.close()
79 return host
80
81
epoger@google.comf9d134d2013-09-27 15:02:44 +000082class Server(object):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +000083 """ HTTP server for our HTML rebaseline viewer. """
epoger@google.comf9d134d2013-09-27 15:02:44 +000084
epoger@google.comf9d134d2013-09-27 15:02:44 +000085 def __init__(self,
86 actuals_dir=DEFAULT_ACTUALS_DIR,
87 expectations_dir=DEFAULT_EXPECTATIONS_DIR,
epoger@google.com542b65f2013-10-15 20:10:33 +000088 port=DEFAULT_PORT, export=False, editable=True,
89 reload_seconds=0):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +000090 """
91 Args:
92 actuals_dir: directory under which we will check out the latest actual
93 GM results
94 expectations_dir: directory under which to find GM expectations (they
95 must already be in that directory)
96 port: which TCP port to listen on for HTTP requests
97 export: whether to allow HTTP clients on other hosts to access this server
epoger@google.com542b65f2013-10-15 20:10:33 +000098 editable: whether HTTP clients are allowed to submit new baselines
99 reload_seconds: polling interval with which to check for new results;
100 if 0, don't check for new results at all
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000101 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000102 self._actuals_dir = actuals_dir
103 self._expectations_dir = expectations_dir
104 self._port = port
105 self._export = export
epoger@google.com542b65f2013-10-15 20:10:33 +0000106 self._editable = editable
107 self._reload_seconds = reload_seconds
epoger@google.comf9d134d2013-09-27 15:02:44 +0000108
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000109 def is_exported(self):
110 """ Returns true iff HTTP clients on other hosts are allowed to access
111 this server. """
112 return self._export
113
epoger@google.com542b65f2013-10-15 20:10:33 +0000114 def is_editable(self):
115 """ Returns true iff HTTP clients are allowed to submit new baselines. """
116 return self._editable
epoger@google.comf9d134d2013-09-27 15:02:44 +0000117
epoger@google.com542b65f2013-10-15 20:10:33 +0000118 def reload_seconds(self):
119 """ Returns the result reload period in seconds, or 0 if we don't reload
120 results. """
121 return self._reload_seconds
122
epoger@google.comeb832592013-10-23 15:07:26 +0000123 def update_results(self):
epoger@google.com542b65f2013-10-15 20:10:33 +0000124 """ Create or update self.results, based on the expectations in
125 self._expectations_dir and the latest actuals from skia-autogen.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000126 """
epoger@google.comeb832592013-10-23 15:07:26 +0000127 with self.results_lock:
128 # self.results_lock prevents us from updating the actual GM results
129 # in multiple threads simultaneously
130 logging.info('Updating actual GM results in %s from SVN repo %s ...' % (
131 self._actuals_dir, ACTUALS_SVN_REPO))
132 actuals_repo = svn.Svn(self._actuals_dir)
133 if not os.path.isdir(self._actuals_dir):
134 os.makedirs(self._actuals_dir)
135 actuals_repo.Checkout(ACTUALS_SVN_REPO, '.')
epoger@google.com542b65f2013-10-15 20:10:33 +0000136 else:
epoger@google.comeb832592013-10-23 15:07:26 +0000137 actuals_repo.Update('.')
epoger@google.com542b65f2013-10-15 20:10:33 +0000138
epoger@google.comeb832592013-10-23 15:07:26 +0000139 # We only update the expectations dir if the server was run with a
140 # nonzero --reload argument; otherwise, we expect the user to maintain
141 # her own expectations as she sees fit.
142 #
143 # self.results_lock prevents us from updating the expected GM results
144 # in multiple threads simultaneously
145 #
146 # TODO(epoger): Use git instead of svn to check out expectations, since
147 # the Skia repo is moving to git.
148 if self._reload_seconds:
149 logging.info(
150 'Updating expected GM results in %s from SVN repo %s ...' % (
151 self._expectations_dir, EXPECTATIONS_SVN_REPO))
152 expectations_repo = svn.Svn(self._expectations_dir)
153 if not os.path.isdir(self._expectations_dir):
154 os.makedirs(self._expectations_dir)
155 expectations_repo.Checkout(EXPECTATIONS_SVN_REPO, '.')
156 else:
157 expectations_repo.Update('.')
158
159 logging.info(
epoger@google.com9dddf6f2013-11-08 16:25:25 +0000160 ('Parsing results from actuals in %s and expectations in %s, '
161 + 'and generating pixel diffs (may take a while) ...') % (
epoger@google.comeb832592013-10-23 15:07:26 +0000162 self._actuals_dir, self._expectations_dir))
163 self.results = results.Results(
164 actuals_root=self._actuals_dir,
epoger@google.com9dddf6f2013-11-08 16:25:25 +0000165 expected_root=self._expectations_dir,
166 generated_images_root=GENERATED_IMAGES_ROOT)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000167
epoger@google.com542b65f2013-10-15 20:10:33 +0000168 def _result_reloader(self):
169 """ If --reload argument was specified, reload results at the appropriate
170 interval.
171 """
172 while self._reload_seconds:
173 time.sleep(self._reload_seconds)
epoger@google.comeb832592013-10-23 15:07:26 +0000174 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000175
epoger@google.comf9d134d2013-09-27 15:02:44 +0000176 def run(self):
epoger@google.com542b65f2013-10-15 20:10:33 +0000177 self.results_lock = thread.allocate_lock()
epoger@google.comeb832592013-10-23 15:07:26 +0000178 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000179 thread.start_new_thread(self._result_reloader, ())
180
epoger@google.comf9d134d2013-09-27 15:02:44 +0000181 if self._export:
182 server_address = ('', self._port)
epoger@google.comb08c7072013-10-30 14:09:04 +0000183 host = get_routable_ip_address()
epoger@google.com542b65f2013-10-15 20:10:33 +0000184 if self._editable:
185 logging.warning('Running with combination of "export" and "editable" '
186 'flags. Users on other machines will '
187 'be able to modify your GM expectations!')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000188 else:
epoger@google.comb08c7072013-10-30 14:09:04 +0000189 host = '127.0.0.1'
190 server_address = (host, self._port)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000191 http_server = BaseHTTPServer.HTTPServer(server_address, HTTPRequestHandler)
epoger@google.comb08c7072013-10-30 14:09:04 +0000192 logging.info('Ready for requests on http://%s:%d' % (host, http_server.server_port))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000193 http_server.serve_forever()
194
195
196class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
197 """ HTTP request handlers for various types of queries this server knows
198 how to handle (static HTML and Javascript, expected/actual results, etc.)
199 """
200 def do_GET(self):
201 """ Handles all GET requests, forwarding them to the appropriate
202 do_GET_* dispatcher. """
203 if self.path == '' or self.path == '/' or self.path == '/index.html' :
epoger@google.com045c3d32013-11-01 16:46:41 +0000204 self.redirect_to('/static/index.html')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000205 return
206 if self.path == '/favicon.ico' :
207 self.redirect_to('/static/favicon.ico')
208 return
209
210 # All requests must be of this form:
211 # /dispatcher/remainder
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000212 # where 'dispatcher' indicates which do_GET_* dispatcher to run
213 # and 'remainder' is the remaining path sent to that dispatcher.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000214 normpath = posixpath.normpath(self.path)
215 (dispatcher_name, remainder) = PATHSPLIT_RE.match(normpath).groups()
216 dispatchers = {
217 'results': self.do_GET_results,
218 'static': self.do_GET_static,
219 }
220 dispatcher = dispatchers[dispatcher_name]
221 dispatcher(remainder)
222
epoger@google.comdcb4e652013-10-11 18:45:33 +0000223 def do_GET_results(self, type):
epoger@google.comf9d134d2013-09-27 15:02:44 +0000224 """ Handle a GET request for GM results.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000225
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000226 Args:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000227 type: string indicating which set of results to return;
228 must be one of the results.RESULTS_* constants
229 """
230 logging.debug('do_GET_results: sending results of type "%s"' % type)
231 try:
232 # TODO(epoger): Rather than using a global variable for the handler
233 # to refer to the Server object, make Server a subclass of
234 # HTTPServer, and then it could be available to the handler via
235 # the handler's .server instance variable.
epoger@google.com542b65f2013-10-15 20:10:33 +0000236
237 with _SERVER.results_lock:
238 response_dict = _SERVER.results.get_results_of_type(type)
239 time_updated = _SERVER.results.get_timestamp()
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000240 response_dict['header'] = {
epoger@google.com542b65f2013-10-15 20:10:33 +0000241 # Timestamps:
242 # 1. when this data was last updated
243 # 2. when the caller should check back for new data (if ever)
244 #
245 # We only return these timestamps if the --reload argument was passed;
246 # otherwise, we have no idea when the expectations were last updated
247 # (we allow the user to maintain her own expectations as she sees fit).
248 'timeUpdated': time_updated if _SERVER.reload_seconds() else None,
249 'timeNextUpdateAvailable': (
250 (time_updated+_SERVER.reload_seconds()) if _SERVER.reload_seconds()
251 else None),
252
epoger@google.comeb832592013-10-23 15:07:26 +0000253 # The type we passed to get_results_of_type()
254 'type': type,
255
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000256 # Hash of testData, which the client must return with any edits--
257 # this ensures that the edits were made to a particular dataset.
epoger@google.com542b65f2013-10-15 20:10:33 +0000258 'dataHash': str(hash(repr(response_dict['testData']))),
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000259
260 # Whether the server will accept edits back.
epoger@google.com542b65f2013-10-15 20:10:33 +0000261 'isEditable': _SERVER.is_editable(),
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000262
263 # Whether the service is accessible from other hosts.
264 'isExported': _SERVER.is_exported(),
265 }
epoger@google.comf9d134d2013-09-27 15:02:44 +0000266 self.send_json_dict(response_dict)
epoger@google.comdcb4e652013-10-11 18:45:33 +0000267 except:
epoger@google.comf9d134d2013-09-27 15:02:44 +0000268 self.send_error(404)
epoger@google.com542b65f2013-10-15 20:10:33 +0000269 raise
epoger@google.comf9d134d2013-09-27 15:02:44 +0000270
271 def do_GET_static(self, path):
epoger@google.comcb55f112013-10-02 19:27:35 +0000272 """ Handle a GET request for a file under the 'static' directory.
273 Only allow serving of files within the 'static' directory that is a
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000274 filesystem sibling of this script.
275
276 Args:
277 path: path to file (under static directory) to retrieve
278 """
epoger@google.comdcb4e652013-10-11 18:45:33 +0000279 # Strip arguments ('?resultsToLoad=all') from the path
280 path = urlparse.urlparse(path).path
281
282 logging.debug('do_GET_static: sending file "%s"' % path)
epoger@google.comcb55f112013-10-02 19:27:35 +0000283 static_dir = os.path.realpath(os.path.join(PARENT_DIRECTORY, 'static'))
284 full_path = os.path.realpath(os.path.join(static_dir, path))
285 if full_path.startswith(static_dir):
286 self.send_file(full_path)
287 else:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000288 logging.error(
289 'Attempted do_GET_static() of path [%s] outside of static dir [%s]'
290 % (full_path, static_dir))
epoger@google.comcb55f112013-10-02 19:27:35 +0000291 self.send_error(404)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000292
epoger@google.comeb832592013-10-23 15:07:26 +0000293 def do_POST(self):
294 """ Handles all POST requests, forwarding them to the appropriate
295 do_POST_* dispatcher. """
296 # All requests must be of this form:
297 # /dispatcher
298 # where 'dispatcher' indicates which do_POST_* dispatcher to run.
299 normpath = posixpath.normpath(self.path)
300 dispatchers = {
301 '/edits': self.do_POST_edits,
302 }
303 try:
304 dispatcher = dispatchers[normpath]
305 dispatcher()
306 self.send_response(200)
307 except:
308 self.send_error(404)
309 raise
310
311 def do_POST_edits(self):
312 """ Handle a POST request with modifications to GM expectations, in this
313 format:
314
315 {
316 'oldResultsType': 'all', # type of results that the client loaded
317 # and then made modifications to
318 'oldResultsHash': 39850913, # hash of results when the client loaded them
319 # (ensures that the client and server apply
320 # modifications to the same base)
321 'modifications': [
322 {
323 'builder': 'Test-Android-Nexus10-MaliT604-Arm7-Debug',
324 'test': 'strokerect',
325 'config': 'gpu',
326 'expectedHashType': 'bitmap-64bitMD5',
327 'expectedHashDigest': '1707359671708613629',
328 },
329 ...
330 ],
331 }
332
333 Raises an Exception if there were any problems.
334 """
335 if not _SERVER.is_editable():
336 raise Exception('this server is not running in --editable mode')
337
338 content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE]
339 if content_type != 'application/json;charset=UTF-8':
340 raise Exception('unsupported %s [%s]' % (
341 _HTTP_HEADER_CONTENT_TYPE, content_type))
342
343 content_length = int(self.headers[_HTTP_HEADER_CONTENT_LENGTH])
344 json_data = self.rfile.read(content_length)
345 data = json.loads(json_data)
346 logging.debug('do_POST_edits: received new GM expectations data [%s]' %
347 data)
348
349 with _SERVER.results_lock:
350 oldResultsType = data['oldResultsType']
351 oldResults = _SERVER.results.get_results_of_type(oldResultsType)
352 oldResultsHash = str(hash(repr(oldResults['testData'])))
353 if oldResultsHash != data['oldResultsHash']:
354 raise Exception('results of type "%s" changed while the client was '
355 'making modifications. The client should reload the '
356 'results and submit the modifications again.' %
357 oldResultsType)
358 _SERVER.results.edit_expectations(data['modifications'])
359
360 # Now that the edits have been committed, update results to reflect them.
361 _SERVER.update_results()
362
epoger@google.comf9d134d2013-09-27 15:02:44 +0000363 def redirect_to(self, url):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000364 """ Redirect the HTTP client to a different url.
365
366 Args:
367 url: URL to redirect the HTTP client to
368 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000369 self.send_response(301)
370 self.send_header('Location', url)
371 self.end_headers()
372
373 def send_file(self, path):
374 """ Send the contents of the file at this path, with a mimetype based
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000375 on the filename extension.
376
377 Args:
378 path: path of file whose contents to send to the HTTP client
379 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000380 # Grab the extension if there is one
381 extension = os.path.splitext(path)[1]
382 if len(extension) >= 1:
383 extension = extension[1:]
384
385 # Determine the MIME type of the file from its extension
386 mime_type = MIME_TYPE_MAP.get(extension, MIME_TYPE_MAP[''])
387
388 # Open the file and send it over HTTP
389 if os.path.isfile(path):
390 with open(path, 'rb') as sending_file:
391 self.send_response(200)
392 self.send_header('Content-type', mime_type)
393 self.end_headers()
394 self.wfile.write(sending_file.read())
395 else:
396 self.send_error(404)
397
398 def send_json_dict(self, json_dict):
399 """ Send the contents of this dictionary in JSON format, with a JSON
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000400 mimetype.
401
402 Args:
403 json_dict: dictionary to send
404 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000405 self.send_response(200)
406 self.send_header('Content-type', 'application/json')
407 self.end_headers()
408 json.dump(json_dict, self.wfile)
409
410
411def main():
epoger@google.comdcb4e652013-10-11 18:45:33 +0000412 logging.basicConfig(level=logging.INFO)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000413 parser = argparse.ArgumentParser()
414 parser.add_argument('--actuals-dir',
415 help=('Directory into which we will check out the latest '
416 'actual GM results. If this directory does not '
417 'exist, it will be created. Defaults to %(default)s'),
418 default=DEFAULT_ACTUALS_DIR)
epoger@google.com542b65f2013-10-15 20:10:33 +0000419 parser.add_argument('--editable', action='store_true',
epoger@google.comeb832592013-10-23 15:07:26 +0000420 help=('Allow HTTP clients to submit new baselines.'))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000421 parser.add_argument('--expectations-dir',
422 help=('Directory under which to find GM expectations; '
423 'defaults to %(default)s'),
424 default=DEFAULT_EXPECTATIONS_DIR)
425 parser.add_argument('--export', action='store_true',
426 help=('Instead of only allowing access from HTTP clients '
427 'on localhost, allow HTTP clients on other hosts '
428 'to access this server. WARNING: doing so will '
429 'allow users on other hosts to modify your '
epoger@google.com542b65f2013-10-15 20:10:33 +0000430 'GM expectations, if combined with --editable.'))
epoger@google.comafaad3d2013-09-30 15:06:25 +0000431 parser.add_argument('--port', type=int,
432 help=('Which TCP port to listen on for HTTP requests; '
433 'defaults to %(default)s'),
434 default=DEFAULT_PORT)
epoger@google.com542b65f2013-10-15 20:10:33 +0000435 parser.add_argument('--reload', type=int,
436 help=('How often (a period in seconds) to update the '
437 'results. If specified, both EXPECTATIONS_DIR and '
438 'ACTUAL_DIR will be updated. '
439 'By default, we do not reload at all, and you '
440 'must restart the server to pick up new data.'),
441 default=0)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000442 args = parser.parse_args()
443 global _SERVER
epoger@google.com542b65f2013-10-15 20:10:33 +0000444 _SERVER = Server(actuals_dir=args.actuals_dir,
445 expectations_dir=args.expectations_dir,
446 port=args.port, export=args.export, editable=args.editable,
447 reload_seconds=args.reload)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000448 _SERVER.run()
449
450if __name__ == '__main__':
451 main()