blob: 835ec35d5961bf5e418f68b56e2784c8b4f42a64 [file] [log] [blame]
mattm@chromium.org830a3712012-11-07 23:00:07 +00001# Copyright (c) 2012 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import json
6import optparse
7import os
8import struct
9import sys
10import warnings
11
12# Ignore deprecation warnings, they make our output more cluttered.
13warnings.filterwarnings("ignore", category=DeprecationWarning)
14
15if sys.platform == 'win32':
16 import msvcrt
17
18
19class Error(Exception):
20 """Error class for this module."""
21
22
23class OptionError(Error):
24 """Error for bad command line options."""
25
26
27class FileMultiplexer(object):
28 def __init__(self, fd1, fd2) :
29 self.__fd1 = fd1
30 self.__fd2 = fd2
31
32 def __del__(self) :
33 if self.__fd1 != sys.stdout and self.__fd1 != sys.stderr:
34 self.__fd1.close()
35 if self.__fd2 != sys.stdout and self.__fd2 != sys.stderr:
36 self.__fd2.close()
37
38 def write(self, text) :
39 self.__fd1.write(text)
40 self.__fd2.write(text)
41
42 def flush(self) :
43 self.__fd1.flush()
44 self.__fd2.flush()
45
46
mattm@chromium.org16959732012-11-28 07:14:19 +000047def MultiplexerHack(std_fd, log_fd):
48 """Creates a FileMultiplexer that will write to both specified files.
49
50 When running on Windows XP bots, stdout and stderr will be invalid file
51 handles, so log_fd will be returned directly. (This does not occur if you
52 run the test suite directly from a console, but only if the output of the
53 test executable is redirected.)
54 """
55 if std_fd.fileno() <= 0:
56 return log_fd
57 return FileMultiplexer(std_fd, log_fd)
58
59
mattm@chromium.org830a3712012-11-07 23:00:07 +000060class TestServerRunner(object):
61 """Runs a test server and communicates with the controlling C++ test code.
62
63 Subclasses should override the create_server method to create their server
64 object, and the add_options method to add their own options.
65 """
66
67 def __init__(self):
68 self.option_parser = optparse.OptionParser()
69 self.add_options()
70
71 def main(self):
72 self.options, self.args = self.option_parser.parse_args()
73
74 logfile = open('testserver.log', 'w')
mattm@chromium.org16959732012-11-28 07:14:19 +000075 sys.stderr = MultiplexerHack(sys.stderr, logfile)
mattm@chromium.org830a3712012-11-07 23:00:07 +000076 if self.options.log_to_console:
mattm@chromium.org16959732012-11-28 07:14:19 +000077 sys.stdout = MultiplexerHack(sys.stdout, logfile)
mattm@chromium.org830a3712012-11-07 23:00:07 +000078 else:
79 sys.stdout = logfile
80
81 server_data = {
82 'host': self.options.host,
83 }
84 self.server = self.create_server(server_data)
85 self._notify_startup_complete(server_data)
86 self.run_server()
87
88 def create_server(self, server_data):
89 """Creates a server object and returns it.
90
91 Must populate server_data['port'], and can set additional server_data
92 elements if desired."""
93 raise NotImplementedError()
94
95 def run_server(self):
96 try:
97 self.server.serve_forever()
98 except KeyboardInterrupt:
99 print 'shutting down server'
100 self.server.stop = True
101
102 def add_options(self):
103 self.option_parser.add_option('--startup-pipe', type='int',
104 dest='startup_pipe',
105 help='File handle of pipe to parent process')
106 self.option_parser.add_option('--log-to-console', action='store_const',
107 const=True, default=False,
108 dest='log_to_console',
109 help='Enables or disables sys.stdout logging '
110 'to the console.')
111 self.option_parser.add_option('--port', default=0, type='int',
112 help='Port used by the server. If '
113 'unspecified, the server will listen on an '
114 'ephemeral port.')
115 self.option_parser.add_option('--host', default='127.0.0.1',
116 dest='host',
117 help='Hostname or IP upon which the server '
118 'will listen. Client connections will also '
119 'only be allowed from this address.')
120
121 def _notify_startup_complete(self, server_data):
122 # Notify the parent that we've started. (BaseServer subclasses
123 # bind their sockets on construction.)
124 if self.options.startup_pipe is not None:
125 server_data_json = json.dumps(server_data)
126 server_data_len = len(server_data_json)
127 print 'sending server_data: %s (%d bytes)' % (
128 server_data_json, server_data_len)
129 if sys.platform == 'win32':
130 fd = msvcrt.open_osfhandle(self.options.startup_pipe, 0)
131 else:
132 fd = self.options.startup_pipe
133 startup_pipe = os.fdopen(fd, "w")
134 # First write the data length as an unsigned 4-byte value. This
135 # is _not_ using network byte ordering since the other end of the
136 # pipe is on the same machine.
137 startup_pipe.write(struct.pack('=L', server_data_len))
138 startup_pipe.write(server_data_json)
139 startup_pipe.close()