apache_http_server.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. """A class to start/stop the apache http server used by layout tests."""
  29. import logging
  30. import os
  31. import re
  32. import socket
  33. import sys
  34. from webkitpy.layout_tests.servers import http_server_base
  35. _log = logging.getLogger(__name__)
  36. class LayoutTestApacheHttpd(http_server_base.HttpServerBase):
  37. def __init__(self, port_obj, output_dir, additional_dirs=None, number_of_servers=None):
  38. """Args:
  39. port_obj: handle to the platform-specific routines
  40. output_dir: the absolute path to the layout test result directory
  41. """
  42. http_server_base.HttpServerBase.__init__(self, port_obj, number_of_servers)
  43. # We use the name "httpd" instead of "apache" to make our paths (e.g. the pid file: /tmp/WebKit/httpd.pid)
  44. # match old-run-webkit-tests: https://bugs.webkit.org/show_bug.cgi?id=63956
  45. self._name = 'httpd'
  46. self._mappings = [{'port': 8000},
  47. {'port': 8080},
  48. {'port': 8443, 'sslcert': True}]
  49. self._output_dir = output_dir
  50. self._filesystem.maybe_make_directory(output_dir)
  51. self._pid_file = self._filesystem.join(self._runtime_path, '%s.pid' % self._name)
  52. test_dir = self._port_obj.layout_tests_dir()
  53. js_test_resources_dir = self._filesystem.join(test_dir, "fast", "js", "resources")
  54. media_resources_dir = self._filesystem.join(test_dir, "media")
  55. mime_types_path = self._filesystem.join(test_dir, "http", "conf", "mime.types")
  56. cert_file = self._filesystem.join(test_dir, "http", "conf", "webkit-httpd.pem")
  57. access_log = self._filesystem.join(output_dir, "access_log.txt")
  58. error_log = self._filesystem.join(output_dir, "error_log.txt")
  59. document_root = self._filesystem.join(test_dir, "http", "tests")
  60. # FIXME: We shouldn't be calling a protected method of _port_obj!
  61. executable = self._port_obj._path_to_apache()
  62. start_cmd = [executable,
  63. '-f', "\"%s\"" % self._get_apache_config_file_path(test_dir, output_dir),
  64. '-C', "\'DocumentRoot \"%s\"\'" % document_root,
  65. '-c', "\'Alias /js-test-resources \"%s\"'" % js_test_resources_dir,
  66. '-c', "\'Alias /media-resources \"%s\"'" % media_resources_dir,
  67. '-c', "\'TypesConfig \"%s\"\'" % mime_types_path,
  68. '-c', "\'CustomLog \"%s\" common\'" % access_log,
  69. '-c', "\'ErrorLog \"%s\"\'" % error_log,
  70. '-C', "\'User \"%s\"\'" % os.environ.get("USERNAME", os.environ.get("USER", "")),
  71. '-c', "\'PidFile %s'" % self._pid_file,
  72. '-k', "start"]
  73. enable_ipv6 = self._port_obj.http_server_supports_ipv6()
  74. # Perform part of the checks Apache's APR does when trying to listen to
  75. # a specific host/port. This allows us to avoid trying to listen to
  76. # IPV6 addresses when it fails on Apache. APR itself tries to call
  77. # getaddrinfo() again without AI_ADDRCONFIG if the first call fails
  78. # with EBADFLAGS, but that is not how it normally fails in our use
  79. # cases, so ignore that for now.
  80. # See https://bugs.webkit.org/show_bug.cgi?id=98602#c7
  81. try:
  82. socket.getaddrinfo('::1', 0, 0, 0, 0, socket.AI_ADDRCONFIG)
  83. except:
  84. enable_ipv6 = False
  85. for mapping in self._mappings:
  86. port = mapping['port']
  87. start_cmd += ['-C', "\'Listen 127.0.0.1:%d\'" % port]
  88. # We listen to both IPv4 and IPv6 loop-back addresses, but ignore
  89. # requests to 8000 from random users on network.
  90. # See https://bugs.webkit.org/show_bug.cgi?id=37104
  91. if enable_ipv6:
  92. start_cmd += ['-C', "\'Listen [::1]:%d\'" % port]
  93. if additional_dirs:
  94. for alias, path in additional_dirs.iteritems():
  95. start_cmd += ['-c', "\'Alias %s \"%s\"\'" % (alias, path),
  96. # Disable CGI handler for additional dirs.
  97. '-c', "\'<Location %s>\'" % alias,
  98. '-c', "\'RemoveHandler .cgi .pl\'",
  99. '-c', "\'</Location>\'"]
  100. if self._number_of_servers:
  101. start_cmd += ['-c', "\'StartServers %d\'" % self._number_of_servers,
  102. '-c', "\'MinSpareServers %d\'" % self._number_of_servers,
  103. '-c', "\'MaxSpareServers %d\'" % self._number_of_servers]
  104. stop_cmd = [executable,
  105. '-f', "\"%s\"" % self._get_apache_config_file_path(test_dir, output_dir),
  106. '-c', "\'PidFile %s'" % self._pid_file,
  107. '-k', "stop"]
  108. start_cmd.extend(['-c', "\'SSLCertificateFile %s\'" % cert_file])
  109. # Join the string here so that Cygwin/Windows and Mac/Linux
  110. # can use the same code. Otherwise, we could remove the single
  111. # quotes above and keep cmd as a sequence.
  112. # FIXME: It's unclear if this is still needed.
  113. self._start_cmd = " ".join(start_cmd)
  114. self._stop_cmd = " ".join(stop_cmd)
  115. def _get_apache_config_file_path(self, test_dir, output_dir):
  116. """Returns the path to the apache config file to use.
  117. Args:
  118. test_dir: absolute path to the LayoutTests directory.
  119. output_dir: absolute path to the layout test results directory.
  120. """
  121. httpd_config = self._port_obj._path_to_apache_config_file()
  122. httpd_config_copy = os.path.join(output_dir, "httpd.conf")
  123. httpd_conf = self._filesystem.read_text_file(httpd_config)
  124. # FIXME: Why do we need to copy the config file since we're not modifying it?
  125. self._filesystem.write_text_file(httpd_config_copy, httpd_conf)
  126. return httpd_config_copy
  127. def _spawn_process(self):
  128. _log.debug('Starting %s server, cmd="%s"' % (self._name, str(self._start_cmd)))
  129. retval, err = self._run(self._start_cmd)
  130. if retval or len(err):
  131. raise http_server_base.ServerError('Failed to start %s: %s' % (self._name, err))
  132. # For some reason apache isn't guaranteed to have created the pid file before
  133. # the process exits, so we wait a little while longer.
  134. if not self._wait_for_action(lambda: self._filesystem.exists(self._pid_file)):
  135. raise http_server_base.ServerError('Failed to start %s: no pid file found' % self._name)
  136. return int(self._filesystem.read_text_file(self._pid_file))
  137. def _stop_running_server(self):
  138. # If apache was forcefully killed, the pid file will not have been deleted, so check
  139. # that the process specified by the pid_file no longer exists before deleting the file.
  140. if self._pid and not self._executive.check_running_pid(self._pid):
  141. self._filesystem.remove(self._pid_file)
  142. return
  143. retval, err = self._run(self._stop_cmd)
  144. if retval or len(err):
  145. raise http_server_base.ServerError('Failed to stop %s: %s' % (self._name, err))
  146. # For some reason apache isn't guaranteed to have actually stopped after
  147. # the stop command returns, so we wait a little while longer for the
  148. # pid file to be removed.
  149. if not self._wait_for_action(lambda: not self._filesystem.exists(self._pid_file)):
  150. raise http_server_base.ServerError('Failed to stop %s: pid file still exists' % self._name)
  151. def _run(self, cmd):
  152. # Use shell=True because we join the arguments into a string for
  153. # the sake of Window/Cygwin and it needs quoting that breaks
  154. # shell=False.
  155. # FIXME: We should not need to be joining shell arguments into strings.
  156. # shell=True is a trail of tears.
  157. # Note: Not thread safe: http://bugs.python.org/issue2320
  158. process = self._executive.popen(cmd, shell=True, stderr=self._executive.PIPE)
  159. process.wait()
  160. retval = process.returncode
  161. err = process.stderr.read()
  162. return (retval, err)