blob: 1ca5757b1a72c5259424584732e5ac56dfa50364 [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.org57994232014-03-20 17:27:46 +000031# We need to add the 'tools' directory for svn.py, and the 'gm' directory for
32# gm_json.py .
33# Make sure that these dirs are in the PYTHONPATH, but add them 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.org57994232014-03-20 17:27:46 +000036GM_DIRECTORY = os.path.dirname(PARENT_DIRECTORY)
37TRUNK_DIRECTORY = os.path.dirname(GM_DIRECTORY)
epoger@google.comf9d134d2013-09-27 15:02:44 +000038TOOLS_DIRECTORY = os.path.join(TRUNK_DIRECTORY, 'tools')
39if TOOLS_DIRECTORY not in sys.path:
40 sys.path.append(TOOLS_DIRECTORY)
41import svn
commit-bot@chromium.org57994232014-03-20 17:27:46 +000042if GM_DIRECTORY not in sys.path:
43 sys.path.append(GM_DIRECTORY)
44import gm_json
epoger@google.comf9d134d2013-09-27 15:02:44 +000045
46# Imports from local dir
commit-bot@chromium.org7498d952014-03-13 14:56:29 +000047#
48# Note: we import results under a different name, to avoid confusion with the
49# Server.results() property. See discussion at
50# https://codereview.chromium.org/195943004/diff/1/gm/rebaseline_server/server.py#newcode44
commit-bot@chromium.org16f41802014-02-26 19:05:20 +000051import imagepairset
commit-bot@chromium.org7498d952014-03-13 14:56:29 +000052import results as results_mod
epoger@google.comf9d134d2013-09-27 15:02:44 +000053
epoger@google.comf9d134d2013-09-27 15:02:44 +000054PATHSPLIT_RE = re.compile('/([^/]+)/(.+)')
epoger@google.comf9d134d2013-09-27 15:02:44 +000055
56# A simple dictionary of file name extensions to MIME types. The empty string
57# entry is used as the default when no extension was given or if the extension
58# has no entry in this dictionary.
59MIME_TYPE_MAP = {'': 'application/octet-stream',
60 'html': 'text/html',
61 'css': 'text/css',
62 'png': 'image/png',
63 'js': 'application/javascript',
64 'json': 'application/json'
65 }
66
commit-bot@chromium.org16f41802014-02-26 19:05:20 +000067# Keys that server.py uses to create the toplevel content header.
68# NOTE: Keep these in sync with static/constants.js
69KEY__EDITS__MODIFICATIONS = 'modifications'
70KEY__EDITS__OLD_RESULTS_HASH = 'oldResultsHash'
71KEY__EDITS__OLD_RESULTS_TYPE = 'oldResultsType'
commit-bot@chromium.org16f41802014-02-26 19:05:20 +000072
commit-bot@chromium.org7498d952014-03-13 14:56:29 +000073DEFAULT_ACTUALS_DIR = results_mod.DEFAULT_ACTUALS_DIR
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +000074DEFAULT_ACTUALS_REPO_REVISION = 'HEAD'
75DEFAULT_ACTUALS_REPO_URL = 'http://skia-autogen.googlecode.com/svn/gm-actual'
epoger@google.comf9d134d2013-09-27 15:02:44 +000076DEFAULT_PORT = 8888
77
commit-bot@chromium.org57994232014-03-20 17:27:46 +000078# Directory within which the server will serve out static files.
79STATIC_CONTENTS_DIR = os.path.realpath(os.path.join(PARENT_DIRECTORY, 'static'))
80GENERATED_IMAGES_DIR = os.path.join(STATIC_CONTENTS_DIR, 'generated-images')
81GENERATED_JSON_DIR = os.path.join(STATIC_CONTENTS_DIR, 'generated-json')
82
epoger@google.com2682c902013-12-05 16:05:16 +000083# How often (in seconds) clients should reload while waiting for initial
84# results to load.
85RELOAD_INTERVAL_UNTIL_READY = 10
86
epoger@google.comeb832592013-10-23 15:07:26 +000087_HTTP_HEADER_CONTENT_LENGTH = 'Content-Length'
88_HTTP_HEADER_CONTENT_TYPE = 'Content-Type'
89
epoger@google.comf9d134d2013-09-27 15:02:44 +000090_SERVER = None # This gets filled in by main()
91
rmistry@google.comd6bab022013-12-02 13:50:38 +000092
93def _run_command(args, directory):
94 """Runs a command and returns stdout as a single string.
95
96 Args:
97 args: the command to run, as a list of arguments
98 directory: directory within which to run the command
99
100 Returns: stdout, as a string
101
102 Raises an Exception if the command failed (exited with nonzero return code).
103 """
104 logging.debug('_run_command: %s in directory %s' % (args, directory))
105 proc = subprocess.Popen(args, cwd=directory,
106 stdout=subprocess.PIPE,
107 stderr=subprocess.PIPE)
108 (stdout, stderr) = proc.communicate()
109 if proc.returncode is not 0:
110 raise Exception('command "%s" failed in dir "%s": %s' %
111 (args, directory, stderr))
112 return stdout
113
114
epoger@google.com591469b2013-11-20 19:58:06 +0000115def _get_routable_ip_address():
epoger@google.comb08c7072013-10-30 14:09:04 +0000116 """Returns routable IP address of this host (the IP address of its network
117 interface that would be used for most traffic, not its localhost
118 interface). See http://stackoverflow.com/a/166589 """
119 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
120 sock.connect(('8.8.8.8', 80))
121 host = sock.getsockname()[0]
122 sock.close()
123 return host
124
rmistry@google.comd6bab022013-12-02 13:50:38 +0000125
epoger@google.com591469b2013-11-20 19:58:06 +0000126def _create_svn_checkout(dir_path, repo_url):
127 """Creates local checkout of an SVN repository at the specified directory
128 path, returning an svn.Svn object referring to the local checkout.
129
130 Args:
131 dir_path: path to the local checkout; if this directory does not yet exist,
132 it will be created and the repo will be checked out into it
133 repo_url: URL of SVN repo to check out into dir_path (unless the local
134 checkout already exists)
135 Returns: an svn.Svn object referring to the local checkout.
136 """
137 local_checkout = svn.Svn(dir_path)
138 if not os.path.isdir(dir_path):
139 os.makedirs(dir_path)
140 local_checkout.Checkout(repo_url, '.')
141 return local_checkout
142
epoger@google.comb08c7072013-10-30 14:09:04 +0000143
epoger@google.comf9d134d2013-09-27 15:02:44 +0000144class Server(object):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000145 """ HTTP server for our HTML rebaseline viewer. """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000146
epoger@google.comf9d134d2013-09-27 15:02:44 +0000147 def __init__(self,
148 actuals_dir=DEFAULT_ACTUALS_DIR,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000149 actuals_repo_revision=DEFAULT_ACTUALS_REPO_REVISION,
150 actuals_repo_url=DEFAULT_ACTUALS_REPO_URL,
epoger@google.com542b65f2013-10-15 20:10:33 +0000151 port=DEFAULT_PORT, export=False, editable=True,
152 reload_seconds=0):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000153 """
154 Args:
155 actuals_dir: directory under which we will check out the latest actual
156 GM results
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000157 actuals_repo_revision: revision of actual-results.json files to process
158 actuals_repo_url: SVN repo to download actual-results.json files from
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000159 port: which TCP port to listen on for HTTP requests
160 export: whether to allow HTTP clients on other hosts to access this server
epoger@google.com542b65f2013-10-15 20:10:33 +0000161 editable: whether HTTP clients are allowed to submit new baselines
162 reload_seconds: polling interval with which to check for new results;
163 if 0, don't check for new results at all
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000164 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000165 self._actuals_dir = actuals_dir
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000166 self._actuals_repo_revision = actuals_repo_revision
167 self._actuals_repo_url = actuals_repo_url
epoger@google.comf9d134d2013-09-27 15:02:44 +0000168 self._port = port
169 self._export = export
epoger@google.com542b65f2013-10-15 20:10:33 +0000170 self._editable = editable
171 self._reload_seconds = reload_seconds
epoger@google.com591469b2013-11-20 19:58:06 +0000172 self._actuals_repo = _create_svn_checkout(
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000173 dir_path=actuals_dir, repo_url=actuals_repo_url)
epoger@google.com591469b2013-11-20 19:58:06 +0000174
rmistry@google.comd6bab022013-12-02 13:50:38 +0000175 # Reentrant lock that must be held whenever updating EITHER of:
176 # 1. self._results
177 # 2. the expected or actual results on local disk
178 self.results_rlock = threading.RLock()
179 # self._results will be filled in by calls to update_results()
180 self._results = None
epoger@google.comf9d134d2013-09-27 15:02:44 +0000181
rmistry@google.comd6bab022013-12-02 13:50:38 +0000182 @property
183 def results(self):
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000184 """ Returns the most recently generated results, or None if we don't have
185 any valid results (update_results() has not completed yet). """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000186 return self._results
187
188 @property
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000189 def is_exported(self):
190 """ Returns true iff HTTP clients on other hosts are allowed to access
191 this server. """
192 return self._export
193
rmistry@google.comd6bab022013-12-02 13:50:38 +0000194 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000195 def is_editable(self):
196 """ Returns true iff HTTP clients are allowed to submit new baselines. """
197 return self._editable
epoger@google.comf9d134d2013-09-27 15:02:44 +0000198
rmistry@google.comd6bab022013-12-02 13:50:38 +0000199 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000200 def reload_seconds(self):
201 """ Returns the result reload period in seconds, or 0 if we don't reload
202 results. """
203 return self._reload_seconds
204
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000205 def update_results(self, invalidate=False):
commit-bot@chromium.org7498d952014-03-13 14:56:29 +0000206 """ Create or update self._results, based on the latest expectations and
207 actuals.
rmistry@google.comd6bab022013-12-02 13:50:38 +0000208
209 We hold self.results_rlock while we do this, to guarantee that no other
210 thread attempts to update either self._results or the underlying files at
211 the same time.
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000212
213 Args:
214 invalidate: if True, invalidate self._results immediately upon entry;
215 otherwise, we will let readers see those results until we
216 replace them
epoger@google.comf9d134d2013-09-27 15:02:44 +0000217 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000218 with self.results_rlock:
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000219 if invalidate:
220 self._results = None
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000221 logging.info(
222 'Updating actual GM results in %s to revision %s from repo %s ...' % (
223 self._actuals_dir, self._actuals_repo_revision,
224 self._actuals_repo_url))
225 self._actuals_repo.Update(path='.', revision=self._actuals_repo_revision)
epoger@google.com591469b2013-11-20 19:58:06 +0000226
rmistry@google.comd6bab022013-12-02 13:50:38 +0000227 # We only update the expectations dir if the server was run with a
228 # nonzero --reload argument; otherwise, we expect the user to maintain
229 # her own expectations as she sees fit.
230 #
231 # Because the Skia repo is moving from SVN to git, and git does not
232 # support updating a single directory tree, we have to update the entire
233 # repo checkout.
234 #
235 # Because Skia uses depot_tools, we have to update using "gclient sync"
236 # instead of raw git (or SVN) update. Happily, this will work whether
237 # the checkout was created using git or SVN.
238 if self._reload_seconds:
239 logging.info(
240 'Updating expected GM results in %s by syncing Skia repo ...' %
commit-bot@chromium.org7498d952014-03-13 14:56:29 +0000241 results_mod.DEFAULT_EXPECTATIONS_DIR)
rmistry@google.comd6bab022013-12-02 13:50:38 +0000242 _run_command(['gclient', 'sync'], TRUNK_DIRECTORY)
243
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000244 new_results = results_mod.Results(
245 actuals_root=self._actuals_dir,
246 generated_images_root=GENERATED_IMAGES_DIR,
247 diff_base_url=os.path.relpath(
248 GENERATED_IMAGES_DIR, GENERATED_JSON_DIR))
249 if not os.path.isdir(GENERATED_JSON_DIR):
250 os.makedirs(GENERATED_JSON_DIR)
251 for summary_type in [results_mod.KEY__HEADER__RESULTS_ALL,
252 results_mod.KEY__HEADER__RESULTS_FAILURES]:
253 gm_json.WriteToFile(
254 new_results.get_packaged_results_of_type(results_type=summary_type),
255 os.path.join(GENERATED_JSON_DIR, '%s.json' % summary_type))
256
257 self._results = new_results
epoger@google.comf9d134d2013-09-27 15:02:44 +0000258
epoger@google.com2682c902013-12-05 16:05:16 +0000259 def _result_loader(self, reload_seconds=0):
260 """ Call self.update_results(), either once or periodically.
261
262 Params:
263 reload_seconds: integer; if nonzero, reload results at this interval
264 (in which case, this method will never return!)
epoger@google.com542b65f2013-10-15 20:10:33 +0000265 """
epoger@google.com2682c902013-12-05 16:05:16 +0000266 self.update_results()
267 logging.info('Initial results loaded. Ready for requests on %s' % self._url)
268 if reload_seconds:
269 while True:
270 time.sleep(reload_seconds)
271 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000272
epoger@google.comf9d134d2013-09-27 15:02:44 +0000273 def run(self):
epoger@google.com2682c902013-12-05 16:05:16 +0000274 arg_tuple = (self._reload_seconds,) # start_new_thread needs a tuple,
275 # even though it holds just one param
276 thread.start_new_thread(self._result_loader, arg_tuple)
epoger@google.com542b65f2013-10-15 20:10:33 +0000277
epoger@google.comf9d134d2013-09-27 15:02:44 +0000278 if self._export:
279 server_address = ('', self._port)
epoger@google.com591469b2013-11-20 19:58:06 +0000280 host = _get_routable_ip_address()
epoger@google.com542b65f2013-10-15 20:10:33 +0000281 if self._editable:
282 logging.warning('Running with combination of "export" and "editable" '
283 'flags. Users on other machines will '
284 'be able to modify your GM expectations!')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000285 else:
epoger@google.comb08c7072013-10-30 14:09:04 +0000286 host = '127.0.0.1'
287 server_address = (host, self._port)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000288 http_server = BaseHTTPServer.HTTPServer(server_address, HTTPRequestHandler)
epoger@google.com2682c902013-12-05 16:05:16 +0000289 self._url = 'http://%s:%d' % (host, http_server.server_port)
290 logging.info('Listening for requests on %s' % self._url)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000291 http_server.serve_forever()
292
293
294class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
295 """ HTTP request handlers for various types of queries this server knows
296 how to handle (static HTML and Javascript, expected/actual results, etc.)
297 """
298 def do_GET(self):
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000299 """
300 Handles all GET requests, forwarding them to the appropriate
301 do_GET_* dispatcher.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000302
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000303 If we see any Exceptions, return a 404. This fixes http://skbug.com/2147
304 """
305 try:
306 logging.debug('do_GET: path="%s"' % self.path)
307 if self.path == '' or self.path == '/' or self.path == '/index.html' :
308 self.redirect_to('/static/index.html')
309 return
310 if self.path == '/favicon.ico' :
311 self.redirect_to('/static/favicon.ico')
312 return
313
314 # All requests must be of this form:
315 # /dispatcher/remainder
316 # where 'dispatcher' indicates which do_GET_* dispatcher to run
317 # and 'remainder' is the remaining path sent to that dispatcher.
318 normpath = posixpath.normpath(self.path)
319 (dispatcher_name, remainder) = PATHSPLIT_RE.match(normpath).groups()
320 dispatchers = {
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000321 'static': self.do_GET_static,
322 }
323 dispatcher = dispatchers[dispatcher_name]
324 dispatcher(remainder)
325 except:
326 self.send_error(404)
327 raise
epoger@google.comf9d134d2013-09-27 15:02:44 +0000328
epoger@google.comf9d134d2013-09-27 15:02:44 +0000329 def do_GET_static(self, path):
epoger@google.comcb55f112013-10-02 19:27:35 +0000330 """ Handle a GET request for a file under the 'static' directory.
331 Only allow serving of files within the 'static' directory that is a
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000332 filesystem sibling of this script.
333
334 Args:
335 path: path to file (under static directory) to retrieve
336 """
epoger@google.comdcb4e652013-10-11 18:45:33 +0000337 # Strip arguments ('?resultsToLoad=all') from the path
338 path = urlparse.urlparse(path).path
339
340 logging.debug('do_GET_static: sending file "%s"' % path)
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000341 full_path = os.path.realpath(os.path.join(STATIC_CONTENTS_DIR, path))
342 if full_path.startswith(STATIC_CONTENTS_DIR):
epoger@google.comcb55f112013-10-02 19:27:35 +0000343 self.send_file(full_path)
344 else:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000345 logging.error(
346 'Attempted do_GET_static() of path [%s] outside of static dir [%s]'
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000347 % (full_path, STATIC_CONTENTS_DIR))
epoger@google.comcb55f112013-10-02 19:27:35 +0000348 self.send_error(404)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000349
epoger@google.comeb832592013-10-23 15:07:26 +0000350 def do_POST(self):
351 """ Handles all POST requests, forwarding them to the appropriate
352 do_POST_* dispatcher. """
353 # All requests must be of this form:
354 # /dispatcher
355 # where 'dispatcher' indicates which do_POST_* dispatcher to run.
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000356 logging.debug('do_POST: path="%s"' % self.path)
epoger@google.comeb832592013-10-23 15:07:26 +0000357 normpath = posixpath.normpath(self.path)
358 dispatchers = {
359 '/edits': self.do_POST_edits,
360 }
361 try:
362 dispatcher = dispatchers[normpath]
363 dispatcher()
364 self.send_response(200)
365 except:
366 self.send_error(404)
367 raise
368
369 def do_POST_edits(self):
370 """ Handle a POST request with modifications to GM expectations, in this
371 format:
372
373 {
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000374 KEY__EDITS__OLD_RESULTS_TYPE: 'all', # type of results that the client
375 # loaded and then made
376 # modifications to
377 KEY__EDITS__OLD_RESULTS_HASH: 39850913, # hash of results when the client
378 # loaded them (ensures that the
379 # client and server apply
380 # modifications to the same base)
381 KEY__EDITS__MODIFICATIONS: [
commit-bot@chromium.org7498d952014-03-13 14:56:29 +0000382 # as needed by results_mod.edit_expectations()
epoger@google.comeb832592013-10-23 15:07:26 +0000383 ...
384 ],
385 }
386
387 Raises an Exception if there were any problems.
388 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000389 if not _SERVER.is_editable:
epoger@google.comeb832592013-10-23 15:07:26 +0000390 raise Exception('this server is not running in --editable mode')
391
392 content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE]
393 if content_type != 'application/json;charset=UTF-8':
394 raise Exception('unsupported %s [%s]' % (
395 _HTTP_HEADER_CONTENT_TYPE, content_type))
396
397 content_length = int(self.headers[_HTTP_HEADER_CONTENT_LENGTH])
398 json_data = self.rfile.read(content_length)
399 data = json.loads(json_data)
400 logging.debug('do_POST_edits: received new GM expectations data [%s]' %
401 data)
402
rmistry@google.comd6bab022013-12-02 13:50:38 +0000403 # Update the results on disk with the information we received from the
404 # client.
405 # We must hold _SERVER.results_rlock while we do this, to guarantee that
406 # no other thread updates expectations (from the Skia repo) while we are
407 # updating them (using the info we received from the client).
408 with _SERVER.results_rlock:
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000409 oldResultsType = data[KEY__EDITS__OLD_RESULTS_TYPE]
rmistry@google.comd6bab022013-12-02 13:50:38 +0000410 oldResults = _SERVER.results.get_results_of_type(oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000411 oldResultsHash = str(hash(repr(oldResults[imagepairset.KEY__IMAGEPAIRS])))
412 if oldResultsHash != data[KEY__EDITS__OLD_RESULTS_HASH]:
rmistry@google.comd6bab022013-12-02 13:50:38 +0000413 raise Exception('results of type "%s" changed while the client was '
414 'making modifications. The client should reload the '
415 'results and submit the modifications again.' %
416 oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000417 _SERVER.results.edit_expectations(data[KEY__EDITS__MODIFICATIONS])
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000418
419 # Read the updated results back from disk.
420 # We can do this in a separate thread; we should return our success message
421 # to the UI as soon as possible.
422 thread.start_new_thread(_SERVER.update_results, (True,))
epoger@google.comeb832592013-10-23 15:07:26 +0000423
epoger@google.comf9d134d2013-09-27 15:02:44 +0000424 def redirect_to(self, url):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000425 """ Redirect the HTTP client to a different url.
426
427 Args:
428 url: URL to redirect the HTTP client to
429 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000430 self.send_response(301)
431 self.send_header('Location', url)
432 self.end_headers()
433
434 def send_file(self, path):
435 """ Send the contents of the file at this path, with a mimetype based
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000436 on the filename extension.
437
438 Args:
439 path: path of file whose contents to send to the HTTP client
440 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000441 # Grab the extension if there is one
442 extension = os.path.splitext(path)[1]
443 if len(extension) >= 1:
444 extension = extension[1:]
445
446 # Determine the MIME type of the file from its extension
447 mime_type = MIME_TYPE_MAP.get(extension, MIME_TYPE_MAP[''])
448
449 # Open the file and send it over HTTP
450 if os.path.isfile(path):
451 with open(path, 'rb') as sending_file:
452 self.send_response(200)
453 self.send_header('Content-type', mime_type)
454 self.end_headers()
455 self.wfile.write(sending_file.read())
456 else:
457 self.send_error(404)
458
epoger@google.comf9d134d2013-09-27 15:02:44 +0000459
460def main():
commit-bot@chromium.orga6ecbb82013-12-19 19:08:31 +0000461 logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
462 datefmt='%m/%d/%Y %H:%M:%S',
463 level=logging.INFO)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000464 parser = argparse.ArgumentParser()
465 parser.add_argument('--actuals-dir',
466 help=('Directory into which we will check out the latest '
467 'actual GM results. If this directory does not '
468 'exist, it will be created. Defaults to %(default)s'),
469 default=DEFAULT_ACTUALS_DIR)
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000470 parser.add_argument('--actuals-repo',
471 help=('URL of SVN repo to download actual-results.json '
472 'files from. Defaults to %(default)s'),
473 default=DEFAULT_ACTUALS_REPO_URL)
474 parser.add_argument('--actuals-revision',
475 help=('revision of actual-results.json files to process. '
476 'Defaults to %(default)s . Beware of setting this '
477 'argument in conjunction with --editable; you '
478 'probably only want to edit results at HEAD.'),
479 default=DEFAULT_ACTUALS_REPO_REVISION)
epoger@google.com542b65f2013-10-15 20:10:33 +0000480 parser.add_argument('--editable', action='store_true',
epoger@google.comeb832592013-10-23 15:07:26 +0000481 help=('Allow HTTP clients to submit new baselines.'))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000482 parser.add_argument('--export', action='store_true',
483 help=('Instead of only allowing access from HTTP clients '
484 'on localhost, allow HTTP clients on other hosts '
485 'to access this server. WARNING: doing so will '
486 'allow users on other hosts to modify your '
epoger@google.com542b65f2013-10-15 20:10:33 +0000487 'GM expectations, if combined with --editable.'))
epoger@google.comafaad3d2013-09-30 15:06:25 +0000488 parser.add_argument('--port', type=int,
489 help=('Which TCP port to listen on for HTTP requests; '
490 'defaults to %(default)s'),
491 default=DEFAULT_PORT)
epoger@google.com542b65f2013-10-15 20:10:33 +0000492 parser.add_argument('--reload', type=int,
493 help=('How often (a period in seconds) to update the '
epoger@google.comb063e132013-11-25 18:06:29 +0000494 'results. If specified, both expected and actual '
rmistry@google.comd6bab022013-12-02 13:50:38 +0000495 'results will be updated by running "gclient sync" '
496 'on your Skia checkout as a whole. '
epoger@google.com542b65f2013-10-15 20:10:33 +0000497 'By default, we do not reload at all, and you '
498 'must restart the server to pick up new data.'),
499 default=0)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000500 args = parser.parse_args()
501 global _SERVER
epoger@google.com542b65f2013-10-15 20:10:33 +0000502 _SERVER = Server(actuals_dir=args.actuals_dir,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000503 actuals_repo_revision=args.actuals_revision,
504 actuals_repo_url=args.actuals_repo,
epoger@google.com542b65f2013-10-15 20:10:33 +0000505 port=args.port, export=args.export, editable=args.editable,
506 reload_seconds=args.reload)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000507 _SERVER.run()
508
rmistry@google.comd6bab022013-12-02 13:50:38 +0000509
epoger@google.comf9d134d2013-09-27 15:02:44 +0000510if __name__ == '__main__':
511 main()