blob: d88d3992d780a5a570f811433a9a169468a487fd [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
commit-bot@chromium.org736be352014-03-20 18:31:00 +000090SUMMARY_TYPES = [
91 results_mod.KEY__HEADER__RESULTS_ALL,
92 results_mod.KEY__HEADER__RESULTS_FAILURES,
93]
94
epoger@google.comf9d134d2013-09-27 15:02:44 +000095_SERVER = None # This gets filled in by main()
96
rmistry@google.comd6bab022013-12-02 13:50:38 +000097
98def _run_command(args, directory):
99 """Runs a command and returns stdout as a single string.
100
101 Args:
102 args: the command to run, as a list of arguments
103 directory: directory within which to run the command
104
105 Returns: stdout, as a string
106
107 Raises an Exception if the command failed (exited with nonzero return code).
108 """
109 logging.debug('_run_command: %s in directory %s' % (args, directory))
110 proc = subprocess.Popen(args, cwd=directory,
111 stdout=subprocess.PIPE,
112 stderr=subprocess.PIPE)
113 (stdout, stderr) = proc.communicate()
114 if proc.returncode is not 0:
115 raise Exception('command "%s" failed in dir "%s": %s' %
116 (args, directory, stderr))
117 return stdout
118
119
epoger@google.com591469b2013-11-20 19:58:06 +0000120def _get_routable_ip_address():
epoger@google.comb08c7072013-10-30 14:09:04 +0000121 """Returns routable IP address of this host (the IP address of its network
122 interface that would be used for most traffic, not its localhost
123 interface). See http://stackoverflow.com/a/166589 """
124 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
125 sock.connect(('8.8.8.8', 80))
126 host = sock.getsockname()[0]
127 sock.close()
128 return host
129
rmistry@google.comd6bab022013-12-02 13:50:38 +0000130
epoger@google.com591469b2013-11-20 19:58:06 +0000131def _create_svn_checkout(dir_path, repo_url):
132 """Creates local checkout of an SVN repository at the specified directory
133 path, returning an svn.Svn object referring to the local checkout.
134
135 Args:
136 dir_path: path to the local checkout; if this directory does not yet exist,
137 it will be created and the repo will be checked out into it
138 repo_url: URL of SVN repo to check out into dir_path (unless the local
139 checkout already exists)
140 Returns: an svn.Svn object referring to the local checkout.
141 """
142 local_checkout = svn.Svn(dir_path)
143 if not os.path.isdir(dir_path):
144 os.makedirs(dir_path)
145 local_checkout.Checkout(repo_url, '.')
146 return local_checkout
147
epoger@google.comb08c7072013-10-30 14:09:04 +0000148
epoger@google.comf9d134d2013-09-27 15:02:44 +0000149class Server(object):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000150 """ HTTP server for our HTML rebaseline viewer. """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000151
epoger@google.comf9d134d2013-09-27 15:02:44 +0000152 def __init__(self,
153 actuals_dir=DEFAULT_ACTUALS_DIR,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000154 actuals_repo_revision=DEFAULT_ACTUALS_REPO_REVISION,
155 actuals_repo_url=DEFAULT_ACTUALS_REPO_URL,
epoger@google.com542b65f2013-10-15 20:10:33 +0000156 port=DEFAULT_PORT, export=False, editable=True,
157 reload_seconds=0):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000158 """
159 Args:
160 actuals_dir: directory under which we will check out the latest actual
161 GM results
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000162 actuals_repo_revision: revision of actual-results.json files to process
163 actuals_repo_url: SVN repo to download actual-results.json files from
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000164 port: which TCP port to listen on for HTTP requests
165 export: whether to allow HTTP clients on other hosts to access this server
epoger@google.com542b65f2013-10-15 20:10:33 +0000166 editable: whether HTTP clients are allowed to submit new baselines
167 reload_seconds: polling interval with which to check for new results;
168 if 0, don't check for new results at all
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000169 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000170 self._actuals_dir = actuals_dir
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000171 self._actuals_repo_revision = actuals_repo_revision
172 self._actuals_repo_url = actuals_repo_url
epoger@google.comf9d134d2013-09-27 15:02:44 +0000173 self._port = port
174 self._export = export
epoger@google.com542b65f2013-10-15 20:10:33 +0000175 self._editable = editable
176 self._reload_seconds = reload_seconds
epoger@google.com591469b2013-11-20 19:58:06 +0000177 self._actuals_repo = _create_svn_checkout(
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000178 dir_path=actuals_dir, repo_url=actuals_repo_url)
epoger@google.com591469b2013-11-20 19:58:06 +0000179
commit-bot@chromium.org736be352014-03-20 18:31:00 +0000180 # Since we don't have any results ready yet, prepare a dummy results file
181 # telling any clients that we're still working on the results.
182 response_dict = {
183 results_mod.KEY__HEADER: {
184 results_mod.KEY__HEADER__SCHEMA_VERSION: (
185 results_mod.REBASELINE_SERVER_SCHEMA_VERSION_NUMBER),
186 results_mod.KEY__HEADER__IS_STILL_LOADING: True,
187 results_mod.KEY__HEADER__TIME_UPDATED: 0,
188 results_mod.KEY__HEADER__TIME_NEXT_UPDATE_AVAILABLE: (
189 RELOAD_INTERVAL_UNTIL_READY),
190 },
191 }
192 if not os.path.isdir(GENERATED_JSON_DIR):
193 os.makedirs(GENERATED_JSON_DIR)
194 for summary_type in SUMMARY_TYPES:
195 gm_json.WriteToFile(
196 response_dict,
197 os.path.join(GENERATED_JSON_DIR, '%s.json' % summary_type))
198
rmistry@google.comd6bab022013-12-02 13:50:38 +0000199 # Reentrant lock that must be held whenever updating EITHER of:
200 # 1. self._results
201 # 2. the expected or actual results on local disk
202 self.results_rlock = threading.RLock()
203 # self._results will be filled in by calls to update_results()
204 self._results = None
epoger@google.comf9d134d2013-09-27 15:02:44 +0000205
rmistry@google.comd6bab022013-12-02 13:50:38 +0000206 @property
207 def results(self):
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000208 """ Returns the most recently generated results, or None if we don't have
209 any valid results (update_results() has not completed yet). """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000210 return self._results
211
212 @property
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000213 def is_exported(self):
214 """ Returns true iff HTTP clients on other hosts are allowed to access
215 this server. """
216 return self._export
217
rmistry@google.comd6bab022013-12-02 13:50:38 +0000218 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000219 def is_editable(self):
220 """ Returns true iff HTTP clients are allowed to submit new baselines. """
221 return self._editable
epoger@google.comf9d134d2013-09-27 15:02:44 +0000222
rmistry@google.comd6bab022013-12-02 13:50:38 +0000223 @property
epoger@google.com542b65f2013-10-15 20:10:33 +0000224 def reload_seconds(self):
225 """ Returns the result reload period in seconds, or 0 if we don't reload
226 results. """
227 return self._reload_seconds
228
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000229 def update_results(self, invalidate=False):
commit-bot@chromium.org7498d952014-03-13 14:56:29 +0000230 """ Create or update self._results, based on the latest expectations and
231 actuals.
rmistry@google.comd6bab022013-12-02 13:50:38 +0000232
233 We hold self.results_rlock while we do this, to guarantee that no other
234 thread attempts to update either self._results or the underlying files at
235 the same time.
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000236
237 Args:
238 invalidate: if True, invalidate self._results immediately upon entry;
239 otherwise, we will let readers see those results until we
240 replace them
epoger@google.comf9d134d2013-09-27 15:02:44 +0000241 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000242 with self.results_rlock:
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000243 if invalidate:
244 self._results = None
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000245 logging.info(
246 'Updating actual GM results in %s to revision %s from repo %s ...' % (
247 self._actuals_dir, self._actuals_repo_revision,
248 self._actuals_repo_url))
249 self._actuals_repo.Update(path='.', revision=self._actuals_repo_revision)
epoger@google.com591469b2013-11-20 19:58:06 +0000250
rmistry@google.comd6bab022013-12-02 13:50:38 +0000251 # We only update the expectations dir if the server was run with a
252 # nonzero --reload argument; otherwise, we expect the user to maintain
253 # her own expectations as she sees fit.
254 #
255 # Because the Skia repo is moving from SVN to git, and git does not
256 # support updating a single directory tree, we have to update the entire
257 # repo checkout.
258 #
259 # Because Skia uses depot_tools, we have to update using "gclient sync"
260 # instead of raw git (or SVN) update. Happily, this will work whether
261 # the checkout was created using git or SVN.
262 if self._reload_seconds:
263 logging.info(
264 'Updating expected GM results in %s by syncing Skia repo ...' %
commit-bot@chromium.org7498d952014-03-13 14:56:29 +0000265 results_mod.DEFAULT_EXPECTATIONS_DIR)
rmistry@google.comd6bab022013-12-02 13:50:38 +0000266 _run_command(['gclient', 'sync'], TRUNK_DIRECTORY)
267
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000268 new_results = results_mod.Results(
269 actuals_root=self._actuals_dir,
270 generated_images_root=GENERATED_IMAGES_DIR,
271 diff_base_url=os.path.relpath(
272 GENERATED_IMAGES_DIR, GENERATED_JSON_DIR))
commit-bot@chromium.org736be352014-03-20 18:31:00 +0000273
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000274 if not os.path.isdir(GENERATED_JSON_DIR):
275 os.makedirs(GENERATED_JSON_DIR)
commit-bot@chromium.org736be352014-03-20 18:31:00 +0000276 for summary_type in SUMMARY_TYPES:
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000277 gm_json.WriteToFile(
278 new_results.get_packaged_results_of_type(results_type=summary_type),
279 os.path.join(GENERATED_JSON_DIR, '%s.json' % summary_type))
280
281 self._results = new_results
epoger@google.comf9d134d2013-09-27 15:02:44 +0000282
epoger@google.com2682c902013-12-05 16:05:16 +0000283 def _result_loader(self, reload_seconds=0):
284 """ Call self.update_results(), either once or periodically.
285
286 Params:
287 reload_seconds: integer; if nonzero, reload results at this interval
288 (in which case, this method will never return!)
epoger@google.com542b65f2013-10-15 20:10:33 +0000289 """
epoger@google.com2682c902013-12-05 16:05:16 +0000290 self.update_results()
291 logging.info('Initial results loaded. Ready for requests on %s' % self._url)
292 if reload_seconds:
293 while True:
294 time.sleep(reload_seconds)
295 self.update_results()
epoger@google.com542b65f2013-10-15 20:10:33 +0000296
epoger@google.comf9d134d2013-09-27 15:02:44 +0000297 def run(self):
epoger@google.com2682c902013-12-05 16:05:16 +0000298 arg_tuple = (self._reload_seconds,) # start_new_thread needs a tuple,
299 # even though it holds just one param
300 thread.start_new_thread(self._result_loader, arg_tuple)
epoger@google.com542b65f2013-10-15 20:10:33 +0000301
epoger@google.comf9d134d2013-09-27 15:02:44 +0000302 if self._export:
303 server_address = ('', self._port)
epoger@google.com591469b2013-11-20 19:58:06 +0000304 host = _get_routable_ip_address()
epoger@google.com542b65f2013-10-15 20:10:33 +0000305 if self._editable:
306 logging.warning('Running with combination of "export" and "editable" '
307 'flags. Users on other machines will '
308 'be able to modify your GM expectations!')
epoger@google.comf9d134d2013-09-27 15:02:44 +0000309 else:
epoger@google.comb08c7072013-10-30 14:09:04 +0000310 host = '127.0.0.1'
311 server_address = (host, self._port)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000312 http_server = BaseHTTPServer.HTTPServer(server_address, HTTPRequestHandler)
epoger@google.com2682c902013-12-05 16:05:16 +0000313 self._url = 'http://%s:%d' % (host, http_server.server_port)
314 logging.info('Listening for requests on %s' % self._url)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000315 http_server.serve_forever()
316
317
318class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
319 """ HTTP request handlers for various types of queries this server knows
320 how to handle (static HTML and Javascript, expected/actual results, etc.)
321 """
322 def do_GET(self):
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000323 """
324 Handles all GET requests, forwarding them to the appropriate
325 do_GET_* dispatcher.
epoger@google.comf9d134d2013-09-27 15:02:44 +0000326
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000327 If we see any Exceptions, return a 404. This fixes http://skbug.com/2147
328 """
329 try:
330 logging.debug('do_GET: path="%s"' % self.path)
331 if self.path == '' or self.path == '/' or self.path == '/index.html' :
332 self.redirect_to('/static/index.html')
333 return
334 if self.path == '/favicon.ico' :
335 self.redirect_to('/static/favicon.ico')
336 return
337
338 # All requests must be of this form:
339 # /dispatcher/remainder
340 # where 'dispatcher' indicates which do_GET_* dispatcher to run
341 # and 'remainder' is the remaining path sent to that dispatcher.
342 normpath = posixpath.normpath(self.path)
343 (dispatcher_name, remainder) = PATHSPLIT_RE.match(normpath).groups()
344 dispatchers = {
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000345 'static': self.do_GET_static,
346 }
347 dispatcher = dispatchers[dispatcher_name]
348 dispatcher(remainder)
349 except:
350 self.send_error(404)
351 raise
epoger@google.comf9d134d2013-09-27 15:02:44 +0000352
epoger@google.comf9d134d2013-09-27 15:02:44 +0000353 def do_GET_static(self, path):
epoger@google.comcb55f112013-10-02 19:27:35 +0000354 """ Handle a GET request for a file under the 'static' directory.
355 Only allow serving of files within the 'static' directory that is a
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000356 filesystem sibling of this script.
357
358 Args:
359 path: path to file (under static directory) to retrieve
360 """
epoger@google.comdcb4e652013-10-11 18:45:33 +0000361 # Strip arguments ('?resultsToLoad=all') from the path
362 path = urlparse.urlparse(path).path
363
364 logging.debug('do_GET_static: sending file "%s"' % path)
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000365 full_path = os.path.realpath(os.path.join(STATIC_CONTENTS_DIR, path))
366 if full_path.startswith(STATIC_CONTENTS_DIR):
epoger@google.comcb55f112013-10-02 19:27:35 +0000367 self.send_file(full_path)
368 else:
epoger@google.comdcb4e652013-10-11 18:45:33 +0000369 logging.error(
370 'Attempted do_GET_static() of path [%s] outside of static dir [%s]'
commit-bot@chromium.org57994232014-03-20 17:27:46 +0000371 % (full_path, STATIC_CONTENTS_DIR))
epoger@google.comcb55f112013-10-02 19:27:35 +0000372 self.send_error(404)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000373
epoger@google.comeb832592013-10-23 15:07:26 +0000374 def do_POST(self):
375 """ Handles all POST requests, forwarding them to the appropriate
376 do_POST_* dispatcher. """
377 # All requests must be of this form:
378 # /dispatcher
379 # where 'dispatcher' indicates which do_POST_* dispatcher to run.
commit-bot@chromium.orge6af4fb2014-02-07 18:21:59 +0000380 logging.debug('do_POST: path="%s"' % self.path)
epoger@google.comeb832592013-10-23 15:07:26 +0000381 normpath = posixpath.normpath(self.path)
382 dispatchers = {
383 '/edits': self.do_POST_edits,
384 }
385 try:
386 dispatcher = dispatchers[normpath]
387 dispatcher()
388 self.send_response(200)
389 except:
390 self.send_error(404)
391 raise
392
393 def do_POST_edits(self):
394 """ Handle a POST request with modifications to GM expectations, in this
395 format:
396
397 {
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000398 KEY__EDITS__OLD_RESULTS_TYPE: 'all', # type of results that the client
399 # loaded and then made
400 # modifications to
401 KEY__EDITS__OLD_RESULTS_HASH: 39850913, # hash of results when the client
402 # loaded them (ensures that the
403 # client and server apply
404 # modifications to the same base)
405 KEY__EDITS__MODIFICATIONS: [
commit-bot@chromium.org7498d952014-03-13 14:56:29 +0000406 # as needed by results_mod.edit_expectations()
epoger@google.comeb832592013-10-23 15:07:26 +0000407 ...
408 ],
409 }
410
411 Raises an Exception if there were any problems.
412 """
rmistry@google.comd6bab022013-12-02 13:50:38 +0000413 if not _SERVER.is_editable:
epoger@google.comeb832592013-10-23 15:07:26 +0000414 raise Exception('this server is not running in --editable mode')
415
416 content_type = self.headers[_HTTP_HEADER_CONTENT_TYPE]
417 if content_type != 'application/json;charset=UTF-8':
418 raise Exception('unsupported %s [%s]' % (
419 _HTTP_HEADER_CONTENT_TYPE, content_type))
420
421 content_length = int(self.headers[_HTTP_HEADER_CONTENT_LENGTH])
422 json_data = self.rfile.read(content_length)
423 data = json.loads(json_data)
424 logging.debug('do_POST_edits: received new GM expectations data [%s]' %
425 data)
426
rmistry@google.comd6bab022013-12-02 13:50:38 +0000427 # Update the results on disk with the information we received from the
428 # client.
429 # We must hold _SERVER.results_rlock while we do this, to guarantee that
430 # no other thread updates expectations (from the Skia repo) while we are
431 # updating them (using the info we received from the client).
432 with _SERVER.results_rlock:
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000433 oldResultsType = data[KEY__EDITS__OLD_RESULTS_TYPE]
rmistry@google.comd6bab022013-12-02 13:50:38 +0000434 oldResults = _SERVER.results.get_results_of_type(oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000435 oldResultsHash = str(hash(repr(oldResults[imagepairset.KEY__IMAGEPAIRS])))
436 if oldResultsHash != data[KEY__EDITS__OLD_RESULTS_HASH]:
rmistry@google.comd6bab022013-12-02 13:50:38 +0000437 raise Exception('results of type "%s" changed while the client was '
438 'making modifications. The client should reload the '
439 'results and submit the modifications again.' %
440 oldResultsType)
commit-bot@chromium.org16f41802014-02-26 19:05:20 +0000441 _SERVER.results.edit_expectations(data[KEY__EDITS__MODIFICATIONS])
commit-bot@chromium.org50ad8e42013-12-17 18:06:13 +0000442
443 # Read the updated results back from disk.
444 # We can do this in a separate thread; we should return our success message
445 # to the UI as soon as possible.
446 thread.start_new_thread(_SERVER.update_results, (True,))
epoger@google.comeb832592013-10-23 15:07:26 +0000447
epoger@google.comf9d134d2013-09-27 15:02:44 +0000448 def redirect_to(self, url):
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000449 """ Redirect the HTTP client to a different url.
450
451 Args:
452 url: URL to redirect the HTTP client to
453 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000454 self.send_response(301)
455 self.send_header('Location', url)
456 self.end_headers()
457
458 def send_file(self, path):
459 """ Send the contents of the file at this path, with a mimetype based
epoger@google.com9fb6c8a2013-10-09 18:05:58 +0000460 on the filename extension.
461
462 Args:
463 path: path of file whose contents to send to the HTTP client
464 """
epoger@google.comf9d134d2013-09-27 15:02:44 +0000465 # Grab the extension if there is one
466 extension = os.path.splitext(path)[1]
467 if len(extension) >= 1:
468 extension = extension[1:]
469
470 # Determine the MIME type of the file from its extension
471 mime_type = MIME_TYPE_MAP.get(extension, MIME_TYPE_MAP[''])
472
473 # Open the file and send it over HTTP
474 if os.path.isfile(path):
475 with open(path, 'rb') as sending_file:
476 self.send_response(200)
477 self.send_header('Content-type', mime_type)
478 self.end_headers()
479 self.wfile.write(sending_file.read())
480 else:
481 self.send_error(404)
482
epoger@google.comf9d134d2013-09-27 15:02:44 +0000483
484def main():
commit-bot@chromium.orga6ecbb82013-12-19 19:08:31 +0000485 logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
486 datefmt='%m/%d/%Y %H:%M:%S',
487 level=logging.INFO)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000488 parser = argparse.ArgumentParser()
489 parser.add_argument('--actuals-dir',
490 help=('Directory into which we will check out the latest '
491 'actual GM results. If this directory does not '
492 'exist, it will be created. Defaults to %(default)s'),
493 default=DEFAULT_ACTUALS_DIR)
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000494 parser.add_argument('--actuals-repo',
495 help=('URL of SVN repo to download actual-results.json '
496 'files from. Defaults to %(default)s'),
497 default=DEFAULT_ACTUALS_REPO_URL)
498 parser.add_argument('--actuals-revision',
499 help=('revision of actual-results.json files to process. '
500 'Defaults to %(default)s . Beware of setting this '
501 'argument in conjunction with --editable; you '
502 'probably only want to edit results at HEAD.'),
503 default=DEFAULT_ACTUALS_REPO_REVISION)
epoger@google.com542b65f2013-10-15 20:10:33 +0000504 parser.add_argument('--editable', action='store_true',
epoger@google.comeb832592013-10-23 15:07:26 +0000505 help=('Allow HTTP clients to submit new baselines.'))
epoger@google.comf9d134d2013-09-27 15:02:44 +0000506 parser.add_argument('--export', action='store_true',
507 help=('Instead of only allowing access from HTTP clients '
508 'on localhost, allow HTTP clients on other hosts '
509 'to access this server. WARNING: doing so will '
510 'allow users on other hosts to modify your '
epoger@google.com542b65f2013-10-15 20:10:33 +0000511 'GM expectations, if combined with --editable.'))
epoger@google.comafaad3d2013-09-30 15:06:25 +0000512 parser.add_argument('--port', type=int,
513 help=('Which TCP port to listen on for HTTP requests; '
514 'defaults to %(default)s'),
515 default=DEFAULT_PORT)
epoger@google.com542b65f2013-10-15 20:10:33 +0000516 parser.add_argument('--reload', type=int,
517 help=('How often (a period in seconds) to update the '
epoger@google.comb063e132013-11-25 18:06:29 +0000518 'results. If specified, both expected and actual '
rmistry@google.comd6bab022013-12-02 13:50:38 +0000519 'results will be updated by running "gclient sync" '
520 'on your Skia checkout as a whole. '
epoger@google.com542b65f2013-10-15 20:10:33 +0000521 'By default, we do not reload at all, and you '
522 'must restart the server to pick up new data.'),
523 default=0)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000524 args = parser.parse_args()
525 global _SERVER
epoger@google.com542b65f2013-10-15 20:10:33 +0000526 _SERVER = Server(actuals_dir=args.actuals_dir,
commit-bot@chromium.org5865ec52014-03-10 18:09:25 +0000527 actuals_repo_revision=args.actuals_revision,
528 actuals_repo_url=args.actuals_repo,
epoger@google.com542b65f2013-10-15 20:10:33 +0000529 port=args.port, export=args.export, editable=args.editable,
530 reload_seconds=args.reload)
epoger@google.comf9d134d2013-09-27 15:02:44 +0000531 _SERVER.run()
532
rmistry@google.comd6bab022013-12-02 13:50:38 +0000533
epoger@google.comf9d134d2013-09-27 15:02:44 +0000534if __name__ == '__main__':
535 main()