blob: 46b99ff65a821c99e59cb6a1eedfb1ed908ae593 [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
152 GM results
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000153 actuals_repo_revision: revision of actual-results.json files to process
154 actuals_repo_url: SVN repo to download actual-results.json files from
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000155 port: which TCP port to listen on for HTTP requests
156 export: whether to allow HTTP clients on other hosts to access this server
epoger@google.com542b65f2013-10-15 20:10:33 +0000157 editable: whether HTTP clients are allowed to submit new baselines
158 reload_seconds: polling interval with which to check for new results;
159 if 0, don't check for new results at all
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000160 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000161 self._actuals_dir = actuals_dir
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000162 self._actuals_repo_revision = actuals_repo_revision
163 self._actuals_repo_url = actuals_repo_url
epoger@google.comf9d134d2013-09-27 15:02:44 +0000164 self._port = port
165 self._export = export
epoger@google.com542b65f2013-10-15 20:10:33 +0000166 self._editable = editable
167 self._reload_seconds = reload_seconds
epoger@google.com591469b2013-11-20 19:58:06 +0000168 self._actuals_repo = _create_svn_checkout(
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000169 dir_path=actuals_dir, repo_url=actuals_repo_url)
epoger@google.com591469b2013-11-20 19:58:06 +0000170
rmistry@google.comd6bab022013-12-02 13:50:38 +0000171 # Reentrant lock that must be held whenever updating EITHER of:
172 # 1. self._results
173 # 2. the expected or actual results on local disk
174 self.results_rlock = threading.RLock()
175 # self._results will be filled in by calls to update_results()
176 self._results = None
epoger@google.comf9d134d2013-09-27 15:02:44 +0000177
rmistry@google.comd6bab022013-12-02 13:50:38 +0000178 @property
179 def results(self):
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000180 """ Returns the most recently generated results, or None if we don't have
181 any valid results (update_results() has not completed yet). """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000182 return self._results
183
184 @property
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000185 def is_exported(self):
186 """ Returns true iff HTTP clients on other hosts are allowed to access
187 this server. """
188 return self._export
189
rmistry@google.comd6bab022013-12-02 13:50:38 +0000190 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000191 def is_editable(self):
192 """ Returns true iff HTTP clients are allowed to submit new baselines. """
193 return self._editable
epoger@google.comf9d134d2013-09-27 15:02:44 +0000194
rmistry@google.comd6bab022013-12-02 13:50:38 +0000195 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000196 def reload_seconds(self):
197 """ Returns the result reload period in seconds, or 0 if we don't reload
198 results. """
199 return self._reload_seconds
200
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000201 def update_results(self, invalidate=False):
commit-bot@chromium.org7498d952014-03-13 14:56:29 +0000202 """ Create or update self._results, based on the latest expectations and
203 actuals.
rmistry@google.comd6bab022013-12-02 13:50:38 +0000204
205 We hold self.results_rlock while we do this, to guarantee that no other
206 thread attempts to update either self._results or the underlying files at
207 the same time.
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000208
209 Args:
210 invalidate: if True, invalidate self._results immediately upon entry;
211 otherwise, we will let readers see those results until we
212 replace them
epoger@google.comf9d134d2013-09-27 15:02:44 +0000213 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000214 with self.results_rlock:
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000215 if invalidate:
216 self._results = None
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000217 logging.info(
218 'Updating actual GM results in %s to revision %s from repo %s ...' % (
219 self._actuals_dir, self._actuals_repo_revision,
220 self._actuals_repo_url))
221 self._actuals_repo.Update(path='.', revision=self._actuals_repo_revision)
epoger@google.com591469b2013-11-20 19:58:06 +0000222
rmistry@google.comd6bab022013-12-02 13:50:38 +0000223 # We only update the expectations dir if the server was run with a
224 # nonzero --reload argument; otherwise, we expect the user to maintain
225 # her own expectations as she sees fit.
226 #
227 # Because the Skia repo is moving from SVN to git, and git does not
228 # support updating a single directory tree, we have to update the entire
229 # repo checkout.
230 #
231 # Because Skia uses depot_tools, we have to update using "gclient sync"
232 # instead of raw git (or SVN) update. Happily, this will work whether
233 # the checkout was created using git or SVN.
234 if self._reload_seconds:
235 logging.info(
236 'Updating expected GM results in %s by syncing Skia repo ...' %
commit-bot@chromium.orgb463d562014-03-21 17:54:14 +0000237 compare_to_expectations.DEFAULT_EXPECTATIONS_DIR)
rmistry@google.comd6bab022013-12-02 13:50:38 +0000238 _run_command(['gclient', 'sync'], TRUNK_DIRECTORY)
239
commit-bot@chromium.orgb463d562014-03-21 17:54:14 +0000240 self._results = compare_to_expectations.Results(
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000241 actuals_root=self._actuals_dir,
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000242 generated_images_root=os.path.join(
243 PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR,
244 GENERATED_IMAGES_SUBDIR),
245 diff_base_url=posixpath.join(
246 os.pardir, STATIC_CONTENTS_SUBDIR, GENERATED_IMAGES_SUBDIR))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000247
epoger@google.com2682c902013-12-05 16:05:16 +0000248 def _result_loader(self, reload_seconds=0):
249 """ Call self.update_results(), either once or periodically.
250
251 Params:
252 reload_seconds: integer; if nonzero, reload results at this interval
253 (in which case, this method will never return!)
epoger@google.com542b65f2013-10-15 20:10:33 +0000254 """
epoger@google.com2682c902013-12-05 16:05:16 +0000255 self.update_results()
256 logging.info('Initial results loaded. Ready for requests on %s' % self._url)
257 if reload_seconds:
258 while True:
259 time.sleep(reload_seconds)
260 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000261
epoger@google.comf9d134d2013-09-27 15:02:44 +0000262 def run(self):
epoger@google.com2682c902013-12-05 16:05:16 +0000263 arg_tuple = (self._reload_seconds,) # start_new_thread needs a tuple,
264 # even though it holds just one param
265 thread.start_new_thread(self._result_loader, arg_tuple)
epoger@google.com542b65f2013-10-15 20:10:33 +0000266
epoger@google.comf9d134d2013-09-27 15:02:44 +0000267 if self._export:
268 server_address = ('', self._port)
epoger@google.com591469b2013-11-20 19:58:06 +0000269 host = _get_routable_ip_address()
epoger@google.com542b65f2013-10-15 20:10:33 +0000270 if self._editable:
271 logging.warning('Running with combination of "export" and "editable" '
272 'flags. Users on other machines will '
273 'be able to modify your GM expectations!')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000274 else:
epoger@google.comb08c7072013-10-30 14:09:04 +0000275 host = '127.0.0.1'
276 server_address = (host, self._port)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000277 http_server = BaseHTTPServer.HTTPServer(server_address, HTTPRequestHandler)
epoger@google.com2682c902013-12-05 16:05:16 +0000278 self._url = 'http://%s:%d' % (host, http_server.server_port)
279 logging.info('Listening for requests on %s' % self._url)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000280 http_server.serve_forever()
281
282
283class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
284 """ HTTP request handlers for various types of queries this server knows
285 how to handle (static HTML and Javascript, expected/actual results, etc.)
286 """
287 def do_GET(self):
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000288 """
289 Handles all GET requests, forwarding them to the appropriate
290 do_GET_* dispatcher.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000291
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000292 If we see any Exceptions, return a 404. This fixes http://skbug.com/2147
293 """
294 try:
295 logging.debug('do_GET: path="%s"' % self.path)
296 if self.path == '' or self.path == '/' or self.path == '/index.html' :
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000297 self.redirect_to('/%s/index.html' % STATIC_CONTENTS_SUBDIR)
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000298 return
299 if self.path == '/favicon.ico' :
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000300 self.redirect_to('/%s/favicon.ico' % STATIC_CONTENTS_SUBDIR)
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000301 return
302
303 # All requests must be of this form:
304 # /dispatcher/remainder
305 # where 'dispatcher' indicates which do_GET_* dispatcher to run
306 # and 'remainder' is the remaining path sent to that dispatcher.
307 normpath = posixpath.normpath(self.path)
308 (dispatcher_name, remainder) = PATHSPLIT_RE.match(normpath).groups()
309 dispatchers = {
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000310 'results': self.do_GET_results,
311 STATIC_CONTENTS_SUBDIR: self.do_GET_static,
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000312 }
313 dispatcher = dispatchers[dispatcher_name]
314 dispatcher(remainder)
315 except:
316 self.send_error(404)
317 raise
epoger@google.comf9d134d2013-09-27 15:02:44 +0000318
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000319 def do_GET_results(self, results_type):
320 """ Handle a GET request for GM results.
321
322 Args:
323 results_type: string indicating which set of results to return;
324 must be one of the results_mod.RESULTS_* constants
325 """
326 logging.debug('do_GET_results: sending results of type "%s"' % results_type)
327 # Since we must make multiple calls to the Results object, grab a
328 # reference to it in case it is updated to point at a new Results
329 # object within another thread.
330 #
331 # TODO(epoger): Rather than using a global variable for the handler
332 # to refer to the Server object, make Server a subclass of
333 # HTTPServer, and then it could be available to the handler via
334 # the handler's .server instance variable.
335 results_obj = _SERVER.results
336 if results_obj:
337 response_dict = results_obj.get_packaged_results_of_type(
338 results_type=results_type, reload_seconds=_SERVER.reload_seconds,
339 is_editable=_SERVER.is_editable, is_exported=_SERVER.is_exported)
340 else:
341 now = int(time.time())
342 response_dict = {
343 results_mod.KEY__HEADER: {
344 results_mod.KEY__HEADER__SCHEMA_VERSION: (
345 results_mod.REBASELINE_SERVER_SCHEMA_VERSION_NUMBER),
346 results_mod.KEY__HEADER__IS_STILL_LOADING: True,
347 results_mod.KEY__HEADER__TIME_UPDATED: now,
348 results_mod.KEY__HEADER__TIME_NEXT_UPDATE_AVAILABLE: (
349 now + RELOAD_INTERVAL_UNTIL_READY),
350 },
351 }
352 self.send_json_dict(response_dict)
353
epoger@google.comf9d134d2013-09-27 15:02:44 +0000354 def do_GET_static(self, path):
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000355 """ Handle a GET request for a file under STATIC_CONTENTS_SUBDIR .
356 Only allow serving of files within STATIC_CONTENTS_SUBDIR that is a
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000357 filesystem sibling of this script.
358
359 Args:
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000360 path: path to file (within STATIC_CONTENTS_SUBDIR) to retrieve
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000361 """
epoger@google.comdcb4e652013-10-11 18:45:33 +0000362 # Strip arguments ('?resultsToLoad=all') from the path
363 path = urlparse.urlparse(path).path
364
365 logging.debug('do_GET_static: sending file "%s"' % path)
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000366 static_dir = os.path.realpath(os.path.join(
367 PARENT_DIRECTORY, STATIC_CONTENTS_SUBDIR))
368 full_path = os.path.realpath(os.path.join(static_dir, path))
369 if full_path.startswith(static_dir):
epoger@google.comcb55f112013-10-02 19:27:35 +0000370 self.send_file(full_path)
371 else:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000372 logging.error(
373 'Attempted do_GET_static() of path [%s] outside of static dir [%s]'
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000374 % (full_path, static_dir))
epoger@google.comcb55f112013-10-02 19:27:35 +0000375 self.send_error(404)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000376
epoger@google.comeb832592013-10-23 15:07:26 +0000377 def do_POST(self):
378 """ Handles all POST requests, forwarding them to the appropriate
379 do_POST_* dispatcher. """
380 # All requests must be of this form:
381 # /dispatcher
382 # where 'dispatcher' indicates which do_POST_* dispatcher to run.
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000383 logging.debug('do_POST: path="%s"' % self.path)
epoger@google.comeb832592013-10-23 15:07:26 +0000384 normpath = posixpath.normpath(self.path)
385 dispatchers = {
386 '/edits': self.do_POST_edits,
387 }
388 try:
389 dispatcher = dispatchers[normpath]
390 dispatcher()
391 self.send_response(200)
392 except:
393 self.send_error(404)
394 raise
395
396 def do_POST_edits(self):
397 """ Handle a POST request with modifications to GM expectations, in this
398 format:
399
400 {
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000401 KEY__EDITS__OLD_RESULTS_TYPE: 'all', # type of results that the client
402 # loaded and then made
403 # modifications to
404 KEY__EDITS__OLD_RESULTS_HASH: 39850913, # hash of results when the client
405 # loaded them (ensures that the
406 # client and server apply
407 # modifications to the same base)
408 KEY__EDITS__MODIFICATIONS: [
commit-bot@chromium.orgb463d562014-03-21 17:54:14 +0000409 # as needed by compare_to_expectations.edit_expectations()
epoger@google.comeb832592013-10-23 15:07:26 +0000410 ...
411 ],
412 }
413
414 Raises an Exception if there were any problems.
415 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000416 if not _SERVER.is_editable:
epoger@google.comeb832592013-10-23 15:07:26 +0000417 raise Exception('this server is not running in --editable mode')
418
419 content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE]
420 if content_type != 'application/json;charset=UTF-8':
421 raise Exception('unsupported %s [%s]' % (
422 _HTTP_HEADER_CONTENT_TYPE, content_type))
423
424 content_length = int(self.headers[_HTTP_HEADER_CONTENT_LENGTH])
425 json_data = self.rfile.read(content_length)
426 data = json.loads(json_data)
427 logging.debug('do_POST_edits: received new GM expectations data [%s]' %
428 data)
429
rmistry@google.comd6bab022013-12-02 13:50:38 +0000430 # Update the results on disk with the information we received from the
431 # client.
432 # We must hold _SERVER.results_rlock while we do this, to guarantee that
433 # no other thread updates expectations (from the Skia repo) while we are
434 # updating them (using the info we received from the client).
435 with _SERVER.results_rlock:
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000436 oldResultsType = data[KEY__EDITS__OLD_RESULTS_TYPE]
rmistry@google.comd6bab022013-12-02 13:50:38 +0000437 oldResults = _SERVER.results.get_results_of_type(oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000438 oldResultsHash = str(hash(repr(oldResults[imagepairset.KEY__IMAGEPAIRS])))
439 if oldResultsHash != data[KEY__EDITS__OLD_RESULTS_HASH]:
rmistry@google.comd6bab022013-12-02 13:50:38 +0000440 raise Exception('results of type "%s" changed while the client was '
441 'making modifications. The client should reload the '
442 'results and submit the modifications again.' %
443 oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000444 _SERVER.results.edit_expectations(data[KEY__EDITS__MODIFICATIONS])
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000445
446 # Read the updated results back from disk.
447 # We can do this in a separate thread; we should return our success message
448 # to the UI as soon as possible.
449 thread.start_new_thread(_SERVER.update_results, (True,))
epoger@google.comeb832592013-10-23 15:07:26 +0000450
epoger@google.comf9d134d2013-09-27 15:02:44 +0000451 def redirect_to(self, url):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000452 """ Redirect the HTTP client to a different url.
453
454 Args:
455 url: URL to redirect the HTTP client to
456 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000457 self.send_response(301)
458 self.send_header('Location', url)
459 self.end_headers()
460
461 def send_file(self, path):
462 """ Send the contents of the file at this path, with a mimetype based
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000463 on the filename extension.
464
465 Args:
466 path: path of file whose contents to send to the HTTP client
467 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000468 # Grab the extension if there is one
469 extension = os.path.splitext(path)[1]
470 if len(extension) >= 1:
471 extension = extension[1:]
472
473 # Determine the MIME type of the file from its extension
474 mime_type = MIME_TYPE_MAP.get(extension, MIME_TYPE_MAP[''])
475
476 # Open the file and send it over HTTP
477 if os.path.isfile(path):
478 with open(path, 'rb') as sending_file:
479 self.send_response(200)
480 self.send_header('Content-type', mime_type)
481 self.end_headers()
482 self.wfile.write(sending_file.read())
483 else:
484 self.send_error(404)
485
commit-bot@chromium.orga25c4e42014-03-21 17:30:12 +0000486 def send_json_dict(self, json_dict):
487 """ Send the contents of this dictionary in JSON format, with a JSON
488 mimetype.
489
490 Args:
491 json_dict: dictionary to send
492 """
493 self.send_response(200)
494 self.send_header('Content-type', 'application/json')
495 self.end_headers()
496 json.dump(json_dict, self.wfile)
497
epoger@google.comf9d134d2013-09-27 15:02:44 +0000498
499def main():
commit-bot@chromium.orga6ecbb82013-12-19 19:08:31 +0000500 logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
501 datefmt='%m/%d/%Y %H:%M:%S',
502 level=logging.INFO)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000503 parser = argparse.ArgumentParser()
504 parser.add_argument('--actuals-dir',
505 help=('Directory into which we will check out the latest '
506 'actual GM results. If this directory does not '
507 'exist, it will be created. Defaults to %(default)s'),
508 default=DEFAULT_ACTUALS_DIR)
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000509 parser.add_argument('--actuals-repo',
510 help=('URL of SVN repo to download actual-results.json '
511 'files from. Defaults to %(default)s'),
512 default=DEFAULT_ACTUALS_REPO_URL)
513 parser.add_argument('--actuals-revision',
514 help=('revision of actual-results.json files to process. '
515 'Defaults to %(default)s . Beware of setting this '
516 'argument in conjunction with --editable; you '
517 'probably only want to edit results at HEAD.'),
518 default=DEFAULT_ACTUALS_REPO_REVISION)
epoger@google.com542b65f2013-10-15 20:10:33 +0000519 parser.add_argument('--editable', action='store_true',
epoger@google.comeb832592013-10-23 15:07:26 +0000520 help=('Allow HTTP clients to submit new baselines.'))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000521 parser.add_argument('--export', action='store_true',
522 help=('Instead of only allowing access from HTTP clients '
523 'on localhost, allow HTTP clients on other hosts '
524 'to access this server. WARNING: doing so will '
525 'allow users on other hosts to modify your '
epoger@google.com542b65f2013-10-15 20:10:33 +0000526 'GM expectations, if combined with --editable.'))
epoger@google.comafaad3d2013-09-30 15:06:25 +0000527 parser.add_argument('--port', type=int,
528 help=('Which TCP port to listen on for HTTP requests; '
529 'defaults to %(default)s'),
530 default=DEFAULT_PORT)
epoger@google.com542b65f2013-10-15 20:10:33 +0000531 parser.add_argument('--reload', type=int,
532 help=('How often (a period in seconds) to update the '
epoger@google.comb063e132013-11-25 18:06:29 +0000533 'results. If specified, both expected and actual '
rmistry@google.comd6bab022013-12-02 13:50:38 +0000534 'results will be updated by running "gclient sync" '
535 'on your Skia checkout as a whole. '
epoger@google.com542b65f2013-10-15 20:10:33 +0000536 'By default, we do not reload at all, and you '
537 'must restart the server to pick up new data.'),
538 default=0)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000539 args = parser.parse_args()
540 global _SERVER
epoger@google.com542b65f2013-10-15 20:10:33 +0000541 _SERVER = Server(actuals_dir=args.actuals_dir,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000542 actuals_repo_revision=args.actuals_revision,
543 actuals_repo_url=args.actuals_repo,
epoger@google.com542b65f2013-10-15 20:10:33 +0000544 port=args.port, export=args.export, editable=args.editable,
545 reload_seconds=args.reload)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000546 _SERVER.run()
547
rmistry@google.comd6bab022013-12-02 13:50:38 +0000548
epoger@google.comf9d134d2013-09-27 15:02:44 +0000549if __name__ == '__main__':
550 main()