websocket_server.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 help start/stop the PyWebSocket server used by layout tests."""
  29. import logging
  30. import os
  31. import sys
  32. import time
  33. from webkitpy.layout_tests.servers import http_server
  34. from webkitpy.layout_tests.servers import http_server_base
  35. _log = logging.getLogger(__name__)
  36. _WS_LOG_PREFIX = 'pywebsocket.ws.log-'
  37. _WSS_LOG_PREFIX = 'pywebsocket.wss.log-'
  38. _DEFAULT_WS_PORT = 8880
  39. _DEFAULT_WSS_PORT = 9323
  40. class PyWebSocket(http_server.Lighttpd):
  41. def __init__(self, port_obj, output_dir, port=_DEFAULT_WS_PORT,
  42. root=None, use_tls=False,
  43. private_key=None, certificate=None, ca_certificate=None,
  44. pidfile=None):
  45. """Args:
  46. output_dir: the absolute path to the layout test result directory
  47. """
  48. http_server.Lighttpd.__init__(self, port_obj, output_dir,
  49. port=_DEFAULT_WS_PORT,
  50. root=root)
  51. self._output_dir = output_dir
  52. self._pid_file = pidfile
  53. self._process = None
  54. self._port = port
  55. self._root = root
  56. self._use_tls = use_tls
  57. self._name = 'pywebsocket'
  58. if self._use_tls:
  59. self._name = 'pywebsocket_secure'
  60. if private_key:
  61. self._private_key = private_key
  62. else:
  63. self._private_key = self._pem_file
  64. if certificate:
  65. self._certificate = certificate
  66. else:
  67. self._certificate = self._pem_file
  68. self._ca_certificate = ca_certificate
  69. if self._port:
  70. self._port = int(self._port)
  71. self._wsin = None
  72. self._wsout = None
  73. self._mappings = [{'port': self._port}]
  74. if not self._pid_file:
  75. self._pid_file = self._filesystem.join(self._runtime_path, '%s.pid' % self._name)
  76. # Webkit tests
  77. # FIXME: This is the wrong way to detect if we're in Chrome vs. WebKit!
  78. # The port objects are supposed to abstract this.
  79. if self._root:
  80. self._layout_tests = self._filesystem.abspath(self._root)
  81. self._web_socket_tests = self._filesystem.abspath(self._filesystem.join(self._root, 'http', 'tests', 'websocket', 'tests'))
  82. else:
  83. try:
  84. self._layout_tests = self._port_obj.layout_tests_dir()
  85. self._web_socket_tests = self._filesystem.join(self._layout_tests, 'http', 'tests', 'websocket', 'tests')
  86. except:
  87. self._web_socket_tests = None
  88. if self._use_tls:
  89. self._log_prefix = _WSS_LOG_PREFIX
  90. else:
  91. self._log_prefix = _WS_LOG_PREFIX
  92. def _prepare_config(self):
  93. time_str = time.strftime('%d%b%Y-%H%M%S')
  94. log_file_name = self._log_prefix + time_str
  95. # FIXME: Doesn't Executive have a devnull, so that we don't have to use os.devnull directly?
  96. self._wsin = open(os.devnull, 'r')
  97. error_log = self._filesystem.join(self._output_dir, log_file_name + "-err.txt")
  98. output_log = self._filesystem.join(self._output_dir, log_file_name + "-out.txt")
  99. self._wsout = self._filesystem.open_text_file_for_writing(output_log)
  100. from webkitpy.thirdparty import mod_pywebsocket
  101. python_interp = sys.executable
  102. # FIXME: Use self._filesystem.path_to_module(self.__module__) instead of __file__
  103. # I think this is trying to get the chrome directory? Doesn't the port object know that?
  104. pywebsocket_base = self._filesystem.join(self._filesystem.dirname(self._filesystem.dirname(self._filesystem.dirname(self._filesystem.abspath(__file__)))), 'thirdparty')
  105. pywebsocket_script = self._filesystem.join(pywebsocket_base, 'mod_pywebsocket', 'standalone.py')
  106. start_cmd = [
  107. python_interp, '-u', pywebsocket_script,
  108. '--server-host', 'localhost',
  109. '--port', str(self._port),
  110. # FIXME: Don't we have a self._port_obj.layout_test_path?
  111. '--document-root', self._filesystem.join(self._layout_tests, 'http', 'tests'),
  112. '--scan-dir', self._web_socket_tests,
  113. '--cgi-paths', '/websocket/tests',
  114. '--log-file', error_log,
  115. ]
  116. handler_map_file = self._filesystem.join(self._web_socket_tests, 'handler_map.txt')
  117. if self._filesystem.exists(handler_map_file):
  118. _log.debug('Using handler_map_file: %s' % handler_map_file)
  119. start_cmd.append('--websock-handlers-map-file')
  120. start_cmd.append(handler_map_file)
  121. else:
  122. _log.warning('No handler_map_file found')
  123. if self._use_tls:
  124. start_cmd.extend(['-t', '-k', self._private_key,
  125. '-c', self._certificate])
  126. if self._ca_certificate:
  127. start_cmd.append('--ca-certificate')
  128. start_cmd.append(self._ca_certificate)
  129. self._start_cmd = start_cmd
  130. server_name = self._filesystem.basename(pywebsocket_script)
  131. self._env = self._port_obj.setup_environ_for_server(server_name)
  132. self._env['PYTHONPATH'] = (pywebsocket_base + os.path.pathsep + self._env.get('PYTHONPATH', ''))
  133. def _remove_stale_logs(self):
  134. try:
  135. self._remove_log_files(self._output_dir, self._log_prefix)
  136. except OSError, e:
  137. _log.warning('Failed to remove stale %s log files: %s' % (self._name, str(e)))
  138. def _spawn_process(self):
  139. _log.debug('Starting %s server, cmd="%s"' % (self._name, self._start_cmd))
  140. self._process = self._executive.popen(self._start_cmd, env=self._env, shell=False, stdin=self._wsin, stdout=self._wsout, stderr=self._executive.STDOUT)
  141. self._filesystem.write_text_file(self._pid_file, str(self._process.pid))
  142. return self._process.pid
  143. def _stop_running_server(self):
  144. super(PyWebSocket, self)._stop_running_server()
  145. if self._wsin:
  146. self._wsin.close()
  147. self._wsin = None
  148. if self._wsout:
  149. self._wsout.close()
  150. self._wsout = None