http_server_base.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # Copyright (C) 2011 Google Inc. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are
  5. # met:
  6. #
  7. # * Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # * Redistributions in binary form must reproduce the above
  10. # copyright notice, this list of conditions and the following disclaimer
  11. # in the documentation and/or other materials provided with the
  12. # distribution.
  13. # * Neither the name of Google Inc. nor the names of its
  14. # contributors may be used to endorse or promote products derived from
  15. # this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. """Base class with common routines between the Apache, Lighttpd, and websocket servers."""
  29. import errno
  30. import logging
  31. import socket
  32. import sys
  33. import tempfile
  34. import time
  35. _log = logging.getLogger(__name__)
  36. class ServerError(Exception):
  37. pass
  38. class HttpServerBase(object):
  39. """A skeleton class for starting and stopping servers used by the layout tests."""
  40. def __init__(self, port_obj, number_of_servers=None):
  41. self._executive = port_obj._executive
  42. self._filesystem = port_obj._filesystem
  43. self._name = '<virtual>'
  44. self._mappings = {}
  45. self._pid = None
  46. self._pid_file = None
  47. self._port_obj = port_obj
  48. self._number_of_servers = number_of_servers
  49. # We need a non-checkout-dependent place to put lock files, etc. We
  50. # don't use the Python default on the Mac because it defaults to a
  51. # randomly-generated directory under /var/folders and no one would ever
  52. # look there.
  53. tmpdir = tempfile.gettempdir()
  54. if port_obj.host.platform.is_mac():
  55. tmpdir = '/tmp'
  56. self._runtime_path = self._filesystem.join(tmpdir, "WebKit")
  57. self._filesystem.maybe_make_directory(self._runtime_path)
  58. def start(self):
  59. """Starts the server. It is an error to start an already started server.
  60. This method also stops any stale servers started by a previous instance."""
  61. assert not self._pid, '%s server is already running' % self._name
  62. # Stop any stale servers left over from previous instances.
  63. if self._filesystem.exists(self._pid_file):
  64. try:
  65. self._pid = int(self._filesystem.read_text_file(self._pid_file))
  66. self._stop_running_server()
  67. except (ValueError, UnicodeDecodeError):
  68. # These could be raised if the pid file is corrupt.
  69. self._remove_pid_file()
  70. self._pid = None
  71. self._remove_stale_logs()
  72. self._prepare_config()
  73. self._check_that_all_ports_are_available()
  74. self._pid = self._spawn_process()
  75. if self._wait_for_action(self._is_server_running_on_all_ports):
  76. _log.debug("%s successfully started (pid = %d)" % (self._name, self._pid))
  77. else:
  78. self._stop_running_server()
  79. raise ServerError('Failed to start %s server' % self._name)
  80. def stop(self):
  81. """Stops the server. Stopping a server that isn't started is harmless."""
  82. actual_pid = None
  83. try:
  84. if self._filesystem.exists(self._pid_file):
  85. try:
  86. actual_pid = int(self._filesystem.read_text_file(self._pid_file))
  87. except (ValueError, UnicodeDecodeError):
  88. # These could be raised if the pid file is corrupt.
  89. pass
  90. if not self._pid:
  91. self._pid = actual_pid
  92. if not self._pid:
  93. return
  94. if not actual_pid:
  95. _log.warning('Failed to stop %s: pid file is missing' % self._name)
  96. return
  97. if self._pid != actual_pid:
  98. _log.warning('Failed to stop %s: pid file contains %d, not %d' %
  99. (self._name, actual_pid, self._pid))
  100. # Try to kill the existing pid, anyway, in case it got orphaned.
  101. self._executive.kill_process(self._pid)
  102. self._pid = None
  103. return
  104. _log.debug("Attempting to shut down %s server at pid %d" % (self._name, self._pid))
  105. self._stop_running_server()
  106. _log.debug("%s server at pid %d stopped" % (self._name, self._pid))
  107. self._pid = None
  108. finally:
  109. # Make sure we delete the pid file no matter what happens.
  110. self._remove_pid_file()
  111. def _prepare_config(self):
  112. """This routine can be overridden by subclasses to do any sort
  113. of initialization required prior to starting the server that may fail."""
  114. pass
  115. def _remove_stale_logs(self):
  116. """This routine can be overridden by subclasses to try and remove logs
  117. left over from a prior run. This routine should log warnings if the
  118. files cannot be deleted, but should not fail unless failure to
  119. delete the logs will actually cause start() to fail."""
  120. pass
  121. def _spawn_process(self):
  122. """This routine must be implemented by subclasses to actually start the server.
  123. This routine returns the pid of the started process, and also ensures that that
  124. pid has been written to self._pid_file."""
  125. raise NotImplementedError()
  126. def _stop_running_server(self):
  127. """This routine must be implemented by subclasses to actually stop the running server listed in self._pid_file."""
  128. raise NotImplementedError()
  129. # Utility routines.
  130. def _remove_pid_file(self):
  131. if self._filesystem.exists(self._pid_file):
  132. self._filesystem.remove(self._pid_file)
  133. def _remove_log_files(self, folder, starts_with):
  134. files = self._filesystem.listdir(folder)
  135. for file in files:
  136. if file.startswith(starts_with):
  137. full_path = self._filesystem.join(folder, file)
  138. self._filesystem.remove(full_path)
  139. def _wait_for_action(self, action, wait_secs=20.0, sleep_secs=1.0):
  140. """Repeat the action for wait_sec or until it succeeds, sleeping for sleep_secs
  141. in between each attempt. Returns whether it succeeded."""
  142. start_time = time.time()
  143. while time.time() - start_time < wait_secs:
  144. if action():
  145. return True
  146. _log.debug("Waiting for action: %s" % action)
  147. time.sleep(sleep_secs)
  148. return False
  149. def _is_server_running_on_all_ports(self):
  150. """Returns whether the server is running on all the desired ports."""
  151. if not self._executive.check_running_pid(self._pid):
  152. _log.debug("Server isn't running at all")
  153. raise ServerError("Server exited")
  154. for mapping in self._mappings:
  155. s = socket.socket()
  156. port = mapping['port']
  157. try:
  158. s.connect(('localhost', port))
  159. _log.debug("Server running on %d" % port)
  160. except IOError, e:
  161. if e.errno not in (errno.ECONNREFUSED, errno.ECONNRESET):
  162. raise
  163. _log.debug("Server NOT running on %d: %s" % (port, e))
  164. return False
  165. finally:
  166. s.close()
  167. return True
  168. def _check_that_all_ports_are_available(self):
  169. for mapping in self._mappings:
  170. s = socket.socket()
  171. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  172. port = mapping['port']
  173. try:
  174. s.bind(('localhost', port))
  175. except IOError, e:
  176. if e.errno in (errno.EALREADY, errno.EADDRINUSE):
  177. raise ServerError('Port %d is already in use.' % port)
  178. elif sys.platform == 'win32' and e.errno in (errno.WSAEACCES,): # pylint: disable=E1101
  179. raise ServerError('Port %d is already in use.' % port)
  180. else:
  181. raise
  182. finally:
  183. s.close()