blob: fc090d25e8f16daaf90b467dc04137186aae2339 [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#
31# 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*
34# 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__))
36TRUNK_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.org16f41802014-02-26 19:05:20 +000043import imagepairset
epoger@google.comf9d134d2013-09-27 15:02:44 +000044import results
45
epoger@google.comf9d134d2013-09-27 15:02:44 +000046PATHSPLIT_RE = re.compile('/([^/]+)/(.+)')
epoger@google.comb063e132013-11-25 18:06:29 +000047EXPECTATIONS_DIR = os.path.join(TRUNK_DIRECTORY, 'expectations', 'gm')
epoger@google.com9dddf6f2013-11-08 16:25:25 +000048GENERATED_IMAGES_ROOT = os.path.join(PARENT_DIRECTORY, 'static',
49 'generated-images')
epoger@google.comf9d134d2013-09-27 15:02:44 +000050
51# A simple dictionary of file name extensions to MIME types. The empty string
52# entry is used as the default when no extension was given or if the extension
53# has no entry in this dictionary.
54MIME_TYPE_MAP = {'': 'application/octet-stream',
55 'html': 'text/html',
56 'css': 'text/css',
57 'png': 'image/png',
58 'js': 'application/javascript',
59 'json': 'application/json'
60 }
61
commit-bot@chromium.org16f41802014-02-26 19:05:20 +000062# Keys that server.py uses to create the toplevel content header.
63# NOTE: Keep these in sync with static/constants.js
64KEY__EDITS__MODIFICATIONS = 'modifications'
65KEY__EDITS__OLD_RESULTS_HASH = 'oldResultsHash'
66KEY__EDITS__OLD_RESULTS_TYPE = 'oldResultsType'
67KEY__HEADER = 'header'
68KEY__HEADER__DATAHASH = 'dataHash'
69KEY__HEADER__IS_EDITABLE = 'isEditable'
70KEY__HEADER__IS_EXPORTED = 'isExported'
71KEY__HEADER__IS_STILL_LOADING = 'resultsStillLoading'
72KEY__HEADER__TIME_NEXT_UPDATE_AVAILABLE = 'timeNextUpdateAvailable'
73KEY__HEADER__TIME_UPDATED = 'timeUpdated'
74KEY__HEADER__TYPE = 'type'
75
epoger@google.comf9d134d2013-09-27 15:02:44 +000076DEFAULT_ACTUALS_DIR = '.gm-actuals'
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +000077DEFAULT_ACTUALS_REPO_REVISION = 'HEAD'
78DEFAULT_ACTUALS_REPO_URL = 'http://skia-autogen.googlecode.com/svn/gm-actual'
epoger@google.comf9d134d2013-09-27 15:02:44 +000079DEFAULT_PORT = 8888
80
epoger@google.com2682c902013-12-05 16:05:16 +000081# How often (in seconds) clients should reload while waiting for initial
82# results to load.
83RELOAD_INTERVAL_UNTIL_READY = 10
84
epoger@google.comeb832592013-10-23 15:07:26 +000085_HTTP_HEADER_CONTENT_LENGTH = 'Content-Length'
86_HTTP_HEADER_CONTENT_TYPE = 'Content-Type'
87
epoger@google.comf9d134d2013-09-27 15:02:44 +000088_SERVER = None # This gets filled in by main()
89
rmistry@google.comd6bab022013-12-02 13:50:38 +000090
91def _run_command(args, directory):
92 """Runs a command and returns stdout as a single string.
93
94 Args:
95 args: the command to run, as a list of arguments
96 directory: directory within which to run the command
97
98 Returns: stdout, as a string
99
100 Raises an Exception if the command failed (exited with nonzero return code).
101 """
102 logging.debug('_run_command: %s in directory %s' % (args, directory))
103 proc = subprocess.Popen(args, cwd=directory,
104 stdout=subprocess.PIPE,
105 stderr=subprocess.PIPE)
106 (stdout, stderr) = proc.communicate()
107 if proc.returncode is not 0:
108 raise Exception('command "%s" failed in dir "%s": %s' %
109 (args, directory, stderr))
110 return stdout
111
112
epoger@google.com591469b2013-11-20 19:58:06 +0000113def _get_routable_ip_address():
epoger@google.comb08c7072013-10-30 14:09:04 +0000114 """Returns routable IP address of this host (the IP address of its network
115 interface that would be used for most traffic, not its localhost
116 interface). See http://stackoverflow.com/a/166589 """
117 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
118 sock.connect(('8.8.8.8', 80))
119 host = sock.getsockname()[0]
120 sock.close()
121 return host
122
rmistry@google.comd6bab022013-12-02 13:50:38 +0000123
epoger@google.com591469b2013-11-20 19:58:06 +0000124def _create_svn_checkout(dir_path, repo_url):
125 """Creates local checkout of an SVN repository at the specified directory
126 path, returning an svn.Svn object referring to the local checkout.
127
128 Args:
129 dir_path: path to the local checkout; if this directory does not yet exist,
130 it will be created and the repo will be checked out into it
131 repo_url: URL of SVN repo to check out into dir_path (unless the local
132 checkout already exists)
133 Returns: an svn.Svn object referring to the local checkout.
134 """
135 local_checkout = svn.Svn(dir_path)
136 if not os.path.isdir(dir_path):
137 os.makedirs(dir_path)
138 local_checkout.Checkout(repo_url, '.')
139 return local_checkout
140
epoger@google.comb08c7072013-10-30 14:09:04 +0000141
epoger@google.comf9d134d2013-09-27 15:02:44 +0000142class Server(object):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000143 """ HTTP server for our HTML rebaseline viewer. """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000144
epoger@google.comf9d134d2013-09-27 15:02:44 +0000145 def __init__(self,
146 actuals_dir=DEFAULT_ACTUALS_DIR,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000147 actuals_repo_revision=DEFAULT_ACTUALS_REPO_REVISION,
148 actuals_repo_url=DEFAULT_ACTUALS_REPO_URL,
epoger@google.com542b65f2013-10-15 20:10:33 +0000149 port=DEFAULT_PORT, export=False, editable=True,
150 reload_seconds=0):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000151 """
152 Args:
153 actuals_dir: directory under which we will check out the latest actual
154 GM results
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000155 actuals_repo_revision: revision of actual-results.json files to process
156 actuals_repo_url: SVN repo to download actual-results.json files from
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;
161 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
epoger@google.com591469b2013-11-20 19:58:06 +0000170 self._actuals_repo = _create_svn_checkout(
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000171 dir_path=actuals_dir, repo_url=actuals_repo_url)
epoger@google.com591469b2013-11-20 19:58:06 +0000172
rmistry@google.comd6bab022013-12-02 13:50:38 +0000173 # Reentrant lock that must be held whenever updating EITHER of:
174 # 1. self._results
175 # 2. the expected or actual results on local disk
176 self.results_rlock = threading.RLock()
177 # self._results will be filled in by calls to update_results()
178 self._results = None
epoger@google.comf9d134d2013-09-27 15:02:44 +0000179
rmistry@google.comd6bab022013-12-02 13:50:38 +0000180 @property
181 def results(self):
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000182 """ Returns the most recently generated results, or None if we don't have
183 any valid results (update_results() has not completed yet). """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000184 return self._results
185
186 @property
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000187 def is_exported(self):
188 """ Returns true iff HTTP clients on other hosts are allowed to access
189 this server. """
190 return self._export
191
rmistry@google.comd6bab022013-12-02 13:50:38 +0000192 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000193 def is_editable(self):
194 """ Returns true iff HTTP clients are allowed to submit new baselines. """
195 return self._editable
epoger@google.comf9d134d2013-09-27 15:02:44 +0000196
rmistry@google.comd6bab022013-12-02 13:50:38 +0000197 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000198 def reload_seconds(self):
199 """ Returns the result reload period in seconds, or 0 if we don't reload
200 results. """
201 return self._reload_seconds
202
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000203 def update_results(self, invalidate=False):
rmistry@google.comd6bab022013-12-02 13:50:38 +0000204 """ Create or update self._results, based on the expectations in
epoger@google.comb063e132013-11-25 18:06:29 +0000205 EXPECTATIONS_DIR and the latest actuals from skia-autogen.
rmistry@google.comd6bab022013-12-02 13:50:38 +0000206
207 We hold self.results_rlock while we do this, to guarantee that no other
208 thread attempts to update either self._results or the underlying files at
209 the same time.
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000210
211 Args:
212 invalidate: if True, invalidate self._results immediately upon entry;
213 otherwise, we will let readers see those results until we
214 replace them
epoger@google.comf9d134d2013-09-27 15:02:44 +0000215 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000216 with self.results_rlock:
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000217 if invalidate:
218 self._results = None
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000219 logging.info(
220 'Updating actual GM results in %s to revision %s from repo %s ...' % (
221 self._actuals_dir, self._actuals_repo_revision,
222 self._actuals_repo_url))
223 self._actuals_repo.Update(path='.', revision=self._actuals_repo_revision)
epoger@google.com591469b2013-11-20 19:58:06 +0000224
rmistry@google.comd6bab022013-12-02 13:50:38 +0000225 # We only update the expectations dir if the server was run with a
226 # nonzero --reload argument; otherwise, we expect the user to maintain
227 # her own expectations as she sees fit.
228 #
229 # Because the Skia repo is moving from SVN to git, and git does not
230 # support updating a single directory tree, we have to update the entire
231 # repo checkout.
232 #
233 # Because Skia uses depot_tools, we have to update using "gclient sync"
234 # instead of raw git (or SVN) update. Happily, this will work whether
235 # the checkout was created using git or SVN.
236 if self._reload_seconds:
237 logging.info(
238 'Updating expected GM results in %s by syncing Skia repo ...' %
239 EXPECTATIONS_DIR)
240 _run_command(['gclient', 'sync'], TRUNK_DIRECTORY)
241
rmistry@google.comd6bab022013-12-02 13:50:38 +0000242 self._results = results.Results(
243 actuals_root=self._actuals_dir,
244 expected_root=EXPECTATIONS_DIR,
245 generated_images_root=GENERATED_IMAGES_ROOT)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000246
epoger@google.com2682c902013-12-05 16:05:16 +0000247 def _result_loader(self, reload_seconds=0):
248 """ Call self.update_results(), either once or periodically.
249
250 Params:
251 reload_seconds: integer; if nonzero, reload results at this interval
252 (in which case, this method will never return!)
epoger@google.com542b65f2013-10-15 20:10:33 +0000253 """
epoger@google.com2682c902013-12-05 16:05:16 +0000254 self.update_results()
255 logging.info('Initial results loaded. Ready for requests on %s' % self._url)
256 if reload_seconds:
257 while True:
258 time.sleep(reload_seconds)
259 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000260
epoger@google.comf9d134d2013-09-27 15:02:44 +0000261 def run(self):
epoger@google.com2682c902013-12-05 16:05:16 +0000262 arg_tuple = (self._reload_seconds,) # start_new_thread needs a tuple,
263 # even though it holds just one param
264 thread.start_new_thread(self._result_loader, arg_tuple)
epoger@google.com542b65f2013-10-15 20:10:33 +0000265
epoger@google.comf9d134d2013-09-27 15:02:44 +0000266 if self._export:
267 server_address = ('', self._port)
epoger@google.com591469b2013-11-20 19:58:06 +0000268 host = _get_routable_ip_address()
epoger@google.com542b65f2013-10-15 20:10:33 +0000269 if self._editable:
270 logging.warning('Running with combination of "export" and "editable" '
271 'flags. Users on other machines will '
272 'be able to modify your GM expectations!')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000273 else:
epoger@google.comb08c7072013-10-30 14:09:04 +0000274 host = '127.0.0.1'
275 server_address = (host, self._port)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000276 http_server = BaseHTTPServer.HTTPServer(server_address, HTTPRequestHandler)
epoger@google.com2682c902013-12-05 16:05:16 +0000277 self._url = 'http://%s:%d' % (host, http_server.server_port)
278 logging.info('Listening for requests on %s' % self._url)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000279 http_server.serve_forever()
280
281
282class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
283 """ HTTP request handlers for various types of queries this server knows
284 how to handle (static HTML and Javascript, expected/actual results, etc.)
285 """
286 def do_GET(self):
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000287 """
288 Handles all GET requests, forwarding them to the appropriate
289 do_GET_* dispatcher.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000290
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000291 If we see any Exceptions, return a 404. This fixes http://skbug.com/2147
292 """
293 try:
294 logging.debug('do_GET: path="%s"' % self.path)
295 if self.path == '' or self.path == '/' or self.path == '/index.html' :
296 self.redirect_to('/static/index.html')
297 return
298 if self.path == '/favicon.ico' :
299 self.redirect_to('/static/favicon.ico')
300 return
301
302 # All requests must be of this form:
303 # /dispatcher/remainder
304 # where 'dispatcher' indicates which do_GET_* dispatcher to run
305 # and 'remainder' is the remaining path sent to that dispatcher.
306 normpath = posixpath.normpath(self.path)
307 (dispatcher_name, remainder) = PATHSPLIT_RE.match(normpath).groups()
308 dispatchers = {
309 'results': self.do_GET_results,
310 'static': self.do_GET_static,
311 }
312 dispatcher = dispatchers[dispatcher_name]
313 dispatcher(remainder)
314 except:
315 self.send_error(404)
316 raise
epoger@google.comf9d134d2013-09-27 15:02:44 +0000317
epoger@google.comdcb4e652013-10-11 18:45:33 +0000318 def do_GET_results(self, type):
epoger@google.comf9d134d2013-09-27 15:02:44 +0000319 """ Handle a GET request for GM results.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000320
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000321 Args:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000322 type: string indicating which set of results to return;
323 must be one of the results.RESULTS_* constants
324 """
325 logging.debug('do_GET_results: sending results of type "%s"' % type)
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000326 # Since we must make multiple calls to the Results object, grab a
327 # reference to it in case it is updated to point at a new Results
328 # object within another thread.
329 #
330 # TODO(epoger): Rather than using a global variable for the handler
331 # to refer to the Server object, make Server a subclass of
332 # HTTPServer, and then it could be available to the handler via
333 # the handler's .server instance variable.
334 results_obj = _SERVER.results
335 if results_obj:
336 response_dict = self.package_results(results_obj, type)
337 else:
338 now = int(time.time())
339 response_dict = {
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000340 KEY__HEADER: {
341 KEY__HEADER__IS_STILL_LOADING: True,
342 KEY__HEADER__TIME_UPDATED: now,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000343 KEY__HEADER__TIME_NEXT_UPDATE_AVAILABLE: (
344 now + RELOAD_INTERVAL_UNTIL_READY),
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000345 },
346 }
347 self.send_json_dict(response_dict)
epoger@google.com542b65f2013-10-15 20:10:33 +0000348
epoger@google.com2682c902013-12-05 16:05:16 +0000349 def package_results(self, results_obj, type):
350 """ Given a nonempty "results" object, package it as a response_dict
351 as needed within do_GET_results.
352
353 Args:
354 results_obj: nonempty "results" object
355 type: string indicating which set of results to return;
356 must be one of the results.RESULTS_* constants
357 """
358 response_dict = results_obj.get_results_of_type(type)
359 time_updated = results_obj.get_timestamp()
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000360 response_dict[KEY__HEADER] = {
epoger@google.com542b65f2013-10-15 20:10:33 +0000361 # Timestamps:
362 # 1. when this data was last updated
363 # 2. when the caller should check back for new data (if ever)
364 #
365 # We only return these timestamps if the --reload argument was passed;
366 # otherwise, we have no idea when the expectations were last updated
367 # (we allow the user to maintain her own expectations as she sees fit).
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000368 KEY__HEADER__TIME_UPDATED:
369 time_updated if _SERVER.reload_seconds else None,
370 KEY__HEADER__TIME_NEXT_UPDATE_AVAILABLE:
rmistry@google.comd6bab022013-12-02 13:50:38 +0000371 (time_updated+_SERVER.reload_seconds) if _SERVER.reload_seconds
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000372 else None,
epoger@google.com542b65f2013-10-15 20:10:33 +0000373
epoger@google.comeb832592013-10-23 15:07:26 +0000374 # The type we passed to get_results_of_type()
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000375 KEY__HEADER__TYPE: type,
epoger@google.comeb832592013-10-23 15:07:26 +0000376
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000377 # Hash of dataset, which the client must return with any edits--
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000378 # this ensures that the edits were made to a particular dataset.
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000379 KEY__HEADER__DATAHASH: str(hash(repr(
380 response_dict[imagepairset.KEY__IMAGEPAIRS]))),
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000381
382 # Whether the server will accept edits back.
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000383 KEY__HEADER__IS_EDITABLE: _SERVER.is_editable,
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000384
385 # Whether the service is accessible from other hosts.
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000386 KEY__HEADER__IS_EXPORTED: _SERVER.is_exported,
epoger@google.com2682c902013-12-05 16:05:16 +0000387 }
388 return response_dict
epoger@google.comf9d134d2013-09-27 15:02:44 +0000389
390 def do_GET_static(self, path):
epoger@google.comcb55f112013-10-02 19:27:35 +0000391 """ Handle a GET request for a file under the 'static' directory.
392 Only allow serving of files within the 'static' directory that is a
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000393 filesystem sibling of this script.
394
395 Args:
396 path: path to file (under static directory) to retrieve
397 """
epoger@google.comdcb4e652013-10-11 18:45:33 +0000398 # Strip arguments ('?resultsToLoad=all') from the path
399 path = urlparse.urlparse(path).path
400
401 logging.debug('do_GET_static: sending file "%s"' % path)
epoger@google.comcb55f112013-10-02 19:27:35 +0000402 static_dir = os.path.realpath(os.path.join(PARENT_DIRECTORY, 'static'))
403 full_path = os.path.realpath(os.path.join(static_dir, path))
404 if full_path.startswith(static_dir):
405 self.send_file(full_path)
406 else:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000407 logging.error(
408 'Attempted do_GET_static() of path [%s] outside of static dir [%s]'
409 % (full_path, static_dir))
epoger@google.comcb55f112013-10-02 19:27:35 +0000410 self.send_error(404)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000411
epoger@google.comeb832592013-10-23 15:07:26 +0000412 def do_POST(self):
413 """ Handles all POST requests, forwarding them to the appropriate
414 do_POST_* dispatcher. """
415 # All requests must be of this form:
416 # /dispatcher
417 # where 'dispatcher' indicates which do_POST_* dispatcher to run.
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000418 logging.debug('do_POST: path="%s"' % self.path)
epoger@google.comeb832592013-10-23 15:07:26 +0000419 normpath = posixpath.normpath(self.path)
420 dispatchers = {
421 '/edits': self.do_POST_edits,
422 }
423 try:
424 dispatcher = dispatchers[normpath]
425 dispatcher()
426 self.send_response(200)
427 except:
428 self.send_error(404)
429 raise
430
431 def do_POST_edits(self):
432 """ Handle a POST request with modifications to GM expectations, in this
433 format:
434
435 {
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000436 KEY__EDITS__OLD_RESULTS_TYPE: 'all', # type of results that the client
437 # loaded and then made
438 # modifications to
439 KEY__EDITS__OLD_RESULTS_HASH: 39850913, # hash of results when the client
440 # loaded them (ensures that the
441 # client and server apply
442 # modifications to the same base)
443 KEY__EDITS__MODIFICATIONS: [
444 # as needed by results.edit_expectations()
epoger@google.comeb832592013-10-23 15:07:26 +0000445 ...
446 ],
447 }
448
449 Raises an Exception if there were any problems.
450 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000451 if not _SERVER.is_editable:
epoger@google.comeb832592013-10-23 15:07:26 +0000452 raise Exception('this server is not running in --editable mode')
453
454 content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE]
455 if content_type != 'application/json;charset=UTF-8':
456 raise Exception('unsupported %s [%s]' % (
457 _HTTP_HEADER_CONTENT_TYPE, content_type))
458
459 content_length = int(self.headers[_HTTP_HEADER_CONTENT_LENGTH])
460 json_data = self.rfile.read(content_length)
461 data = json.loads(json_data)
462 logging.debug('do_POST_edits: received new GM expectations data [%s]' %
463 data)
464
rmistry@google.comd6bab022013-12-02 13:50:38 +0000465 # Update the results on disk with the information we received from the
466 # client.
467 # We must hold _SERVER.results_rlock while we do this, to guarantee that
468 # no other thread updates expectations (from the Skia repo) while we are
469 # updating them (using the info we received from the client).
470 with _SERVER.results_rlock:
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000471 oldResultsType = data[KEY__EDITS__OLD_RESULTS_TYPE]
rmistry@google.comd6bab022013-12-02 13:50:38 +0000472 oldResults = _SERVER.results.get_results_of_type(oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000473 oldResultsHash = str(hash(repr(oldResults[imagepairset.KEY__IMAGEPAIRS])))
474 if oldResultsHash != data[KEY__EDITS__OLD_RESULTS_HASH]:
rmistry@google.comd6bab022013-12-02 13:50:38 +0000475 raise Exception('results of type "%s" changed while the client was '
476 'making modifications. The client should reload the '
477 'results and submit the modifications again.' %
478 oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000479 _SERVER.results.edit_expectations(data[KEY__EDITS__MODIFICATIONS])
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000480
481 # Read the updated results back from disk.
482 # We can do this in a separate thread; we should return our success message
483 # to the UI as soon as possible.
484 thread.start_new_thread(_SERVER.update_results, (True,))
epoger@google.comeb832592013-10-23 15:07:26 +0000485
epoger@google.comf9d134d2013-09-27 15:02:44 +0000486 def redirect_to(self, url):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000487 """ Redirect the HTTP client to a different url.
488
489 Args:
490 url: URL to redirect the HTTP client to
491 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000492 self.send_response(301)
493 self.send_header('Location', url)
494 self.end_headers()
495
496 def send_file(self, path):
497 """ Send the contents of the file at this path, with a mimetype based
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000498 on the filename extension.
499
500 Args:
501 path: path of file whose contents to send to the HTTP client
502 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000503 # Grab the extension if there is one
504 extension = os.path.splitext(path)[1]
505 if len(extension) >= 1:
506 extension = extension[1:]
507
508 # Determine the MIME type of the file from its extension
509 mime_type = MIME_TYPE_MAP.get(extension, MIME_TYPE_MAP[''])
510
511 # Open the file and send it over HTTP
512 if os.path.isfile(path):
513 with open(path, 'rb') as sending_file:
514 self.send_response(200)
515 self.send_header('Content-type', mime_type)
516 self.end_headers()
517 self.wfile.write(sending_file.read())
518 else:
519 self.send_error(404)
520
521 def send_json_dict(self, json_dict):
522 """ Send the contents of this dictionary in JSON format, with a JSON
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000523 mimetype.
524
525 Args:
526 json_dict: dictionary to send
527 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000528 self.send_response(200)
529 self.send_header('Content-type', 'application/json')
530 self.end_headers()
531 json.dump(json_dict, self.wfile)
532
533
534def main():
commit-bot@chromium.orga6ecbb82013-12-19 19:08:31 +0000535 logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
536 datefmt='%m/%d/%Y %H:%M:%S',
537 level=logging.INFO)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000538 parser = argparse.ArgumentParser()
539 parser.add_argument('--actuals-dir',
540 help=('Directory into which we will check out the latest '
541 'actual GM results. If this directory does not '
542 'exist, it will be created. Defaults to %(default)s'),
543 default=DEFAULT_ACTUALS_DIR)
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000544 parser.add_argument('--actuals-repo',
545 help=('URL of SVN repo to download actual-results.json '
546 'files from. Defaults to %(default)s'),
547 default=DEFAULT_ACTUALS_REPO_URL)
548 parser.add_argument('--actuals-revision',
549 help=('revision of actual-results.json files to process. '
550 'Defaults to %(default)s . Beware of setting this '
551 'argument in conjunction with --editable; you '
552 'probably only want to edit results at HEAD.'),
553 default=DEFAULT_ACTUALS_REPO_REVISION)
epoger@google.com542b65f2013-10-15 20:10:33 +0000554 parser.add_argument('--editable', action='store_true',
epoger@google.comeb832592013-10-23 15:07:26 +0000555 help=('Allow HTTP clients to submit new baselines.'))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000556 parser.add_argument('--export', action='store_true',
557 help=('Instead of only allowing access from HTTP clients '
558 'on localhost, allow HTTP clients on other hosts '
559 'to access this server. WARNING: doing so will '
560 'allow users on other hosts to modify your '
epoger@google.com542b65f2013-10-15 20:10:33 +0000561 'GM expectations, if combined with --editable.'))
epoger@google.comafaad3d2013-09-30 15:06:25 +0000562 parser.add_argument('--port', type=int,
563 help=('Which TCP port to listen on for HTTP requests; '
564 'defaults to %(default)s'),
565 default=DEFAULT_PORT)
epoger@google.com542b65f2013-10-15 20:10:33 +0000566 parser.add_argument('--reload', type=int,
567 help=('How often (a period in seconds) to update the '
epoger@google.comb063e132013-11-25 18:06:29 +0000568 'results. If specified, both expected and actual '
rmistry@google.comd6bab022013-12-02 13:50:38 +0000569 'results will be updated by running "gclient sync" '
570 'on your Skia checkout as a whole. '
epoger@google.com542b65f2013-10-15 20:10:33 +0000571 'By default, we do not reload at all, and you '
572 'must restart the server to pick up new data.'),
573 default=0)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000574 args = parser.parse_args()
575 global _SERVER
epoger@google.com542b65f2013-10-15 20:10:33 +0000576 _SERVER = Server(actuals_dir=args.actuals_dir,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000577 actuals_repo_revision=args.actuals_revision,
578 actuals_repo_url=args.actuals_repo,
epoger@google.com542b65f2013-10-15 20:10:33 +0000579 port=args.port, export=args.export, editable=args.editable,
580 reload_seconds=args.reload)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000581 _SERVER.run()
582
rmistry@google.comd6bab022013-12-02 13:50:38 +0000583
epoger@google.comf9d134d2013-09-27 15:02:44 +0000584if __name__ == '__main__':
585 main()