REGRESSION (r217572): run-webkit-tests exits without emitting newline character
[WebKit.git] / Tools / Scripts / webkitpy / layout_tests / servers / websocket_server.py
1 # Copyright (C) 2011 Google Inc. All rights reserved.
2 # Copyright (C) 2016 Apple Inc. All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met:
7 #
8 #     * Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 #     * Redistributions in binary form must reproduce the above
11 # copyright notice, this list of conditions and the following disclaimer
12 # in the documentation and/or other materials provided with the
13 # distribution.
14 #     * Neither the name of Google Inc. nor the names of its
15 # contributors may be used to endorse or promote products derived from
16 # this software without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 """A class to help start/stop the PyWebSocket server used by layout tests."""
31
32 import logging
33 import os
34 import sys
35 import time
36
37 from webkitpy.layout_tests.servers import http_server, http_server_base
38
39 _log = logging.getLogger(__name__)
40
41
42 _WS_LOG_NAME = 'pywebsocket.ws.log'
43 _WSS_LOG_NAME = 'pywebsocket.wss.log'
44
45
46 class PyWebSocket(http_server.Lighttpd):
47     DEFAULT_WS_PORT = 8880
48     DEFAULT_WSS_PORT = 9323
49
50     def __init__(self, port_obj, output_dir, port=DEFAULT_WS_PORT,
51                  root=None, use_tls=False,
52                  private_key=None, certificate=None, ca_certificate=None,
53                  pidfile=None):
54         """Args:
55           output_dir: the absolute path to the layout test result directory
56         """
57         http_server.Lighttpd.__init__(self, port_obj, output_dir,
58                                       port=port,
59                                       root=root)
60         self._output_dir = output_dir
61         self._pid_file = pidfile
62         self._process = None
63
64         self._port = port
65         self._root = root
66         self._use_tls = use_tls
67
68         self._name = 'pywebsocket'
69         if self._use_tls:
70             self._name = 'pywebsocket_secure'
71
72         if private_key:
73             self._private_key = private_key
74         else:
75             self._private_key = self._pem_file
76         if certificate:
77             self._certificate = certificate
78         else:
79             self._certificate = self._pem_file
80         self._ca_certificate = ca_certificate
81         if self._port:
82             self._port = int(self._port)
83         self._wsin = None
84         self._wsout = None
85         self._mappings = [{'port': self._port}]
86
87         if not self._pid_file:
88             self._pid_file = self._filesystem.join(self._runtime_path, '%s.pid' % self._name)
89
90         # Webkit tests
91         # FIXME: This is the wrong way to detect if we're in Chrome vs. WebKit!
92         # The port objects are supposed to abstract this.
93         if self._root:
94             self._layout_tests = self._filesystem.abspath(self._root)
95             self._web_socket_tests = self._filesystem.abspath(self._filesystem.join(self._root, 'http', 'tests', 'websocket', 'tests'))
96         else:
97             try:
98                 self._layout_tests = self._port_obj.layout_tests_dir()
99                 self._web_socket_tests = self._filesystem.join(self._layout_tests, 'http', 'tests', 'websocket', 'tests')
100             except:
101                 self._web_socket_tests = None
102
103         if self._use_tls:
104             self._log_prefix = _WSS_LOG_NAME
105         else:
106             self._log_prefix = _WS_LOG_NAME
107
108     def ports_to_forward(self):
109         return [self._port]
110
111     def _prepare_config(self):
112         log_file_name = self._log_prefix
113         # FIXME: Doesn't Executive have a devnull, so that we don't have to use os.devnull directly?
114         self._wsin = open(os.devnull, 'r')
115
116         error_log = self._filesystem.join(self._output_dir, log_file_name + "-err.txt")
117         output_log = self._filesystem.join(self._output_dir, log_file_name + "-out.txt")
118         self._wsout = self._filesystem.open_text_file_for_writing(output_log)
119
120         from webkitpy.thirdparty import mod_pywebsocket
121         python_interp = sys.executable
122         # FIXME: Use self._filesystem.path_to_module(self.__module__) instead of __file__
123         # I think this is trying to get the chrome directory?  Doesn't the port object know that?
124         pywebsocket_base = self._filesystem.join(self._filesystem.dirname(self._filesystem.dirname(self._filesystem.dirname(self._filesystem.abspath(__file__)))), 'thirdparty')
125         pywebsocket_script = self._filesystem.join(pywebsocket_base, 'mod_pywebsocket', 'standalone.py')
126         start_cmd = [
127             python_interp, '-u', pywebsocket_script,
128             '--server-host', 'localhost',
129             '--port', str(self._port),
130             # FIXME: Don't we have a self._port_obj.layout_test_path?
131             '--document-root', self._filesystem.join(self._layout_tests, 'http', 'tests'),
132             '--scan-dir', self._web_socket_tests,
133             '--cgi-paths', '/websocket/tests',
134             '--log-file', error_log,
135         ]
136
137         handler_map_file = self._filesystem.join(self._web_socket_tests, 'handler_map.txt')
138         if self._filesystem.exists(handler_map_file):
139             _log.debug('Using handler_map_file: %s' % handler_map_file)
140             start_cmd.append('--websock-handlers-map-file')
141             start_cmd.append(handler_map_file)
142         else:
143             _log.warning('No handler_map_file found')
144
145         if self._use_tls:
146             start_cmd.extend(['-t', '-k', self._private_key,
147                               '-c', self._certificate])
148             if self._ca_certificate:
149                 start_cmd.append('--tls-client-ca')
150                 start_cmd.append(self._ca_certificate)
151
152         self._start_cmd = start_cmd
153         server_name = self._filesystem.basename(pywebsocket_script)
154         self._env = self._port_obj.setup_environ_for_server(server_name)
155         self._env['PYTHONPATH'] = (pywebsocket_base + os.path.pathsep + self._env.get('PYTHONPATH', ''))
156
157     def _remove_stale_logs(self):
158         try:
159             self._remove_log_files(self._output_dir, self._log_prefix)
160         except OSError as e:
161             _log.warning('Failed to remove stale %s log files: %s' % (self._name, str(e)))
162
163     def _spawn_process(self):
164         _log.debug('Starting %s server, cmd="%s"' % (self._name, self._start_cmd))
165         self._process = self._executive.popen(self._start_cmd, env=self._env, shell=False, stdin=self._wsin, stdout=self._wsout, stderr=self._executive.STDOUT)
166         self._filesystem.write_text_file(self._pid_file, str(self._process.pid))
167         return self._process.pid
168
169     def _stop_running_server(self):
170         super(PyWebSocket, self)._stop_running_server()
171
172         if self._wsin:
173             self._wsin.close()
174             self._wsin = None
175         if self._wsout:
176             self._wsout.close()
177             self._wsout = None
178
179
180 def is_web_socket_server_running():
181     return http_server_base.HttpServerBase._is_running_on_port(PyWebSocket.DEFAULT_WS_PORT)