blob: dff95045d77dfe580f4b4794fddcd86fe471d47d [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
rmistry@google.comd6bab022013-12-02 13:50:38 +000022import subprocess
epoger@google.comf9d134d2013-09-27 15:02:44 +000023import sys
epoger@google.com542b65f2013-10-15 20:10:33 +000024import thread
rmistry@google.comd6bab022013-12-02 13:50:38 +000025import threading
epoger@google.com542b65f2013-10-15 20:10:33 +000026import time
epoger@google.comdcb4e652013-10-11 18:45:33 +000027import urlparse
epoger@google.comf9d134d2013-09-27 15:02:44 +000028
29# Imports from within Skia
30#
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +000031# We need to add the 'tools' directory, so that we can import svn.py within
32# that directory.
33# Make sure that the 'tools' dir is in the PYTHONPATH, but add it at the *end*
epoger@google.comf9d134d2013-09-27 15:02:44 +000034# so any dirs that are already in the PYTHONPATH will be preferred.
epoger@google.comcb55f112013-10-02 19:27:35 +000035PARENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +000036TRUNK_DIRECTORY = os.path.dirname(os.path.dirname(PARENT_DIRECTORY))
epoger@google.comf9d134d2013-09-27 15:02:44 +000037TOOLS_DIRECTORY = os.path.join(TRUNK_DIRECTORY, 'tools')
38if TOOLS_DIRECTORY not in sys.path:
39 sys.path.append(TOOLS_DIRECTORY)
40import svn
41
42# Imports from local dir
commit-bot@chromium.org7498d952014-03-13 14:56:29 +000043#
44# Note: we import results under a different name, to avoid confusion with the
45# Server.results() property. See discussion at
46# https://codereview.chromium.org/195943004/diff/1/gm/rebaseline_server/server.py#newcode44
commit-bot@chromium.orgb463d562014-03-21 17:54:14 +000047import compare_to_expectations
commit-bot@chromium.org16f41802014-02-26 19:05:20 +000048import imagepairset
commit-bot@chromium.org7498d952014-03-13 14:56:29 +000049import results as results_mod
epoger@google.comf9d134d2013-09-27 15:02:44 +000050
epoger@google.comf9d134d2013-09-27 15:02:44 +000051PATHSPLIT_RE = re.compile('/([^/]+)/(.+)')
epoger@google.comf9d134d2013-09-27 15:02:44 +000052
53# A simple dictionary of file name extensions to MIME types. The empty string
54# entry is used as the default when no extension was given or if the extension
55# has no entry in this dictionary.
56MIME_TYPE_MAP = {'': 'application/octet-stream',
57 'html': 'text/html',
58 'css': 'text/css',
59 'png': 'image/png',
60 'js': 'application/javascript',
61 'json': 'application/json'
62 }
63
commit-bot@chromium.org16f41802014-02-26 19:05:20 +000064# Keys that server.py uses to create the toplevel content header.
65# NOTE: Keep these in sync with static/constants.js
66KEY__EDITS__MODIFICATIONS = 'modifications'
67KEY__EDITS__OLD_RESULTS_HASH = 'oldResultsHash'
68KEY__EDITS__OLD_RESULTS_TYPE = 'oldResultsType'
commit-bot@chromium.org16f41802014-02-26 19:05:20 +000069
commit-bot@chromium.orgb463d562014-03-21 17:54:14 +000070DEFAULT_ACTUALS_DIR = compare_to_expectations.DEFAULT_ACTUALS_DIR
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +000071DEFAULT_ACTUALS_REPO_REVISION = 'HEAD'
72DEFAULT_ACTUALS_REPO_URL = 'http://skia-autogen.googlecode.com/svn/gm-actual'
epoger@google.comf9d134d2013-09-27 15:02:44 +000073DEFAULT_PORT = 8888
74
commit-bot@chromium.org57994232014-03-20 17:27:46 +000075# Directory within which the server will serve out static files.
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +000076STATIC_CONTENTS_SUBDIR = 'static' # within PARENT_DIR
77GENERATED_IMAGES_SUBDIR = 'generated-images' # within STATIC_CONTENTS_SUBDIR
commit-bot@chromium.org57994232014-03-20 17:27:46 +000078
epoger@google.com2682c902013-12-05 16:05:16 +000079# How often (in seconds) clients should reload while waiting for initial
80# results to load.
81RELOAD_INTERVAL_UNTIL_READY = 10
82
epoger@google.comeb832592013-10-23 15:07:26 +000083_HTTP_HEADER_CONTENT_LENGTH = 'Content-Length'
84_HTTP_HEADER_CONTENT_TYPE = 'Content-Type'
85
epoger@google.comf9d134d2013-09-27 15:02:44 +000086_SERVER = None # This gets filled in by main()
87
rmistry@google.comd6bab022013-12-02 13:50:38 +000088
89def _run_command(args, directory):
90 """Runs a command and returns stdout as a single string.
91
92 Args:
93 args: the command to run, as a list of arguments
94 directory: directory within which to run the command
95
96 Returns: stdout, as a string
97
98 Raises an Exception if the command failed (exited with nonzero return code).
99 """
100 logging.debug('_run_command: %s in directory %s' % (args, directory))
101 proc = subprocess.Popen(args, cwd=directory,
102 stdout=subprocess.PIPE,
103 stderr=subprocess.PIPE)
104 (stdout, stderr) = proc.communicate()
105 if proc.returncode is not 0:
106 raise Exception('command "%s" failed in dir "%s": %s' %
107 (args, directory, stderr))
108 return stdout
109
110
epoger@google.com591469b2013-11-20 19:58:06 +0000111def _get_routable_ip_address():
epoger@google.comb08c7072013-10-30 14:09:04 +0000112 """Returns routable IP address of this host (the IP address of its network
113 interface that would be used for most traffic, not its localhost
114 interface). See http://stackoverflow.com/a/166589 """
115 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
116 sock.connect(('8.8.8.8', 80))
117 host = sock.getsockname()[0]
118 sock.close()
119 return host
120
rmistry@google.comd6bab022013-12-02 13:50:38 +0000121
epoger@google.com591469b2013-11-20 19:58:06 +0000122def _create_svn_checkout(dir_path, repo_url):
123 """Creates local checkout of an SVN repository at the specified directory
124 path, returning an svn.Svn object referring to the local checkout.
125
126 Args:
127 dir_path: path to the local checkout; if this directory does not yet exist,
128 it will be created and the repo will be checked out into it
129 repo_url: URL of SVN repo to check out into dir_path (unless the local
130 checkout already exists)
131 Returns: an svn.Svn object referring to the local checkout.
132 """
133 local_checkout = svn.Svn(dir_path)
134 if not os.path.isdir(dir_path):
135 os.makedirs(dir_path)
136 local_checkout.Checkout(repo_url, '.')
137 return local_checkout
138
epoger@google.comb08c7072013-10-30 14:09:04 +0000139
epoger@google.comf9d134d2013-09-27 15:02:44 +0000140class Server(object):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000141 """ HTTP server for our HTML rebaseline viewer. """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000142
epoger@google.comf9d134d2013-09-27 15:02:44 +0000143 def __init__(self,
144 actuals_dir=DEFAULT_ACTUALS_DIR,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000145 actuals_repo_revision=DEFAULT_ACTUALS_REPO_REVISION,
146 actuals_repo_url=DEFAULT_ACTUALS_REPO_URL,
epoger@google.com542b65f2013-10-15 20:10:33 +0000147 port=DEFAULT_PORT, export=False, editable=True,
148 reload_seconds=0):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000149 """
150 Args:
151 actuals_dir: directory under which we will check out the latest actual
commit-bot@chromium.orgc0df2fb2014-03-28 14:28:04 +0000152 GM results
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000153 actuals_repo_revision: revision of actual-results.json files to process
commit-bot@chromium.orgc0df2fb2014-03-28 14:28:04 +0000154 actuals_repo_url: SVN repo to download actual-results.json files from;
155 if None or '', don't fetch new actual-results files at all,
156 just compare to whatever files are already in actuals_dir
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000157 port: which TCP port to listen on for HTTP requests
158 export: whether to allow HTTP clients on other hosts to access this server
epoger@google.com542b65f2013-10-15 20:10:33 +0000159 editable: whether HTTP clients are allowed to submit new baselines
160 reload_seconds: polling interval with which to check for new results;
commit-bot@chromium.orgc0df2fb2014-03-28 14:28:04 +0000161 if 0, don't check for new results at all
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000162 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000163 self._actuals_dir = actuals_dir
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000164 self._actuals_repo_revision = actuals_repo_revision
165 self._actuals_repo_url = actuals_repo_url
epoger@google.comf9d134d2013-09-27 15:02:44 +0000166 self._port = port
167 self._export = export
epoger@google.com542b65f2013-10-15 20:10:33 +0000168 self._editable = editable
169 self._reload_seconds = reload_seconds
commit-bot@chromium.orgc0df2fb2014-03-28 14:28:04 +0000170 if actuals_repo_url:
171 self._actuals_repo = _create_svn_checkout(
172 dir_path=actuals_dir, repo_url=actuals_repo_url)
epoger@google.com591469b2013-11-20 19:58:06 +0000173
rmistry@google.comd6bab022013-12-02 13:50:38 +0000174 # Reentrant lock that must be held whenever updating EITHER of:
175 # 1. self._results
176 # 2. the expected or actual results on local disk
177 self.results_rlock = threading.RLock()
178 # self._results will be filled in by calls to update_results()
179 self._results = None
epoger@google.comf9d134d2013-09-27 15:02:44 +0000180
rmistry@google.comd6bab022013-12-02 13:50:38 +0000181 @property
182 def results(self):
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000183 """ Returns the most recently generated results, or None if we don't have
184 any valid results (update_results() has not completed yet). """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000185 return self._results
186
187 @property
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000188 def is_exported(self):
189 """ Returns true iff HTTP clients on other hosts are allowed to access
190 this server. """
191 return self._export
192
rmistry@google.comd6bab022013-12-02 13:50:38 +0000193 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000194 def is_editable(self):
195 """ Returns true iff HTTP clients are allowed to submit new baselines. """
196 return self._editable
epoger@google.comf9d134d2013-09-27 15:02:44 +0000197
rmistry@google.comd6bab022013-12-02 13:50:38 +0000198 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000199 def reload_seconds(self):
200 """ Returns the result reload period in seconds, or 0 if we don't reload
201 results. """
202 return self._reload_seconds
203
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000204 def update_results(self, invalidate=False):
commit-bot@chromium.org7498d952014-03-13 14:56:29 +0000205 """ Create or update self._results, based on the latest expectations and
206 actuals.
rmistry@google.comd6bab022013-12-02 13:50:38 +0000207
208 We hold self.results_rlock while we do this, to guarantee that no other
209 thread attempts to update either self._results or the underlying files at
210 the same time.
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000211
212 Args:
213 invalidate: if True, invalidate self._results immediately upon entry;
214 otherwise, we will let readers see those results until we
215 replace them
epoger@google.comf9d134d2013-09-27 15:02:44 +0000216 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000217 with self.results_rlock:
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000218 if invalidate:
219 self._results = None
commit-bot@chromium.orgc0df2fb2014-03-28 14:28:04 +0000220 if self._actuals_repo_url:
221 logging.info(
222 'Updating actual GM results in %s to revision %s from repo %s ...'
223 % (
224 self._actuals_dir, self._actuals_repo_revision,
225 self._actuals_repo_url))
226 self._actuals_repo.Update(
227 path='.', revision=self._actuals_repo_revision)
epoger@google.com591469b2013-11-20 19:58:06 +0000228
rmistry@google.comd6bab022013-12-02 13:50:38 +0000229 # We only update the expectations dir if the server was run with a
230 # nonzero --reload argument; otherwise, we expect the user to maintain
231 # her own expectations as she sees fit.
232 #
233 # Because the Skia repo is moving from SVN to git, and git does not
234 # support updating a single directory tree, we have to update the entire
235 # repo checkout.
236 #
237 # Because Skia uses depot_tools, we have to update using "gclient sync"
238 # instead of raw git (or SVN) update. Happily, this will work whether
239 # the checkout was created using git or SVN.
240 if self._reload_seconds:
241 logging.info(
242 'Updating expected GM results in %s by syncing Skia repo ...' %
commit-bot@chromium.orgb463d562014-03-21 17:54:14 +0000243 compare_to_expectations.DEFAULT_EXPECTATIONS_DIR)
rmistry@google.comd6bab022013-12-02 13:50:38 +0000244 _run_command(['gclient', 'sync'], TRUNK_DIRECTORY)
245
commit-bot@chromium.orgb463d562014-03-21 17:54:14 +0000246 self._results = compare_to_expectations.Results(
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000247 actuals_root=self._actuals_dir,
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000248 generated_images_root=os.path.join(
249 PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR,
250 GENERATED_IMAGES_SUBDIR),
251 diff_base_url=posixpath.join(
252 os.pardir, STATIC_CONTENTS_SUBDIR, GENERATED_IMAGES_SUBDIR))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000253
epoger@google.com2682c902013-12-05 16:05:16 +0000254 def _result_loader(self, reload_seconds=0):
255 """ Call self.update_results(), either once or periodically.
256
257 Params:
258 reload_seconds: integer; if nonzero, reload results at this interval
259 (in which case, this method will never return!)
epoger@google.com542b65f2013-10-15 20:10:33 +0000260 """
epoger@google.com2682c902013-12-05 16:05:16 +0000261 self.update_results()
262 logging.info('Initial results loaded. Ready for requests on %s' % self._url)
263 if reload_seconds:
264 while True:
265 time.sleep(reload_seconds)
266 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000267
epoger@google.comf9d134d2013-09-27 15:02:44 +0000268 def run(self):
epoger@google.com2682c902013-12-05 16:05:16 +0000269 arg_tuple = (self._reload_seconds,) # start_new_thread needs a tuple,
270 # even though it holds just one param
271 thread.start_new_thread(self._result_loader, arg_tuple)
epoger@google.com542b65f2013-10-15 20:10:33 +0000272
epoger@google.comf9d134d2013-09-27 15:02:44 +0000273 if self._export:
274 server_address = ('', self._port)
epoger@google.com591469b2013-11-20 19:58:06 +0000275 host = _get_routable_ip_address()
epoger@google.com542b65f2013-10-15 20:10:33 +0000276 if self._editable:
277 logging.warning('Running with combination of "export" and "editable" '
278 'flags. Users on other machines will '
279 'be able to modify your GM expectations!')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000280 else:
epoger@google.comb08c7072013-10-30 14:09:04 +0000281 host = '127.0.0.1'
282 server_address = (host, self._port)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000283 http_server = BaseHTTPServer.HTTPServer(server_address, HTTPRequestHandler)
epoger@google.com2682c902013-12-05 16:05:16 +0000284 self._url = 'http://%s:%d' % (host, http_server.server_port)
285 logging.info('Listening for requests on %s' % self._url)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000286 http_server.serve_forever()
287
288
289class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
290 """ HTTP request handlers for various types of queries this server knows
291 how to handle (static HTML and Javascript, expected/actual results, etc.)
292 """
293 def do_GET(self):
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000294 """
295 Handles all GET requests, forwarding them to the appropriate
296 do_GET_* dispatcher.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000297
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000298 If we see any Exceptions, return a 404. This fixes http://skbug.com/2147
299 """
300 try:
301 logging.debug('do_GET: path="%s"' % self.path)
302 if self.path == '' or self.path == '/' or self.path == '/index.html' :
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000303 self.redirect_to('/%s/index.html' % STATIC_CONTENTS_SUBDIR)
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000304 return
305 if self.path == '/favicon.ico' :
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000306 self.redirect_to('/%s/favicon.ico' % STATIC_CONTENTS_SUBDIR)
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000307 return
308
309 # All requests must be of this form:
310 # /dispatcher/remainder
311 # where 'dispatcher' indicates which do_GET_* dispatcher to run
312 # and 'remainder' is the remaining path sent to that dispatcher.
313 normpath = posixpath.normpath(self.path)
314 (dispatcher_name, remainder) = PATHSPLIT_RE.match(normpath).groups()
315 dispatchers = {
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000316 'results': self.do_GET_results,
317 STATIC_CONTENTS_SUBDIR: self.do_GET_static,
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000318 }
319 dispatcher = dispatchers[dispatcher_name]
320 dispatcher(remainder)
321 except:
322 self.send_error(404)
323 raise
epoger@google.comf9d134d2013-09-27 15:02:44 +0000324
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000325 def do_GET_results(self, results_type):
326 """ Handle a GET request for GM results.
327
328 Args:
329 results_type: string indicating which set of results to return;
330 must be one of the results_mod.RESULTS_* constants
331 """
332 logging.debug('do_GET_results: sending results of type "%s"' % results_type)
333 # Since we must make multiple calls to the Results object, grab a
334 # reference to it in case it is updated to point at a new Results
335 # object within another thread.
336 #
337 # TODO(epoger): Rather than using a global variable for the handler
338 # to refer to the Server object, make Server a subclass of
339 # HTTPServer, and then it could be available to the handler via
340 # the handler's .server instance variable.
341 results_obj = _SERVER.results
342 if results_obj:
343 response_dict = results_obj.get_packaged_results_of_type(
344 results_type=results_type, reload_seconds=_SERVER.reload_seconds,
345 is_editable=_SERVER.is_editable, is_exported=_SERVER.is_exported)
346 else:
347 now = int(time.time())
348 response_dict = {
349 results_mod.KEY__HEADER: {
350 results_mod.KEY__HEADER__SCHEMA_VERSION: (
351 results_mod.REBASELINE_SERVER_SCHEMA_VERSION_NUMBER),
352 results_mod.KEY__HEADER__IS_STILL_LOADING: True,
353 results_mod.KEY__HEADER__TIME_UPDATED: now,
354 results_mod.KEY__HEADER__TIME_NEXT_UPDATE_AVAILABLE: (
355 now + RELOAD_INTERVAL_UNTIL_READY),
356 },
357 }
358 self.send_json_dict(response_dict)
359
epoger@google.comf9d134d2013-09-27 15:02:44 +0000360 def do_GET_static(self, path):
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000361 """ Handle a GET request for a file under STATIC_CONTENTS_SUBDIR .
362 Only allow serving of files within STATIC_CONTENTS_SUBDIR that is a
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000363 filesystem sibling of this script.
364
365 Args:
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000366 path: path to file (within STATIC_CONTENTS_SUBDIR) to retrieve
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000367 """
epoger@google.comdcb4e652013-10-11 18:45:33 +0000368 # Strip arguments ('?resultsToLoad=all') from the path
369 path = urlparse.urlparse(path).path
370
371 logging.debug('do_GET_static: sending file "%s"' % path)
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000372 static_dir = os.path.realpath(os.path.join(
373 PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR))
374 full_path = os.path.realpath(os.path.join(static_dir, path))
375 if full_path.startswith(static_dir):
epoger@google.comcb55f112013-10-02 19:27:35 +0000376 self.send_file(full_path)
377 else:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000378 logging.error(
379 'Attempted do_GET_static() of path [%s] outside of static dir [%s]'
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000380 % (full_path, static_dir))
epoger@google.comcb55f112013-10-02 19:27:35 +0000381 self.send_error(404)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000382
epoger@google.comeb832592013-10-23 15:07:26 +0000383 def do_POST(self):
384 """ Handles all POST requests, forwarding them to the appropriate
385 do_POST_* dispatcher. """
386 # All requests must be of this form:
387 # /dispatcher
388 # where 'dispatcher' indicates which do_POST_* dispatcher to run.
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000389 logging.debug('do_POST: path="%s"' % self.path)
epoger@google.comeb832592013-10-23 15:07:26 +0000390 normpath = posixpath.normpath(self.path)
391 dispatchers = {
392 '/edits': self.do_POST_edits,
393 }
394 try:
395 dispatcher = dispatchers[normpath]
396 dispatcher()
397 self.send_response(200)
398 except:
399 self.send_error(404)
400 raise
401
402 def do_POST_edits(self):
403 """ Handle a POST request with modifications to GM expectations, in this
404 format:
405
406 {
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000407 KEY__EDITS__OLD_RESULTS_TYPE: 'all', # type of results that the client
408 # loaded and then made
409 # modifications to
410 KEY__EDITS__OLD_RESULTS_HASH: 39850913, # hash of results when the client
411 # loaded them (ensures that the
412 # client and server apply
413 # modifications to the same base)
414 KEY__EDITS__MODIFICATIONS: [
commit-bot@chromium.orgb463d562014-03-21 17:54:14 +0000415 # as needed by compare_to_expectations.edit_expectations()
epoger@google.comeb832592013-10-23 15:07:26 +0000416 ...
417 ],
418 }
419
420 Raises an Exception if there were any problems.
421 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000422 if not _SERVER.is_editable:
epoger@google.comeb832592013-10-23 15:07:26 +0000423 raise Exception('this server is not running in --editable mode')
424
425 content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE]
426 if content_type != 'application/json;charset=UTF-8':
427 raise Exception('unsupported %s [%s]' % (
428 _HTTP_HEADER_CONTENT_TYPE, content_type))
429
430 content_length = int(self.headers[_HTTP_HEADER_CONTENT_LENGTH])
431 json_data = self.rfile.read(content_length)
432 data = json.loads(json_data)
433 logging.debug('do_POST_edits: received new GM expectations data [%s]' %
434 data)
435
rmistry@google.comd6bab022013-12-02 13:50:38 +0000436 # Update the results on disk with the information we received from the
437 # client.
438 # We must hold _SERVER.results_rlock while we do this, to guarantee that
439 # no other thread updates expectations (from the Skia repo) while we are
440 # updating them (using the info we received from the client).
441 with _SERVER.results_rlock:
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000442 oldResultsType = data[KEY__EDITS__OLD_RESULTS_TYPE]
rmistry@google.comd6bab022013-12-02 13:50:38 +0000443 oldResults = _SERVER.results.get_results_of_type(oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000444 oldResultsHash = str(hash(repr(oldResults[imagepairset.KEY__IMAGEPAIRS])))
445 if oldResultsHash != data[KEY__EDITS__OLD_RESULTS_HASH]:
rmistry@google.comd6bab022013-12-02 13:50:38 +0000446 raise Exception('results of type "%s" changed while the client was '
447 'making modifications. The client should reload the '
448 'results and submit the modifications again.' %
449 oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000450 _SERVER.results.edit_expectations(data[KEY__EDITS__MODIFICATIONS])
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000451
452 # Read the updated results back from disk.
453 # We can do this in a separate thread; we should return our success message
454 # to the UI as soon as possible.
455 thread.start_new_thread(_SERVER.update_results, (True,))
epoger@google.comeb832592013-10-23 15:07:26 +0000456
epoger@google.comf9d134d2013-09-27 15:02:44 +0000457 def redirect_to(self, url):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000458 """ Redirect the HTTP client to a different url.
459
460 Args:
461 url: URL to redirect the HTTP client to
462 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000463 self.send_response(301)
464 self.send_header('Location', url)
465 self.end_headers()
466
467 def send_file(self, path):
468 """ Send the contents of the file at this path, with a mimetype based
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000469 on the filename extension.
470
471 Args:
472 path: path of file whose contents to send to the HTTP client
473 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000474 # Grab the extension if there is one
475 extension = os.path.splitext(path)[1]
476 if len(extension) >= 1:
477 extension = extension[1:]
478
479 # Determine the MIME type of the file from its extension
480 mime_type = MIME_TYPE_MAP.get(extension, MIME_TYPE_MAP[''])
481
482 # Open the file and send it over HTTP
483 if os.path.isfile(path):
484 with open(path, 'rb') as sending_file:
485 self.send_response(200)
486 self.send_header('Content-type', mime_type)
487 self.end_headers()
488 self.wfile.write(sending_file.read())
489 else:
490 self.send_error(404)
491
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000492 def send_json_dict(self, json_dict):
493 """ Send the contents of this dictionary in JSON format, with a JSON
494 mimetype.
495
496 Args:
497 json_dict: dictionary to send
498 """
499 self.send_response(200)
500 self.send_header('Content-type', 'application/json')
501 self.end_headers()
502 json.dump(json_dict, self.wfile)
503
epoger@google.comf9d134d2013-09-27 15:02:44 +0000504
505def main():
commit-bot@chromium.orga6ecbb82013-12-19 19:08:31 +0000506 logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
507 datefmt='%m/%d/%Y %H:%M:%S',
508 level=logging.INFO)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000509 parser = argparse.ArgumentParser()
510 parser.add_argument('--actuals-dir',
511 help=('Directory into which we will check out the latest '
512 'actual GM results. If this directory does not '
513 'exist, it will be created. Defaults to %(default)s'),
514 default=DEFAULT_ACTUALS_DIR)
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000515 parser.add_argument('--actuals-repo',
516 help=('URL of SVN repo to download actual-results.json '
commit-bot@chromium.orgc0df2fb2014-03-28 14:28:04 +0000517 'files from. Defaults to %(default)s ; if set to '
518 'empty string, just compare to actual-results '
519 'already found in ACTUALS_DIR.'),
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000520 default=DEFAULT_ACTUALS_REPO_URL)
521 parser.add_argument('--actuals-revision',
522 help=('revision of actual-results.json files to process. '
523 'Defaults to %(default)s . Beware of setting this '
524 'argument in conjunction with --editable; you '
525 'probably only want to edit results at HEAD.'),
526 default=DEFAULT_ACTUALS_REPO_REVISION)
epoger@google.com542b65f2013-10-15 20:10:33 +0000527 parser.add_argument('--editable', action='store_true',
epoger@google.comeb832592013-10-23 15:07:26 +0000528 help=('Allow HTTP clients to submit new baselines.'))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000529 parser.add_argument('--export', action='store_true',
530 help=('Instead of only allowing access from HTTP clients '
531 'on localhost, allow HTTP clients on other hosts '
532 'to access this server. WARNING: doing so will '
533 'allow users on other hosts to modify your '
epoger@google.com542b65f2013-10-15 20:10:33 +0000534 'GM expectations, if combined with --editable.'))
epoger@google.comafaad3d2013-09-30 15:06:25 +0000535 parser.add_argument('--port', type=int,
536 help=('Which TCP port to listen on for HTTP requests; '
537 'defaults to %(default)s'),
538 default=DEFAULT_PORT)
epoger@google.com542b65f2013-10-15 20:10:33 +0000539 parser.add_argument('--reload', type=int,
540 help=('How often (a period in seconds) to update the '
epoger@google.comb063e132013-11-25 18:06:29 +0000541 'results. If specified, both expected and actual '
rmistry@google.comd6bab022013-12-02 13:50:38 +0000542 'results will be updated by running "gclient sync" '
543 'on your Skia checkout as a whole. '
epoger@google.com542b65f2013-10-15 20:10:33 +0000544 'By default, we do not reload at all, and you '
545 'must restart the server to pick up new data.'),
546 default=0)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000547 args = parser.parse_args()
548 global _SERVER
epoger@google.com542b65f2013-10-15 20:10:33 +0000549 _SERVER = Server(actuals_dir=args.actuals_dir,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000550 actuals_repo_revision=args.actuals_revision,
551 actuals_repo_url=args.actuals_repo,
epoger@google.com542b65f2013-10-15 20:10:33 +0000552 port=args.port, export=args.export, editable=args.editable,
553 reload_seconds=args.reload)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000554 _SERVER.run()
555
rmistry@google.comd6bab022013-12-02 13:50:38 +0000556
epoger@google.comf9d134d2013-09-27 15:02:44 +0000557if __name__ == '__main__':
558 main()