testserver_base.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # Copyright 2013 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. from six.moves import BaseHTTPServer
  5. import errno
  6. import json
  7. import optparse
  8. import os
  9. import re
  10. import socket
  11. from six.moves import socketserver as SocketServer
  12. import struct
  13. import sys
  14. import warnings
  15. # Ignore deprecation warnings, they make our output more cluttered.
  16. warnings.filterwarnings("ignore", category=DeprecationWarning)
  17. if sys.platform == 'win32':
  18. import msvcrt
  19. # Using debug() seems to cause hangs on XP: see http://crbug.com/64515.
  20. debug_output = sys.stderr
  21. def debug(string):
  22. debug_output.write(string + "\n")
  23. debug_output.flush()
  24. class Error(Exception):
  25. """Error class for this module."""
  26. class OptionError(Error):
  27. """Error for bad command line options."""
  28. class FileMultiplexer(object):
  29. def __init__(self, fd1, fd2) :
  30. self.__fd1 = fd1
  31. self.__fd2 = fd2
  32. def __del__(self) :
  33. if self.__fd1 != sys.stdout and self.__fd1 != sys.stderr:
  34. self.__fd1.close()
  35. if self.__fd2 != sys.stdout and self.__fd2 != sys.stderr:
  36. self.__fd2.close()
  37. def write(self, text) :
  38. self.__fd1.write(text)
  39. self.__fd2.write(text)
  40. def flush(self) :
  41. self.__fd1.flush()
  42. self.__fd2.flush()
  43. class ClientRestrictingServerMixIn:
  44. """Implements verify_request to limit connections to our configured IP
  45. address."""
  46. def verify_request(self, _request, client_address):
  47. return client_address[0] == self.server_address[0]
  48. class BrokenPipeHandlerMixIn:
  49. """Allows the server to deal with "broken pipe" errors (which happen if the
  50. browser quits with outstanding requests, like for the favicon). This mix-in
  51. requires the class to derive from SocketServer.BaseServer and not override its
  52. handle_error() method. """
  53. def handle_error(self, request, client_address):
  54. value = sys.exc_info()[1]
  55. if isinstance(value, socket.error):
  56. err = value.args[0]
  57. if sys.platform in ('win32', 'cygwin'):
  58. # "An established connection was aborted by the software in your host."
  59. pipe_err = 10053
  60. else:
  61. pipe_err = errno.EPIPE
  62. if err == pipe_err:
  63. print("testserver.py: Broken pipe")
  64. return
  65. if err == errno.ECONNRESET:
  66. print("testserver.py: Connection reset by peer")
  67. return
  68. SocketServer.BaseServer.handle_error(self, request, client_address)
  69. class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
  70. """This is a specialization of BaseHTTPServer to allow it
  71. to be exited cleanly (by setting its "stop" member to True)."""
  72. def serve_forever(self):
  73. self.stop = False
  74. self.nonce_time = None
  75. while not self.stop:
  76. self.handle_request()
  77. self.socket.close()
  78. def MultiplexerHack(std_fd, log_fd):
  79. """Creates a FileMultiplexer that will write to both specified files.
  80. When running on Windows XP bots, stdout and stderr will be invalid file
  81. handles, so log_fd will be returned directly. (This does not occur if you
  82. run the test suite directly from a console, but only if the output of the
  83. test executable is redirected.)
  84. """
  85. if std_fd.fileno() <= 0:
  86. return log_fd
  87. return FileMultiplexer(std_fd, log_fd)
  88. class BasePageHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  89. def __init__(self, request, client_address, socket_server,
  90. connect_handlers, get_handlers, head_handlers, post_handlers,
  91. put_handlers):
  92. self._connect_handlers = connect_handlers
  93. self._get_handlers = get_handlers
  94. self._head_handlers = head_handlers
  95. self._post_handlers = post_handlers
  96. self._put_handlers = put_handlers
  97. BaseHTTPServer.BaseHTTPRequestHandler.__init__(
  98. self, request, client_address, socket_server)
  99. def log_request(self, *args, **kwargs):
  100. # Disable request logging to declutter test log output.
  101. pass
  102. def _ShouldHandleRequest(self, handler_name):
  103. """Determines if the path can be handled by the handler.
  104. We consider a handler valid if the path begins with the
  105. handler name. It can optionally be followed by "?*", "/*".
  106. """
  107. pattern = re.compile('%s($|\?|/).*' % handler_name)
  108. return pattern.match(self.path)
  109. def do_CONNECT(self):
  110. for handler in self._connect_handlers:
  111. if handler():
  112. return
  113. def do_GET(self):
  114. for handler in self._get_handlers:
  115. if handler():
  116. return
  117. def do_HEAD(self):
  118. for handler in self._head_handlers:
  119. if handler():
  120. return
  121. def do_POST(self):
  122. for handler in self._post_handlers:
  123. if handler():
  124. return
  125. def do_PUT(self):
  126. for handler in self._put_handlers:
  127. if handler():
  128. return
  129. class TestServerRunner(object):
  130. """Runs a test server and communicates with the controlling C++ test code.
  131. Subclasses should override the create_server method to create their server
  132. object, and the add_options method to add their own options.
  133. """
  134. def __init__(self):
  135. self.option_parser = optparse.OptionParser()
  136. self.add_options()
  137. def main(self):
  138. self.options, self.args = self.option_parser.parse_args()
  139. logfile = open(self.options.log_file, 'w')
  140. # http://crbug.com/248796 : Error logs streamed to normal sys.stderr will be
  141. # written to HTTP response payload when remote test server is used.
  142. # For this reason, some tests like ResourceFetcherTests.ResourceFetcher404
  143. # were failing on Android because remote test server is being used there.
  144. # To fix them, we need to use sys.stdout as sys.stderr if remote test server
  145. # is used.
  146. if self.options.on_remote_server:
  147. sys.stderr = sys.stdout
  148. sys.stderr = MultiplexerHack(sys.stderr, logfile)
  149. if self.options.log_to_console:
  150. sys.stdout = MultiplexerHack(sys.stdout, logfile)
  151. else:
  152. sys.stdout = logfile
  153. server_data = {
  154. 'host': self.options.host,
  155. }
  156. self.server = self.create_server(server_data)
  157. self._notify_startup_complete(server_data)
  158. self.run_server()
  159. def create_server(self, server_data):
  160. """Creates a server object and returns it.
  161. Must populate server_data['port'], and can set additional server_data
  162. elements if desired."""
  163. raise NotImplementedError()
  164. def run_server(self):
  165. try:
  166. self.server.serve_forever()
  167. except KeyboardInterrupt:
  168. print('shutting down server')
  169. self.server.stop = True
  170. def add_options(self):
  171. self.option_parser.add_option('--startup-pipe', type='int',
  172. dest='startup_pipe',
  173. help='File handle of pipe to parent process')
  174. self.option_parser.add_option('--log-to-console', action='store_const',
  175. const=True, default=False,
  176. dest='log_to_console',
  177. help='Enables or disables sys.stdout logging '
  178. 'to the console.')
  179. self.option_parser.add_option('--log-file', default='testserver.log',
  180. dest='log_file',
  181. help='The name of the server log file.')
  182. self.option_parser.add_option('--port', default=0, type='int',
  183. help='Port used by the server. If '
  184. 'unspecified, the server will listen on an '
  185. 'ephemeral port.')
  186. self.option_parser.add_option('--host', default='127.0.0.1',
  187. dest='host',
  188. help='Hostname or IP upon which the server '
  189. 'will listen. Client connections will also '
  190. 'only be allowed from this address.')
  191. self.option_parser.add_option('--data-dir', dest='data_dir',
  192. help='Directory from which to read the '
  193. 'files.')
  194. self.option_parser.add_option('--on-remote-server', action='store_const',
  195. const=True, default=False,
  196. dest='on_remote_server',
  197. help='Whether remote server is being used or '
  198. 'not.')
  199. def _notify_startup_complete(self, server_data):
  200. # Notify the parent that we've started. (BaseServer subclasses
  201. # bind their sockets on construction.)
  202. if self.options.startup_pipe is not None:
  203. server_data_json = json.dumps(server_data).encode()
  204. server_data_len = len(server_data_json)
  205. print('sending server_data: %s (%d bytes)' %
  206. (server_data_json, server_data_len))
  207. if sys.platform == 'win32':
  208. fd = msvcrt.open_osfhandle(self.options.startup_pipe, 0)
  209. else:
  210. fd = self.options.startup_pipe
  211. startup_pipe = os.fdopen(fd, "wb")
  212. # First write the data length as an unsigned 4-byte value. This
  213. # is _not_ using network byte ordering since the other end of the
  214. # pipe is on the same machine.
  215. startup_pipe.write(struct.pack('=L', server_data_len))
  216. startup_pipe.write(server_data_json)
  217. startup_pipe.close()