blob: e062378a8fa69eb981644fef8d42c50406ed9a67 [file] [log] [blame]
Mark Slee57cc25e2007-02-28 21:43:54 +00001#!/usr/bin/env python
Mark Sleec9676562006-09-05 17:34:52 +00002
David Reissea2cba82009-03-30 21:35:00 +00003#
4# Licensed to the Apache Software Foundation (ASF) under one
5# or more contributor license agreements. See the NOTICE file
6# distributed with this work for additional information
7# regarding copyright ownership. The ASF licenses this file
8# to you under the Apache License, Version 2.0 (the
9# "License"); you may not use this file except in compliance
10# with the License. You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing,
15# software distributed under the License is distributed on an
16# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17# KIND, either express or implied. See the License for the
18# specific language governing permissions and limitations
19# under the License.
20#
Jens Geyerd629ea02015-09-23 21:16:50 +020021import logging
22import os
James E. King III6f8c99e2018-03-24 16:32:02 -040023import signal
Jens Geyerd629ea02015-09-23 21:16:50 +020024import sys
25import time
Bryan Duxbury59d4efd2011-03-21 17:38:22 +000026from optparse import OptionParser
Mark Sleec9676562006-09-05 17:34:52 +000027
Nobuaki Sukegawa7af189a2016-02-11 16:21:01 +090028from util import local_libpath
James E. King III9804ab92019-02-07 16:59:05 -050029sys.path.insert(0, local_libpath())
30from thrift.protocol import TProtocol, TProtocolDecorator
Nobuaki Sukegawa7af189a2016-02-11 16:21:01 +090031
Nobuaki Sukegawaa185d7e2015-11-06 21:24:24 +090032SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
Roger Meierf4eec7a2011-09-11 18:16:21 +000033
Mark Sleec9676562006-09-05 17:34:52 +000034
Jens Geyerd629ea02015-09-23 21:16:50 +020035class TestHandler(object):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090036 def testVoid(self):
37 if options.verbose > 1:
38 logging.info('testVoid()')
Mark Sleec9676562006-09-05 17:34:52 +000039
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090040 def testString(self, str):
41 if options.verbose > 1:
42 logging.info('testString(%s)' % str)
43 return str
Mark Sleec9676562006-09-05 17:34:52 +000044
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090045 def testBool(self, boolean):
46 if options.verbose > 1:
47 logging.info('testBool(%s)' % str(boolean).lower())
48 return boolean
Nobuaki Sukegawaa649e742015-09-21 13:53:25 +090049
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090050 def testByte(self, byte):
51 if options.verbose > 1:
52 logging.info('testByte(%d)' % byte)
53 return byte
Mark Sleec9676562006-09-05 17:34:52 +000054
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090055 def testI16(self, i16):
56 if options.verbose > 1:
57 logging.info('testI16(%d)' % i16)
58 return i16
Mark Sleec98d0502006-09-06 02:42:25 +000059
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090060 def testI32(self, i32):
61 if options.verbose > 1:
62 logging.info('testI32(%d)' % i32)
63 return i32
Mark Sleec98d0502006-09-06 02:42:25 +000064
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090065 def testI64(self, i64):
66 if options.verbose > 1:
67 logging.info('testI64(%d)' % i64)
68 return i64
Mark Sleec98d0502006-09-06 02:42:25 +000069
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090070 def testDouble(self, dub):
71 if options.verbose > 1:
72 logging.info('testDouble(%f)' % dub)
73 return dub
Mark Sleec98d0502006-09-06 02:42:25 +000074
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090075 def testBinary(self, thing):
76 if options.verbose > 1:
77 logging.info('testBinary()') # TODO: hex output
78 return thing
Jens Geyerd629ea02015-09-23 21:16:50 +020079
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090080 def testStruct(self, thing):
81 if options.verbose > 1:
82 logging.info('testStruct({%s, %s, %s, %s})' % (thing.string_thing, thing.byte_thing, thing.i32_thing, thing.i64_thing))
83 return thing
Mark Sleec98d0502006-09-06 02:42:25 +000084
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090085 def testException(self, arg):
86 # if options.verbose > 1:
87 logging.info('testException(%s)' % arg)
88 if arg == 'Xception':
89 raise Xception(errorCode=1001, message=arg)
90 elif arg == 'TException':
91 raise TException(message='This is a TException')
Roger Meier1f554e12013-01-05 20:38:35 +010092
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090093 def testMultiException(self, arg0, arg1):
94 if options.verbose > 1:
95 logging.info('testMultiException(%s, %s)' % (arg0, arg1))
96 if arg0 == 'Xception':
97 raise Xception(errorCode=1001, message='This is an Xception')
98 elif arg0 == 'Xception2':
99 raise Xception2(
100 errorCode=2002,
101 struct_thing=Xtruct(string_thing='This is an Xception2'))
102 return Xtruct(string_thing=arg1)
Mark Sleec9676562006-09-05 17:34:52 +0000103
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900104 def testOneway(self, seconds):
105 if options.verbose > 1:
106 logging.info('testOneway(%d) => sleeping...' % seconds)
107 time.sleep(seconds / 3) # be quick
108 if options.verbose > 1:
109 logging.info('done sleeping')
David Reissdb893b62008-02-18 02:11:48 +0000110
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900111 def testNest(self, thing):
112 if options.verbose > 1:
113 logging.info('testNest(%s)' % thing)
114 return thing
David Reiss74421272008-11-07 23:09:31 +0000115
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900116 def testMap(self, thing):
117 if options.verbose > 1:
118 logging.info('testMap(%s)' % thing)
119 return thing
Jens Geyerd629ea02015-09-23 21:16:50 +0200120
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900121 def testStringMap(self, thing):
122 if options.verbose > 1:
123 logging.info('testStringMap(%s)' % thing)
124 return thing
David Reiss74421272008-11-07 23:09:31 +0000125
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900126 def testSet(self, thing):
127 if options.verbose > 1:
128 logging.info('testSet(%s)' % thing)
129 return thing
David Reiss74421272008-11-07 23:09:31 +0000130
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900131 def testList(self, thing):
132 if options.verbose > 1:
133 logging.info('testList(%s)' % thing)
134 return thing
David Reiss74421272008-11-07 23:09:31 +0000135
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900136 def testEnum(self, thing):
137 if options.verbose > 1:
138 logging.info('testEnum(%s)' % thing)
139 return thing
David Reiss74421272008-11-07 23:09:31 +0000140
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900141 def testTypedef(self, thing):
142 if options.verbose > 1:
143 logging.info('testTypedef(%s)' % thing)
144 return thing
David Reiss74421272008-11-07 23:09:31 +0000145
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900146 def testMapMap(self, thing):
147 if options.verbose > 1:
148 logging.info('testMapMap(%s)' % thing)
149 return {
150 -4: {
151 -4: -4,
152 -3: -3,
153 -2: -2,
154 -1: -1,
155 },
156 4: {
157 4: 4,
158 3: 3,
159 2: 2,
160 1: 1,
161 },
162 }
Roger Meier1f554e12013-01-05 20:38:35 +0100163
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900164 def testInsanity(self, argument):
165 if options.verbose > 1:
166 logging.info('testInsanity(%s)' % argument)
167 return {
168 1: {
169 2: argument,
170 3: argument,
171 },
172 2: {6: Insanity()},
173 }
Bryan Duxbury59d4efd2011-03-21 17:38:22 +0000174
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900175 def testMulti(self, arg0, arg1, arg2, arg3, arg4, arg5):
176 if options.verbose > 1:
Jens Geyer506e3112020-05-17 22:48:51 +0200177 logging.info('testMulti(%s, %s, %s, %s, %s, %s)' % (arg0, arg1, arg2, arg3, arg4, arg5))
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900178 return Xtruct(string_thing='Hello2',
179 byte_thing=arg0, i32_thing=arg1, i64_thing=arg2)
Roger Meier1f554e12013-01-05 20:38:35 +0100180
Bryan Duxbury59d4efd2011-03-21 17:38:22 +0000181
James E. King III9804ab92019-02-07 16:59:05 -0500182class SecondHandler(object):
183 def secondtestString(self, argument):
184 return "testString(\"" + argument + "\")"
185
186
187# LAST_SEQID is a global because we have one transport and multiple protocols
188# running on it (when multiplexed)
189LAST_SEQID = None
190
191
192class TPedanticSequenceIdProtocolWrapper(TProtocolDecorator.TProtocolDecorator):
193 """
194 Wraps any protocol with sequence ID checking: looks for outbound
195 uniqueness as well as request/response alignment.
196 """
197 def __init__(self, protocol):
198 # TProtocolDecorator.__new__ does all the heavy lifting
199 pass
200
201 def readMessageBegin(self):
202 global LAST_SEQID
203 (name, type, seqid) =\
204 super(TPedanticSequenceIdProtocolWrapper, self).readMessageBegin()
205 if LAST_SEQID is not None and LAST_SEQID == seqid:
206 raise TProtocol.TProtocolException(
207 TProtocol.TProtocolException.INVALID_DATA,
208 "We received the same seqid {0} twice in a row".format(seqid))
209 LAST_SEQID = seqid
210 return (name, type, seqid)
211
212
213def make_pedantic(proto):
214 """ Wrap a protocol in the pedantic sequence ID wrapper. """
215 # NOTE: this is disabled for now as many clients send seqid
216 # of zero and that is okay, need a way to identify
217 # clients that MUST send seqid unique to function right
218 # or just force all implementations to send unique seqids (preferred)
219 return proto # TPedanticSequenceIdProtocolWrapper(proto)
220
221
222class TPedanticSequenceIdProtocolFactory(TProtocol.TProtocolFactory):
223 def __init__(self, encapsulated):
224 super(TPedanticSequenceIdProtocolFactory, self).__init__()
225 self.encapsulated = encapsulated
226
227 def getProtocol(self, trans):
228 return make_pedantic(self.encapsulated.getProtocol(trans))
229
230
Nobuaki Sukegawaa185d7e2015-11-06 21:24:24 +0900231def main(options):
James E. King III9804ab92019-02-07 16:59:05 -0500232 # common header allowed client types
233 allowed_client_types = [
234 THeaderTransport.THeaderClientType.HEADERS,
235 THeaderTransport.THeaderClientType.FRAMED_BINARY,
236 THeaderTransport.THeaderClientType.UNFRAMED_BINARY,
237 THeaderTransport.THeaderClientType.FRAMED_COMPACT,
238 THeaderTransport.THeaderClientType.UNFRAMED_COMPACT,
239 ]
240
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900241 # set up the protocol factory form the --protocol option
242 prot_factories = {
Neil Williams66a44c52018-08-13 16:12:24 -0700243 'accel': TBinaryProtocol.TBinaryProtocolAcceleratedFactory(),
James E. King III9804ab92019-02-07 16:59:05 -0500244 'multia': TBinaryProtocol.TBinaryProtocolAcceleratedFactory(),
Neil Williams66a44c52018-08-13 16:12:24 -0700245 'accelc': TCompactProtocol.TCompactProtocolAcceleratedFactory(),
James E. King III9804ab92019-02-07 16:59:05 -0500246 'multiac': TCompactProtocol.TCompactProtocolAcceleratedFactory(),
247 'binary': TPedanticSequenceIdProtocolFactory(TBinaryProtocol.TBinaryProtocolFactory()),
248 'multi': TPedanticSequenceIdProtocolFactory(TBinaryProtocol.TBinaryProtocolFactory()),
Neil Williams66a44c52018-08-13 16:12:24 -0700249 'compact': TCompactProtocol.TCompactProtocolFactory(),
James E. King III9804ab92019-02-07 16:59:05 -0500250 'multic': TCompactProtocol.TCompactProtocolFactory(),
251 'header': THeaderProtocol.THeaderProtocolFactory(allowed_client_types),
252 'multih': THeaderProtocol.THeaderProtocolFactory(allowed_client_types),
Neil Williams66a44c52018-08-13 16:12:24 -0700253 'json': TJSONProtocol.TJSONProtocolFactory(),
James E. King III9804ab92019-02-07 16:59:05 -0500254 'multij': TJSONProtocol.TJSONProtocolFactory(),
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900255 }
Neil Williams66a44c52018-08-13 16:12:24 -0700256 pfactory = prot_factories.get(options.proto, None)
257 if pfactory is None:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900258 raise AssertionError('Unknown --protocol option: %s' % options.proto)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900259 try:
260 pfactory.string_length_limit = options.string_limit
261 pfactory.container_length_limit = options.container_limit
James E. King, III350fe752017-10-25 09:57:18 -0400262 except Exception:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900263 # Ignore errors for those protocols that does not support length limit
264 pass
Bryan Duxbury16066592011-03-22 18:06:04 +0000265
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900266 # get the server type (TSimpleServer, TNonblockingServer, etc...)
267 if len(args) > 1:
268 raise AssertionError('Only one server type may be specified, not multiple types.')
269 server_type = args[0]
James E. King III6f8c99e2018-03-24 16:32:02 -0400270 if options.trans == 'http':
271 server_type = 'THttpServer'
David Reissbcaa2ad2008-06-10 22:55:26 +0000272
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900273 # Set up the handler and processor objects
274 handler = TestHandler()
275 processor = ThriftTest.Processor(handler)
Bryan Duxbury16066592011-03-22 18:06:04 +0000276
James E. King III9804ab92019-02-07 16:59:05 -0500277 if options.proto.startswith('multi'):
278 secondHandler = SecondHandler()
279 secondProcessor = SecondService.Processor(secondHandler)
280
281 multiplexedProcessor = TMultiplexedProcessor()
282 multiplexedProcessor.registerDefault(processor)
283 multiplexedProcessor.registerProcessor('ThriftTest', processor)
284 multiplexedProcessor.registerProcessor('SecondService', secondProcessor)
285 processor = multiplexedProcessor
286
James E. King III6f8c99e2018-03-24 16:32:02 -0400287 global server
288
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900289 # Handle THttpServer as a special case
290 if server_type == 'THttpServer':
James E. King III6f8c99e2018-03-24 16:32:02 -0400291 if options.ssl:
292 __certfile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "server.crt")
293 __keyfile = os.path.join(os.path.dirname(SCRIPT_DIR), "keys", "server.key")
294 server = THttpServer.THttpServer(processor, ('', options.port), pfactory, cert_file=__certfile, key_file=__keyfile)
295 else:
296 server = THttpServer.THttpServer(processor, ('', options.port), pfactory)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900297 server.serve()
298 sys.exit(0)
299
300 # set up server transport and transport factory
301
302 abs_key_path = os.path.join(os.path.dirname(SCRIPT_DIR), 'keys', 'server.pem')
303
304 host = None
305 if options.ssl:
306 from thrift.transport import TSSLSocket
307 transport = TSSLSocket.TSSLServerSocket(host, options.port, certfile=abs_key_path)
308 else:
Kengo Sekif1c53412019-12-13 08:09:36 +0900309 transport = TSocket.TServerSocket(host, options.port, options.domain_socket)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900310 tfactory = TTransport.TBufferedTransportFactory()
311 if options.trans == 'buffered':
312 tfactory = TTransport.TBufferedTransportFactory()
313 elif options.trans == 'framed':
314 tfactory = TTransport.TFramedTransportFactory()
315 elif options.trans == '':
316 raise AssertionError('Unknown --transport option: %s' % options.trans)
317 else:
318 tfactory = TTransport.TBufferedTransportFactory()
319 # if --zlib, then wrap server transport, and use a different transport factory
320 if options.zlib:
321 transport = TZlibTransport.TZlibTransport(transport) # wrap with zlib
322 tfactory = TZlibTransport.TZlibTransportFactory()
323
324 # do server-specific setup here:
325 if server_type == "TNonblockingServer":
326 server = TNonblockingServer.TNonblockingServer(processor, transport, inputProtocolFactory=pfactory)
327 elif server_type == "TProcessPoolServer":
328 import signal
329 from thrift.server import TProcessPoolServer
330 server = TProcessPoolServer.TProcessPoolServer(processor, transport, tfactory, pfactory)
331 server.setNumWorkers(5)
332
333 def set_alarm():
334 def clean_shutdown(signum, frame):
335 for worker in server.workers:
336 if options.verbose > 0:
337 logging.info('Terminating worker: %s' % worker)
338 worker.terminate()
339 if options.verbose > 0:
340 logging.info('Requesting server to stop()')
341 try:
342 server.stop()
James E. King, III350fe752017-10-25 09:57:18 -0400343 except Exception:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900344 pass
345 signal.signal(signal.SIGALRM, clean_shutdown)
346 signal.alarm(4)
347 set_alarm()
348 else:
349 # look up server class dynamically to instantiate server
350 ServerClass = getattr(TServer, server_type)
351 server = ServerClass(processor, transport, tfactory, pfactory)
352 # enter server main loop
Nobuaki Sukegawaa185d7e2015-11-06 21:24:24 +0900353 server.serve()
Nobuaki Sukegawaa185d7e2015-11-06 21:24:24 +0900354
James E. King, III0ad20bd2017-09-30 15:44:16 -0700355
James E. King III6f8c99e2018-03-24 16:32:02 -0400356def exit_gracefully(signum, frame):
357 print("SIGINT received\n")
358 server.shutdown() # doesn't work properly, yet
359 sys.exit(0)
360
361
Nobuaki Sukegawaa185d7e2015-11-06 21:24:24 +0900362if __name__ == '__main__':
James E. King III6f8c99e2018-03-24 16:32:02 -0400363 signal.signal(signal.SIGINT, exit_gracefully)
364
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900365 parser = OptionParser()
366 parser.add_option('--libpydir', type='string', dest='libpydir',
367 help='include this directory to sys.path for locating library code')
368 parser.add_option('--genpydir', type='string', dest='genpydir',
369 default='gen-py',
370 help='include this directory to sys.path for locating generated code')
371 parser.add_option("--port", type="int", dest="port",
372 help="port number for server to listen on")
373 parser.add_option("--zlib", action="store_true", dest="zlib",
374 help="use zlib wrapper for compressed transport")
375 parser.add_option("--ssl", action="store_true", dest="ssl",
376 help="use SSL for encrypted transport")
377 parser.add_option('-v', '--verbose', action="store_const",
378 dest="verbose", const=2,
379 help="verbose output")
380 parser.add_option('-q', '--quiet', action="store_const",
381 dest="verbose", const=0,
382 help="minimal output")
383 parser.add_option('--protocol', dest="proto", type="string",
James E. King III9804ab92019-02-07 16:59:05 -0500384 help="protocol to use, one of: accel, accelc, binary, compact, json, multi, multia, multiac, multic, multih, multij")
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900385 parser.add_option('--transport', dest="trans", type="string",
James E. King III6f8c99e2018-03-24 16:32:02 -0400386 help="transport to use, one of: buffered, framed, http")
Kengo Sekif1c53412019-12-13 08:09:36 +0900387 parser.add_option('--domain-socket', dest="domain_socket", type="string",
388 help="Unix domain socket path")
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900389 parser.add_option('--container-limit', dest='container_limit', type='int', default=None)
390 parser.add_option('--string-limit', dest='string_limit', type='int', default=None)
James E. King III6f8c99e2018-03-24 16:32:02 -0400391 parser.set_defaults(port=9090, verbose=1, proto='binary', transport='buffered')
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900392 options, args = parser.parse_args()
Nobuaki Sukegawaa185d7e2015-11-06 21:24:24 +0900393
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900394 # Print TServer log to stdout so that the test-runner can redirect it to log files
395 logging.basicConfig(level=options.verbose)
Nobuaki Sukegawa7b545b52016-01-11 13:46:04 +0900396
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900397 sys.path.insert(0, os.path.join(SCRIPT_DIR, options.genpydir))
Nobuaki Sukegawaa185d7e2015-11-06 21:24:24 +0900398
James E. King III9804ab92019-02-07 16:59:05 -0500399 from ThriftTest import ThriftTest, SecondService
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900400 from ThriftTest.ttypes import Xtruct, Xception, Xception2, Insanity
401 from thrift.Thrift import TException
James E. King III9804ab92019-02-07 16:59:05 -0500402 from thrift.TMultiplexedProcessor import TMultiplexedProcessor
Neil Williams66a44c52018-08-13 16:12:24 -0700403 from thrift.transport import THeaderTransport
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900404 from thrift.transport import TTransport
405 from thrift.transport import TSocket
406 from thrift.transport import TZlibTransport
407 from thrift.protocol import TBinaryProtocol
408 from thrift.protocol import TCompactProtocol
Neil Williams66a44c52018-08-13 16:12:24 -0700409 from thrift.protocol import THeaderProtocol
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900410 from thrift.protocol import TJSONProtocol
411 from thrift.server import TServer, TNonblockingServer, THttpServer
Nobuaki Sukegawaa185d7e2015-11-06 21:24:24 +0900412
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900413 sys.exit(main(options))