1f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com#!/usr/bin/python
2f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
39fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com"""
4f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comCopyright 2013 Google Inc.
5f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
6f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comUse of this source code is governed by a BSD-style license that can be
7f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comfound in the LICENSE file.
8f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
9f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comHTTP server for our HTML rebaseline viewer.
109fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com"""
11f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
12f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com# System-level imports
13f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comimport argparse
14f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comimport BaseHTTPServer
15f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comimport json
16dcb4e65998913bfb2cc7e331ffacf0965bdee0eaepoger@google.comimport logging
17f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comimport os
18f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comimport posixpath
19f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comimport re
20f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comimport shutil
21b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.comimport socket
22d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.comimport subprocess
23542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.comimport thread
24d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.comimport threading
25542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.comimport time
26dcb4e65998913bfb2cc7e331ffacf0965bdee0eaepoger@google.comimport urlparse
27f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
28f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com# Imports from within Skia
29b144271179aaf82cb1151e9dfd8e866747402594epogerimport fix_pythonpath  # must do this first
30b144271179aaf82cb1151e9dfd8e866747402594epogerfrom pyutils import gs_utils
3131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgimport gm_json
32f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
33f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com# Imports from local dir
347498d95bde16eeaa4b20643fb930b6a3be7face1commit-bot@chromium.org#
357498d95bde16eeaa4b20643fb930b6a3be7face1commit-bot@chromium.org# Note: we import results under a different name, to avoid confusion with the
367498d95bde16eeaa4b20643fb930b6a3be7face1commit-bot@chromium.org# Server.results() property. See discussion at
377498d95bde16eeaa4b20643fb930b6a3be7face1commit-bot@chromium.org# https://codereview.chromium.org/195943004/diff/1/gm/rebaseline_server/server.py#newcode44
3831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgimport compare_configs
39b463d5668a498b672b80047f09901981afe513edcommit-bot@chromium.orgimport compare_to_expectations
40b144271179aaf82cb1151e9dfd8e866747402594epogerimport download_actuals
4116f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.orgimport imagepairset
427498d95bde16eeaa4b20643fb930b6a3be7face1commit-bot@chromium.orgimport results as results_mod
43f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
44f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comPATHSPLIT_RE = re.compile('/([^/]+)/(.+)')
45f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
46f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com# A simple dictionary of file name extensions to MIME types. The empty string
47f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com# entry is used as the default when no extension was given or if the extension
48f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com# has no entry in this dictionary.
49f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comMIME_TYPE_MAP = {'': 'application/octet-stream',
50f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                 'html': 'text/html',
51f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                 'css': 'text/css',
52f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                 'png': 'image/png',
53f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                 'js': 'application/javascript',
54f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                 'json': 'application/json'
55f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                 }
56f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
5716f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org# Keys that server.py uses to create the toplevel content header.
5816f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org# NOTE: Keep these in sync with static/constants.js
5916f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.orgKEY__EDITS__MODIFICATIONS = 'modifications'
6016f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.orgKEY__EDITS__OLD_RESULTS_HASH = 'oldResultsHash'
6116f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.orgKEY__EDITS__OLD_RESULTS_TYPE = 'oldResultsType'
627498d95bde16eeaa4b20643fb930b6a3be7face1commit-bot@chromium.org
6331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgDEFAULT_ACTUALS_DIR = results_mod.DEFAULT_ACTUALS_DIR
64b144271179aaf82cb1151e9dfd8e866747402594epogerDEFAULT_GM_SUMMARIES_BUCKET = download_actuals.GM_SUMMARIES_BUCKET
65b144271179aaf82cb1151e9dfd8e866747402594epogerDEFAULT_JSON_FILENAME = download_actuals.DEFAULT_JSON_FILENAME
66f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comDEFAULT_PORT = 8888
67f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
68b144271179aaf82cb1151e9dfd8e866747402594epogerPARENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
69b144271179aaf82cb1151e9dfd8e866747402594epogerTRUNK_DIRECTORY = os.path.dirname(os.path.dirname(PARENT_DIRECTORY))
7031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org# Directory, relative to PARENT_DIRECTORY, within which the server will serve
7131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org# out live results (not static files).
7231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgRESULTS_SUBDIR = 'results'
7331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org# Directory, relative to PARENT_DIRECTORY, within which the server will serve
7431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org# out static files.
7531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgSTATIC_CONTENTS_SUBDIR = 'static'
7631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org# All of the GENERATED_*_SUBDIRS are relative to STATIC_CONTENTS_SUBDIR
7731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgGENERATED_HTML_SUBDIR = 'generated-html'
7831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgGENERATED_IMAGES_SUBDIR = 'generated-images'
7931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgGENERATED_JSON_SUBDIR = 'generated-json'
80579942387bed9259b03419c593503022e1399931commit-bot@chromium.org
812682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com# How often (in seconds) clients should reload while waiting for initial
822682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com# results to load.
832682c90860655f6c25c61f97c8d8db309d03087aepoger@google.comRELOAD_INTERVAL_UNTIL_READY = 10
842682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com
8531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgSUMMARY_TYPES = [
8631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    results_mod.KEY__HEADER__RESULTS_FAILURES,
8731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    results_mod.KEY__HEADER__RESULTS_ALL,
8831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org]
8931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org# If --compare-configs is specified, compare these configs.
9031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgCONFIG_PAIRS_TO_COMPARE = [('8888', 'gpu')]
9131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
92eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com_HTTP_HEADER_CONTENT_LENGTH = 'Content-Length'
93eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com_HTTP_HEADER_CONTENT_TYPE = 'Content-Type'
94eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com
95f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com_SERVER = None   # This gets filled in by main()
96f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
97d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
98d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.comdef _run_command(args, directory):
99d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  """Runs a command and returns stdout as a single string.
100d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
101d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  Args:
102d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    args: the command to run, as a list of arguments
103d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    directory: directory within which to run the command
104d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
105d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  Returns: stdout, as a string
106d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
107d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  Raises an Exception if the command failed (exited with nonzero return code).
108d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  """
109d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  logging.debug('_run_command: %s in directory %s' % (args, directory))
110d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  proc = subprocess.Popen(args, cwd=directory,
111d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com                          stdout=subprocess.PIPE,
112d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com                          stderr=subprocess.PIPE)
113d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  (stdout, stderr) = proc.communicate()
114d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  if proc.returncode is not 0:
115d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    raise Exception('command "%s" failed in dir "%s": %s' %
116d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com                    (args, directory, stderr))
117d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  return stdout
118d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
119d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
120591469b1e93f72172cef13a2f0675699994d7848epoger@google.comdef _get_routable_ip_address():
121b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com  """Returns routable IP address of this host (the IP address of its network
122b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com     interface that would be used for most traffic, not its localhost
123b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com     interface).  See http://stackoverflow.com/a/166589 """
124b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
125b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com  sock.connect(('8.8.8.8', 80))
126b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com  host = sock.getsockname()[0]
127b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com  sock.close()
128b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com  return host
129b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com
130d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
13131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.orgdef _create_index(file_path, config_pairs):
13231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  """Creates an index file linking to all results available from this server.
13331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
13431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  Prior to https://codereview.chromium.org/215503002 , we had a static
13531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  index.html within our repo.  But now that the results may or may not include
13631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  config comparisons, index.html needs to be generated differently depending
13731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  on which results are included.
13831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
13931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  TODO(epoger): Instead of including raw HTML within the Python code,
14031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  consider restoring the index.html file as a template and using django (or
14131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  similar) to fill in dynamic content.
14231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
14331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  Args:
14431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    file_path: path on local disk to write index to; any directory components
14531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org               of this path that do not already exist will be created
14631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    config_pairs: what pairs of configs (if any) we compare actual results of
14731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  """
14831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  dir_path = os.path.dirname(file_path)
14931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  if not os.path.isdir(dir_path):
15031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    os.makedirs(dir_path)
15131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  with open(file_path, 'w') as file_handle:
15231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    file_handle.write(
15331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        '<!DOCTYPE html><html>'
15431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        '<head><title>rebaseline_server</title></head>'
15531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        '<body><ul>')
15631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    if SUMMARY_TYPES:
15731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      file_handle.write('<li>Expectations vs Actuals</li><ul>')
15831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      for summary_type in SUMMARY_TYPES:
15931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        file_handle.write(
16031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            '<li>'
16131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            '<a href="/%s/view.html#/view.html?resultsToLoad=/%s/%s">'
16231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            '%s</a></li>' % (
16331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                STATIC_CONTENTS_SUBDIR, RESULTS_SUBDIR,
16431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                summary_type, summary_type))
16531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      file_handle.write('</ul>')
16631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    if config_pairs:
16731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      file_handle.write('<li>Comparing configs within actual results</li><ul>')
16831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      for config_pair in config_pairs:
16931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        file_handle.write('<li>%s vs %s:' % config_pair)
17031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        for summary_type in SUMMARY_TYPES:
17131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org          file_handle.write(
17231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org              ' <a href="/%s/view.html#/view.html?'
17331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org              'resultsToLoad=/%s/%s/%s-vs-%s_%s.json">%s</a>' % (
17431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                  STATIC_CONTENTS_SUBDIR, STATIC_CONTENTS_SUBDIR,
17531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                  GENERATED_JSON_SUBDIR, config_pair[0], config_pair[1],
17631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                  summary_type, summary_type))
17731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        file_handle.write('</li>')
17831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      file_handle.write('</ul>')
17931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    file_handle.write('</ul></body></html>')
18031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
18131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
182f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comclass Server(object):
1839fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com  """ HTTP server for our HTML rebaseline viewer. """
1849fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com
185f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  def __init__(self,
186f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com               actuals_dir=DEFAULT_ACTUALS_DIR,
187b144271179aaf82cb1151e9dfd8e866747402594epoger               json_filename=DEFAULT_JSON_FILENAME,
188b144271179aaf82cb1151e9dfd8e866747402594epoger               gm_summaries_bucket=DEFAULT_GM_SUMMARIES_BUCKET,
189542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com               port=DEFAULT_PORT, export=False, editable=True,
190defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org               reload_seconds=0, config_pairs=None, builder_regex_list=None):
1919fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    """
1929fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    Args:
1939fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com      actuals_dir: directory under which we will check out the latest actual
194c0df2fb5d0421a649d1dff9133874e440300fa7ccommit-bot@chromium.org          GM results
195b144271179aaf82cb1151e9dfd8e866747402594epoger      json_filename: basename of the JSON summary file to load for each builder
196b144271179aaf82cb1151e9dfd8e866747402594epoger      gm_summaries_bucket: Google Storage bucket to download json_filename
197b144271179aaf82cb1151e9dfd8e866747402594epoger          files from; if None or '', don't fetch new actual-results files
198b144271179aaf82cb1151e9dfd8e866747402594epoger          at all, just compare to whatever files are already in actuals_dir
1999fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com      port: which TCP port to listen on for HTTP requests
2009fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com      export: whether to allow HTTP clients on other hosts to access this server
201542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com      editable: whether HTTP clients are allowed to submit new baselines
202542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com      reload_seconds: polling interval with which to check for new results;
203c0df2fb5d0421a649d1dff9133874e440300fa7ccommit-bot@chromium.org          if 0, don't check for new results at all
20431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      config_pairs: List of (string, string) tuples; for each tuple, compare
20531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org          actual results of these two configs.  If None or empty,
20631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org          don't compare configs at all.
207defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org      builder_regex_list: List of regular expressions specifying which builders
208defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org          we will process. If None, process all builders.
2099fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    """
210f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    self._actuals_dir = actuals_dir
211b144271179aaf82cb1151e9dfd8e866747402594epoger    self._json_filename = json_filename
212b144271179aaf82cb1151e9dfd8e866747402594epoger    self._gm_summaries_bucket = gm_summaries_bucket
213f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    self._port = port
214f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    self._export = export
215542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com    self._editable = editable
216542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com    self._reload_seconds = reload_seconds
21731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    self._config_pairs = config_pairs or []
218defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org    self._builder_regex_list = builder_regex_list
21931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    _create_index(
22031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        file_path=os.path.join(
22131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR, GENERATED_HTML_SUBDIR,
22231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            "index.html"),
22331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        config_pairs=config_pairs)
224591469b1e93f72172cef13a2f0675699994d7848epoger@google.com
225d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # Reentrant lock that must be held whenever updating EITHER of:
226d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # 1. self._results
227d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # 2. the expected or actual results on local disk
228d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    self.results_rlock = threading.RLock()
229d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # self._results will be filled in by calls to update_results()
230d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    self._results = None
231d7255b6ae43f1931d5ec086fe4e92a664e28ab6fepoger@google.com
232d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  @property
233d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  def results(self):
23450ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org    """ Returns the most recently generated results, or None if we don't have
23550ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org    any valid results (update_results() has not completed yet). """
236d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    return self._results
237d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
238d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  @property
2399fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com  def is_exported(self):
2409fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    """ Returns true iff HTTP clients on other hosts are allowed to access
2419fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    this server. """
2429fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    return self._export
2439fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com
244d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  @property
245542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com  def is_editable(self):
246542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com    """ Returns true iff HTTP clients are allowed to submit new baselines. """
247542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com    return self._editable
248542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com
249d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com  @property
250542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com  def reload_seconds(self):
251542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com    """ Returns the result reload period in seconds, or 0 if we don't reload
252542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com    results. """
253542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com    return self._reload_seconds
254f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
25550ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org  def update_results(self, invalidate=False):
2567498d95bde16eeaa4b20643fb930b6a3be7face1commit-bot@chromium.org    """ Create or update self._results, based on the latest expectations and
2577498d95bde16eeaa4b20643fb930b6a3be7face1commit-bot@chromium.org    actuals.
258d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
259d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    We hold self.results_rlock while we do this, to guarantee that no other
260d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    thread attempts to update either self._results or the underlying files at
261d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    the same time.
26250ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org
26350ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org    Args:
26450ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org      invalidate: if True, invalidate self._results immediately upon entry;
26550ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org                  otherwise, we will let readers see those results until we
26650ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org                  replace them
267f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    """
268d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    with self.results_rlock:
26950ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org      if invalidate:
27050ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org        self._results = None
271b144271179aaf82cb1151e9dfd8e866747402594epoger      if self._gm_summaries_bucket:
272c0df2fb5d0421a649d1dff9133874e440300fa7ccommit-bot@chromium.org        logging.info(
273b144271179aaf82cb1151e9dfd8e866747402594epoger            'Updating GM result summaries in %s from gm_summaries_bucket %s ...'
274b144271179aaf82cb1151e9dfd8e866747402594epoger            % (self._actuals_dir, self._gm_summaries_bucket))
275b144271179aaf82cb1151e9dfd8e866747402594epoger
276b144271179aaf82cb1151e9dfd8e866747402594epoger        # Clean out actuals_dir first, in case some builders have gone away
277b144271179aaf82cb1151e9dfd8e866747402594epoger        # since we last ran.
278b144271179aaf82cb1151e9dfd8e866747402594epoger        if os.path.isdir(self._actuals_dir):
279b144271179aaf82cb1151e9dfd8e866747402594epoger          shutil.rmtree(self._actuals_dir)
280b144271179aaf82cb1151e9dfd8e866747402594epoger
281b144271179aaf82cb1151e9dfd8e866747402594epoger        # Get the list of builders we care about.
282b144271179aaf82cb1151e9dfd8e866747402594epoger        all_builders = download_actuals.get_builders_list(
283b144271179aaf82cb1151e9dfd8e866747402594epoger            summaries_bucket=self._gm_summaries_bucket)
284b144271179aaf82cb1151e9dfd8e866747402594epoger        if self._builder_regex_list:
285b144271179aaf82cb1151e9dfd8e866747402594epoger          matching_builders = []
286b144271179aaf82cb1151e9dfd8e866747402594epoger          for builder in all_builders:
287b144271179aaf82cb1151e9dfd8e866747402594epoger            for regex in self._builder_regex_list:
288b144271179aaf82cb1151e9dfd8e866747402594epoger              if re.match(regex, builder):
289b144271179aaf82cb1151e9dfd8e866747402594epoger                matching_builders.append(builder)
290b144271179aaf82cb1151e9dfd8e866747402594epoger                break  # go on to the next builder, no need to try more regexes
291b144271179aaf82cb1151e9dfd8e866747402594epoger        else:
292b144271179aaf82cb1151e9dfd8e866747402594epoger          matching_builders = all_builders
293b144271179aaf82cb1151e9dfd8e866747402594epoger
294b144271179aaf82cb1151e9dfd8e866747402594epoger        # Download the JSON file for each builder we care about.
295b144271179aaf82cb1151e9dfd8e866747402594epoger        #
296b144271179aaf82cb1151e9dfd8e866747402594epoger        # TODO(epoger): When this is a large number of builders, we would be
297b144271179aaf82cb1151e9dfd8e866747402594epoger        # better off downloading them in parallel!
298b144271179aaf82cb1151e9dfd8e866747402594epoger        for builder in matching_builders:
299b144271179aaf82cb1151e9dfd8e866747402594epoger          gs_utils.download_file(
300b144271179aaf82cb1151e9dfd8e866747402594epoger              source_bucket=self._gm_summaries_bucket,
301b144271179aaf82cb1151e9dfd8e866747402594epoger              source_path=posixpath.join(builder, self._json_filename),
302b144271179aaf82cb1151e9dfd8e866747402594epoger              dest_path=os.path.join(self._actuals_dir, builder,
303b144271179aaf82cb1151e9dfd8e866747402594epoger                                     self._json_filename),
304b144271179aaf82cb1151e9dfd8e866747402594epoger              create_subdirs_if_needed=True)
305d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
306d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      # We only update the expectations dir if the server was run with a
307d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      # nonzero --reload argument; otherwise, we expect the user to maintain
308d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      # her own expectations as she sees fit.
309d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      #
310b144271179aaf82cb1151e9dfd8e866747402594epoger      # Because the Skia repo is hosted using git, and git does not
311d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      # support updating a single directory tree, we have to update the entire
312d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      # repo checkout.
313d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      #
314d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      # Because Skia uses depot_tools, we have to update using "gclient sync"
315b144271179aaf82cb1151e9dfd8e866747402594epoger      # instead of raw git commands.
316b144271179aaf82cb1151e9dfd8e866747402594epoger      #
317b144271179aaf82cb1151e9dfd8e866747402594epoger      # TODO(epoger): Fetch latest expectations in some other way.
318b144271179aaf82cb1151e9dfd8e866747402594epoger      # Eric points out that our official documentation recommends an
319b144271179aaf82cb1151e9dfd8e866747402594epoger      # unmanaged Skia checkout, so "gclient sync" will not bring down updated
320b144271179aaf82cb1151e9dfd8e866747402594epoger      # expectations from origin/master-- you'd have to do a "git pull" of
321b144271179aaf82cb1151e9dfd8e866747402594epoger      # some sort instead.
322b144271179aaf82cb1151e9dfd8e866747402594epoger      # However, the live rebaseline_server at
323b144271179aaf82cb1151e9dfd8e866747402594epoger      # http://skia-tree-status.appspot.com/redirect/rebaseline-server (which
324b144271179aaf82cb1151e9dfd8e866747402594epoger      # is probably the only user of the --reload flag!) uses a managed
325b144271179aaf82cb1151e9dfd8e866747402594epoger      # checkout, so "gclient sync" works in that case.
326b144271179aaf82cb1151e9dfd8e866747402594epoger      # Probably the best idea is to avoid all of this nonsense by fetching
327b144271179aaf82cb1151e9dfd8e866747402594epoger      # updated expectations into a temp directory, and leaving the rest of
328b144271179aaf82cb1151e9dfd8e866747402594epoger      # the checkout alone.  This could be done using "git show", or by
329b144271179aaf82cb1151e9dfd8e866747402594epoger      # downloading individual expectation JSON files from
330b144271179aaf82cb1151e9dfd8e866747402594epoger      # skia.googlesource.com .
331d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      if self._reload_seconds:
332d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com        logging.info(
333d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com            'Updating expected GM results in %s by syncing Skia repo ...' %
334b463d5668a498b672b80047f09901981afe513edcommit-bot@chromium.org            compare_to_expectations.DEFAULT_EXPECTATIONS_DIR)
335d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com        _run_command(['gclient', 'sync'], TRUNK_DIRECTORY)
336591469b1e93f72172cef13a2f0675699994d7848epoger@google.com
33731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      self._results = compare_to_expectations.ExpectationComparisons(
338579942387bed9259b03419c593503022e1399931commit-bot@chromium.org          actuals_root=self._actuals_dir,
339a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org          generated_images_root=os.path.join(
340a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org              PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR,
341a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org              GENERATED_IMAGES_SUBDIR),
342a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org          diff_base_url=posixpath.join(
343defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org              os.pardir, STATIC_CONTENTS_SUBDIR, GENERATED_IMAGES_SUBDIR),
344defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org          builder_regex_list=self._builder_regex_list)
345f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
34631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      json_dir = os.path.join(
34731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org          PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR, GENERATED_JSON_SUBDIR)
34831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      if not os.path.isdir(json_dir):
34931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org         os.makedirs(json_dir)
35031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
35131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org      for config_pair in self._config_pairs:
35231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        config_comparisons = compare_configs.ConfigComparisons(
35331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            configs=config_pair,
35431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            actuals_root=self._actuals_dir,
35531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            generated_images_root=os.path.join(
35631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR,
35731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                GENERATED_IMAGES_SUBDIR),
35831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            diff_base_url=posixpath.join(
359defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org                os.pardir, GENERATED_IMAGES_SUBDIR),
360defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org            builder_regex_list=self._builder_regex_list)
36131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        for summary_type in SUMMARY_TYPES:
36231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org          gm_json.WriteToFile(
36331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org              config_comparisons.get_packaged_results_of_type(
36431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                  results_type=summary_type),
36531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org              os.path.join(
36631d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                  json_dir, '%s-vs-%s_%s.json' % (
36731d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                      config_pair[0], config_pair[1], summary_type)))
36831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
3692682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com  def _result_loader(self, reload_seconds=0):
3702682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    """ Call self.update_results(), either once or periodically.
3712682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com
3722682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    Params:
3732682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com      reload_seconds: integer; if nonzero, reload results at this interval
3742682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com          (in which case, this method will never return!)
375542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com    """
3762682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    self.update_results()
3772682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    logging.info('Initial results loaded. Ready for requests on %s' % self._url)
3782682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    if reload_seconds:
3792682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com      while True:
3802682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com        time.sleep(reload_seconds)
3812682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com        self.update_results()
382542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com
383f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  def run(self):
3842682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    arg_tuple = (self._reload_seconds,)  # start_new_thread needs a tuple,
3852682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com                                         # even though it holds just one param
3862682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    thread.start_new_thread(self._result_loader, arg_tuple)
387542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com
388f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    if self._export:
389f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com      server_address = ('', self._port)
390591469b1e93f72172cef13a2f0675699994d7848epoger@google.com      host = _get_routable_ip_address()
391542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com      if self._editable:
392542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com        logging.warning('Running with combination of "export" and "editable" '
393542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com                        'flags.  Users on other machines will '
394542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com                        'be able to modify your GM expectations!')
395f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    else:
396b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com      host = '127.0.0.1'
397b08c707847be4b0c94adf592912b4e7073f71ecbepoger@google.com      server_address = (host, self._port)
398f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    http_server = BaseHTTPServer.HTTPServer(server_address, HTTPRequestHandler)
3992682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    self._url = 'http://%s:%d' % (host, http_server.server_port)
4002682c90860655f6c25c61f97c8d8db309d03087aepoger@google.com    logging.info('Listening for requests on %s' % self._url)
401f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    http_server.serve_forever()
402f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
403f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
404f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comclass HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
405f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  """ HTTP request handlers for various types of queries this server knows
406f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com      how to handle (static HTML and Javascript, expected/actual results, etc.)
407f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  """
408f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  def do_GET(self):
409e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org    """
410e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org    Handles all GET requests, forwarding them to the appropriate
411e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org    do_GET_* dispatcher.
412f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
413e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org    If we see any Exceptions, return a 404.  This fixes http://skbug.com/2147
414e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org    """
415e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org    try:
416e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      logging.debug('do_GET: path="%s"' % self.path)
417e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      if self.path == '' or self.path == '/' or self.path == '/index.html' :
41831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org        self.redirect_to('/%s/%s/index.html' % (
41931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org            STATIC_CONTENTS_SUBDIR, GENERATED_HTML_SUBDIR))
420e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org        return
421e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      if self.path == '/favicon.ico' :
422a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org        self.redirect_to('/%s/favicon.ico' % STATIC_CONTENTS_SUBDIR)
423e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org        return
424e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org
425e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      # All requests must be of this form:
426e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      #   /dispatcher/remainder
427e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      # where 'dispatcher' indicates which do_GET_* dispatcher to run
428e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      # and 'remainder' is the remaining path sent to that dispatcher.
429e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      normpath = posixpath.normpath(self.path)
430e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      (dispatcher_name, remainder) = PATHSPLIT_RE.match(normpath).groups()
431e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      dispatchers = {
43231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org          RESULTS_SUBDIR: self.do_GET_results,
43331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org          STATIC_CONTENTS_SUBDIR: self.do_GET_static,
434e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      }
435e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      dispatcher = dispatchers[dispatcher_name]
436e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      dispatcher(remainder)
437e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org    except:
438e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      self.send_error(404)
439e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org      raise
440f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
441a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org  def do_GET_results(self, results_type):
442a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    """ Handle a GET request for GM results.
443a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org
444a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    Args:
445a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org      results_type: string indicating which set of results to return;
446a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org            must be one of the results_mod.RESULTS_* constants
447a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    """
448a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    logging.debug('do_GET_results: sending results of type "%s"' % results_type)
44931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    # Since we must make multiple calls to the ExpectationComparisons object,
45031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    # grab a reference to it in case it is updated to point at a new
45131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    # ExpectationComparisons object within another thread.
452a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    #
453a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    # TODO(epoger): Rather than using a global variable for the handler
454a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    # to refer to the Server object, make Server a subclass of
455a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    # HTTPServer, and then it could be available to the handler via
456a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    # the handler's .server instance variable.
457a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    results_obj = _SERVER.results
458a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    if results_obj:
459a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org      response_dict = results_obj.get_packaged_results_of_type(
460a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org          results_type=results_type, reload_seconds=_SERVER.reload_seconds,
461a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org          is_editable=_SERVER.is_editable, is_exported=_SERVER.is_exported)
462a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    else:
463a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org      now = int(time.time())
464a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org      response_dict = {
46568a3815401f461976f76891d0477cb1440fa0abacommit-bot@chromium.org          imagepairset.KEY__ROOT__HEADER: {
466a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org              results_mod.KEY__HEADER__SCHEMA_VERSION: (
46768a3815401f461976f76891d0477cb1440fa0abacommit-bot@chromium.org                  results_mod.VALUE__HEADER__SCHEMA_VERSION),
468a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org              results_mod.KEY__HEADER__IS_STILL_LOADING: True,
469a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org              results_mod.KEY__HEADER__TIME_UPDATED: now,
470a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org              results_mod.KEY__HEADER__TIME_NEXT_UPDATE_AVAILABLE: (
471a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org                  now + RELOAD_INTERVAL_UNTIL_READY),
472a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org          },
473a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org      }
474a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    self.send_json_dict(response_dict)
475a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org
476f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  def do_GET_static(self, path):
477a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    """ Handle a GET request for a file under STATIC_CONTENTS_SUBDIR .
478a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    Only allow serving of files within STATIC_CONTENTS_SUBDIR that is a
4799fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    filesystem sibling of this script.
4809fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com
4819fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    Args:
482a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org      path: path to file (within STATIC_CONTENTS_SUBDIR) to retrieve
4839fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    """
484dcb4e65998913bfb2cc7e331ffacf0965bdee0eaepoger@google.com    # Strip arguments ('?resultsToLoad=all') from the path
485dcb4e65998913bfb2cc7e331ffacf0965bdee0eaepoger@google.com    path = urlparse.urlparse(path).path
486dcb4e65998913bfb2cc7e331ffacf0965bdee0eaepoger@google.com
487dcb4e65998913bfb2cc7e331ffacf0965bdee0eaepoger@google.com    logging.debug('do_GET_static: sending file "%s"' % path)
488a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    static_dir = os.path.realpath(os.path.join(
489a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org        PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR))
490a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    full_path = os.path.realpath(os.path.join(static_dir, path))
491a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    if full_path.startswith(static_dir):
492cb55f11a8f8ad66cdfc7643298a8772837cc35dfepoger@google.com      self.send_file(full_path)
493cb55f11a8f8ad66cdfc7643298a8772837cc35dfepoger@google.com    else:
494dcb4e65998913bfb2cc7e331ffacf0965bdee0eaepoger@google.com      logging.error(
495dcb4e65998913bfb2cc7e331ffacf0965bdee0eaepoger@google.com          'Attempted do_GET_static() of path [%s] outside of static dir [%s]'
496a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org          % (full_path, static_dir))
497cb55f11a8f8ad66cdfc7643298a8772837cc35dfepoger@google.com      self.send_error(404)
498f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
499eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com  def do_POST(self):
500eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    """ Handles all POST requests, forwarding them to the appropriate
501eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com        do_POST_* dispatcher. """
502eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    # All requests must be of this form:
503eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    #   /dispatcher
504eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    # where 'dispatcher' indicates which do_POST_* dispatcher to run.
505e6af4fb34bd780ff24e0e967a8dc73639ccc2a9dcommit-bot@chromium.org    logging.debug('do_POST: path="%s"' % self.path)
506eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    normpath = posixpath.normpath(self.path)
507eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    dispatchers = {
508eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      '/edits': self.do_POST_edits,
509eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    }
510eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    try:
511eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      dispatcher = dispatchers[normpath]
512eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      dispatcher()
513eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      self.send_response(200)
514eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    except:
515eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      self.send_error(404)
516eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      raise
517eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com
518eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com  def do_POST_edits(self):
519eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    """ Handle a POST request with modifications to GM expectations, in this
520eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    format:
521eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com
522eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    {
52316f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org      KEY__EDITS__OLD_RESULTS_TYPE: 'all',  # type of results that the client
52416f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org                                            # loaded and then made
52516f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org                                            # modifications to
52616f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org      KEY__EDITS__OLD_RESULTS_HASH: 39850913, # hash of results when the client
52716f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org                                              # loaded them (ensures that the
52816f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org                                              # client and server apply
52916f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org                                              # modifications to the same base)
53016f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org      KEY__EDITS__MODIFICATIONS: [
531b463d5668a498b672b80047f09901981afe513edcommit-bot@chromium.org        # as needed by compare_to_expectations.edit_expectations()
532eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com        ...
533eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      ],
534eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    }
535eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com
536eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    Raises an Exception if there were any problems.
537eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    """
538d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    if not _SERVER.is_editable:
539eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      raise Exception('this server is not running in --editable mode')
540eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com
541eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE]
542eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    if content_type != 'application/json;charset=UTF-8':
543eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com      raise Exception('unsupported %s [%s]' % (
544eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com          _HTTP_HEADER_CONTENT_TYPE, content_type))
545eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com
546eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    content_length = int(self.headers[_HTTP_HEADER_CONTENT_LENGTH])
547eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    json_data = self.rfile.read(content_length)
548eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    data = json.loads(json_data)
549eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com    logging.debug('do_POST_edits: received new GM expectations data [%s]' %
550eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com                  data)
551eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com
552d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # Update the results on disk with the information we received from the
553d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # client.
554d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # We must hold _SERVER.results_rlock while we do this, to guarantee that
555d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # no other thread updates expectations (from the Skia repo) while we are
556d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    # updating them (using the info we received from the client).
557d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com    with _SERVER.results_rlock:
55816f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org      oldResultsType = data[KEY__EDITS__OLD_RESULTS_TYPE]
559d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com      oldResults = _SERVER.results.get_results_of_type(oldResultsType)
56068a3815401f461976f76891d0477cb1440fa0abacommit-bot@chromium.org      oldResultsHash = str(hash(repr(
56168a3815401f461976f76891d0477cb1440fa0abacommit-bot@chromium.org          oldResults[imagepairset.KEY__ROOT__IMAGEPAIRS])))
56216f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org      if oldResultsHash != data[KEY__EDITS__OLD_RESULTS_HASH]:
563d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com        raise Exception('results of type "%s" changed while the client was '
564d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com                        'making modifications. The client should reload the '
565d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com                        'results and submit the modifications again.' %
566d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com                        oldResultsType)
56716f418080ff6751e15e0193263149412de9c848acommit-bot@chromium.org      _SERVER.results.edit_expectations(data[KEY__EDITS__MODIFICATIONS])
56850ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org
56950ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org    # Read the updated results back from disk.
57050ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org    # We can do this in a separate thread; we should return our success message
57150ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org    # to the UI as soon as possible.
57250ad8e4d8efcd04f8a2c34cc32f6fecb3985a1a4commit-bot@chromium.org    thread.start_new_thread(_SERVER.update_results, (True,))
573eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com
574f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  def redirect_to(self, url):
5759fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    """ Redirect the HTTP client to a different url.
5769fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com
5779fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    Args:
5789fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com      url: URL to redirect the HTTP client to
5799fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    """
580f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    self.send_response(301)
581f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    self.send_header('Location', url)
582f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    self.end_headers()
583f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
584f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  def send_file(self, path):
585f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    """ Send the contents of the file at this path, with a mimetype based
5869fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com        on the filename extension.
5879fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com
5889fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    Args:
5899fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com      path: path of file whose contents to send to the HTTP client
5909fb6c8ac9ce7dd5d3319b4e3affd5f1e051162a2epoger@google.com    """
591f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    # Grab the extension if there is one
592f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    extension = os.path.splitext(path)[1]
593f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    if len(extension) >= 1:
594f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com      extension = extension[1:]
595f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
596f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    # Determine the MIME type of the file from its extension
597f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    mime_type = MIME_TYPE_MAP.get(extension, MIME_TYPE_MAP[''])
598f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
599f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    # Open the file and send it over HTTP
600f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    if os.path.isfile(path):
601f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com      with open(path, 'rb') as sending_file:
602f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com        self.send_response(200)
603f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com        self.send_header('Content-type', mime_type)
604f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com        self.end_headers()
605f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com        self.wfile.write(sending_file.read())
606f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com    else:
607f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com      self.send_error(404)
608f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
609a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org  def send_json_dict(self, json_dict):
610a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    """ Send the contents of this dictionary in JSON format, with a JSON
611a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org        mimetype.
612a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org
613a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    Args:
614a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org      json_dict: dictionary to send
615a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    """
616a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    self.send_response(200)
617a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    self.send_header('Content-type', 'application/json')
618a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    self.end_headers()
619a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org    json.dump(json_dict, self.wfile)
620a25c4e4fefd10980e2a4701607e494513a6c60b5commit-bot@chromium.org
621f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
622f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comdef main():
623a6ecbb8414b017fcb262e645fffc5a3129ecdf43commit-bot@chromium.org  logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
624a6ecbb8414b017fcb262e645fffc5a3129ecdf43commit-bot@chromium.org                      datefmt='%m/%d/%Y %H:%M:%S',
625a6ecbb8414b017fcb262e645fffc5a3129ecdf43commit-bot@chromium.org                      level=logging.INFO)
626f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  parser = argparse.ArgumentParser()
627f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  parser.add_argument('--actuals-dir',
628f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                    help=('Directory into which we will check out the latest '
629f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                          'actual GM results. If this directory does not '
630f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                          'exist, it will be created. Defaults to %(default)s'),
631f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                    default=DEFAULT_ACTUALS_DIR)
632b144271179aaf82cb1151e9dfd8e866747402594epoger  # TODO(epoger): Before https://codereview.chromium.org/310093003 ,
633b144271179aaf82cb1151e9dfd8e866747402594epoger  # when this tool downloaded the JSON summaries from skia-autogen,
634b144271179aaf82cb1151e9dfd8e866747402594epoger  # it had an --actuals-revision the caller could specify to download
635b144271179aaf82cb1151e9dfd8e866747402594epoger  # actual results as of a specific point in time.  We should add similar
636b144271179aaf82cb1151e9dfd8e866747402594epoger  # functionality when retrieving the summaries from Google Storage.
637defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org  parser.add_argument('--builders', metavar='BUILDER_REGEX', nargs='+',
638defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org                      help=('Only process builders matching these regular '
639defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org                            'expressions.  If unspecified, process all '
640defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org                            'builders.'))
64131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  parser.add_argument('--compare-configs', action='store_true',
64231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                      help=('In addition to generating differences between '
64331d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                            'expectations and actuals, also generate '
64431d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                            'differences between these config pairs: '
64531d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org                            + str(CONFIG_PAIRS_TO_COMPARE)))
646542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com  parser.add_argument('--editable', action='store_true',
647eb832599b631a09b180ea3615347adba6bd5e363epoger@google.com                      help=('Allow HTTP clients to submit new baselines.'))
648f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  parser.add_argument('--export', action='store_true',
649f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                      help=('Instead of only allowing access from HTTP clients '
650f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                            'on localhost, allow HTTP clients on other hosts '
651f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                            'to access this server.  WARNING: doing so will '
652f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com                            'allow users on other hosts to modify your '
653542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com                            'GM expectations, if combined with --editable.'))
654b144271179aaf82cb1151e9dfd8e866747402594epoger  parser.add_argument('--gm-summaries-bucket',
655b144271179aaf82cb1151e9dfd8e866747402594epoger                    help=('Google Cloud Storage bucket to download '
656b144271179aaf82cb1151e9dfd8e866747402594epoger                          'JSON_FILENAME files from. '
657b144271179aaf82cb1151e9dfd8e866747402594epoger                          'Defaults to %(default)s ; if set to '
658b144271179aaf82cb1151e9dfd8e866747402594epoger                          'empty string, just compare to actual-results '
659b144271179aaf82cb1151e9dfd8e866747402594epoger                          'already found in ACTUALS_DIR.'),
660b144271179aaf82cb1151e9dfd8e866747402594epoger                    default=DEFAULT_GM_SUMMARIES_BUCKET)
661b144271179aaf82cb1151e9dfd8e866747402594epoger  parser.add_argument('--json-filename',
662b144271179aaf82cb1151e9dfd8e866747402594epoger                    help=('JSON summary filename to read for each builder; '
663b144271179aaf82cb1151e9dfd8e866747402594epoger                          'defaults to %(default)s.'),
664b144271179aaf82cb1151e9dfd8e866747402594epoger                    default=DEFAULT_JSON_FILENAME)
665afaad3dd7002feb6e69983ddc4e5148d7803baedepoger@google.com  parser.add_argument('--port', type=int,
666afaad3dd7002feb6e69983ddc4e5148d7803baedepoger@google.com                      help=('Which TCP port to listen on for HTTP requests; '
667afaad3dd7002feb6e69983ddc4e5148d7803baedepoger@google.com                            'defaults to %(default)s'),
668afaad3dd7002feb6e69983ddc4e5148d7803baedepoger@google.com                      default=DEFAULT_PORT)
669542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com  parser.add_argument('--reload', type=int,
670542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com                      help=('How often (a period in seconds) to update the '
671b063e13428cef96abda9a80b273c92e2ed9c8287epoger@google.com                            'results.  If specified, both expected and actual '
672d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com                            'results will be updated by running "gclient sync" '
673d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com                            'on your Skia checkout as a whole.  '
674542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com                            'By default, we do not reload at all, and you '
675542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com                            'must restart the server to pick up new data.'),
676542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com                      default=0)
677f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  args = parser.parse_args()
67831d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  if args.compare_configs:
67931d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    config_pairs = CONFIG_PAIRS_TO_COMPARE
68031d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org  else:
68131d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org    config_pairs = None
68231d0b3d806a1aa86b7edaa442b3821f5d548e184commit-bot@chromium.org
683f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  global _SERVER
684542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com  _SERVER = Server(actuals_dir=args.actuals_dir,
685b144271179aaf82cb1151e9dfd8e866747402594epoger                   json_filename=args.json_filename,
686b144271179aaf82cb1151e9dfd8e866747402594epoger                   gm_summaries_bucket=args.gm_summaries_bucket,
687542b65f2347f571d1361df5a71844ebe24f1351cepoger@google.com                   port=args.port, export=args.export, editable=args.editable,
688defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org                   reload_seconds=args.reload, config_pairs=config_pairs,
689defe6fdbc8edb2df0887c007450a8d8cc446f420commit-bot@chromium.org                   builder_regex_list=args.builders)
690f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  _SERVER.run()
691f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com
692d6bab0238655dbab24dfe92bd0b16b464310a8c7rmistry@google.com
693f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.comif __name__ == '__main__':
694f9d134da93b8c78e7127efd84c9a26f99a73527eepoger@google.com  main()
695