2011-07-06 Adam Barth <abarth@webkit.org>
[WebKit-https.git] / Tools / Scripts / webkitpy / layout_tests / servers / websocket_server.py
1 #!/usr/bin/env python
2 # Copyright (C) 2011 Google 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
38 from webkitpy.layout_tests.servers import http_server_base
39
40 _log = logging.getLogger(__name__)
41
42
43 _WS_LOG_PREFIX = 'pywebsocket.ws.log-'
44 _WSS_LOG_PREFIX = 'pywebsocket.wss.log-'
45
46
47 _DEFAULT_WS_PORT = 8880
48 _DEFAULT_WSS_PORT = 9323
49
50
51 class PyWebSocket(http_server.Lighttpd):
52     def __init__(self, port_obj, output_dir, port=_DEFAULT_WS_PORT,
53                  root=None, use_tls=False,
54                  pidfile=None):
55         """Args:
56           output_dir: the absolute path to the layout test result directory
57         """
58         http_server.Lighttpd.__init__(self, port_obj, output_dir,
59                                       port=_DEFAULT_WS_PORT,
60                                       root=root)
61         self._output_dir = output_dir
62         self._pid_file = pidfile
63         self._process = None
64
65         self._port = port
66         self._root = root
67         self._use_tls = use_tls
68
69         self._name = 'pywebsocket'
70         if self._use_tls:
71             self._name = 'pywebsocket_secure'
72
73         self._private_key = self._pem_file
74         self._certificate = self._pem_file
75         if self._port:
76             self._port = int(self._port)
77         self._wsin = None
78         self._wsout = None
79         self._mappings = [{'port': self._port}]
80
81         if not self._pid_file:
82             self._pid_file = self._filesystem.join(self._runtime_path, '%s.pid' % self._name)
83
84         # Webkit tests
85         if self._root:
86             self._layout_tests = os.path.abspath(self._root)
87             self._web_socket_tests = os.path.abspath(
88                 os.path.join(self._root, 'http', 'tests',
89                              'websocket', 'tests'))
90         else:
91             try:
92                 self._layout_tests = self._port_obj.layout_tests_dir()
93                 self._web_socket_tests = os.path.join(self._layout_tests,
94                      'http', 'tests', 'websocket', 'tests')
95             except:
96                 self._web_socket_tests = None
97
98         if self._use_tls:
99             self._log_prefix = _WSS_LOG_PREFIX
100         else:
101             self._log_prefix = _WS_LOG_PREFIX
102
103     def _prepare_config(self):
104         time_str = time.strftime('%d%b%Y-%H%M%S')
105         log_file_name = self._log_prefix + time_str
106         self._wsin = open(os.devnull, 'r')
107
108         error_log = os.path.join(self._output_dir, log_file_name + "-err.txt")
109
110         output_log = os.path.join(self._output_dir, log_file_name + "-out.txt")
111         self._wsout = self._filesystem.open_text_file_for_writing(output_log)
112
113         from webkitpy.thirdparty.autoinstalled.pywebsocket import mod_pywebsocket
114         python_interp = sys.executable
115         pywebsocket_base = os.path.join(
116             os.path.dirname(os.path.dirname(os.path.dirname(
117             os.path.abspath(__file__)))), 'thirdparty',
118             'autoinstalled', 'pywebsocket')
119         pywebsocket_script = os.path.join(pywebsocket_base, 'mod_pywebsocket',
120             'standalone.py')
121         start_cmd = [
122             python_interp, '-u', pywebsocket_script,
123             '--server-host', '127.0.0.1',
124             '--port', str(self._port),
125             '--document-root', os.path.join(self._layout_tests, 'http', 'tests'),
126             '--scan-dir', self._web_socket_tests,
127             '--cgi-paths', '/websocket/tests',
128             '--log-file', error_log,
129         ]
130
131         handler_map_file = os.path.join(self._web_socket_tests,
132                                         'handler_map.txt')
133         if os.path.exists(handler_map_file):
134             _log.debug('Using handler_map_file: %s' % handler_map_file)
135             start_cmd.append('--websock-handlers-map-file')
136             start_cmd.append(handler_map_file)
137         else:
138             _log.warning('No handler_map_file found')
139
140         if self._use_tls:
141             start_cmd.extend(['-t', '-k', self._private_key,
142                               '-c', self._certificate])
143
144         self._start_cmd = start_cmd
145         self._env = self._port_obj.setup_environ_for_server()
146         self._env['PYTHONPATH'] = (pywebsocket_base + os.path.pathsep + self._env.get('PYTHONPATH', ''))
147
148     def _remove_stale_logs(self):
149         try:
150             self._remove_log_files(self._output_dir, self._log_prefix)
151         except OSError, e:
152             _log.warning('Failed to remove stale %s log files: %s' % (self._name, str(e)))
153
154     def _spawn_process(self):
155         _log.debug('Starting %s server, cmd="%s"' % (self._name, self._start_cmd))
156         self._process = self._executive.popen(self._start_cmd, env=self._env, shell=False, stdin=self._wsin, stdout=self._wsout, stderr=self._executive.STDOUT)
157         self._filesystem.write_text_file(self._pid_file, str(self._process.pid))
158         return self._process.pid
159
160     def _stop_running_server(self):
161         super(PyWebSocket, self)._stop_running_server()
162
163         if self._wsin:
164             self._wsin.close()
165             self._wsin = None
166         if self._wsout:
167             self._wsout.close()
168             self._wsout = None