blob: 65e569dcf036d7915efb265227205d36bb699573 [file] [log] [blame]
David Reissea2cba82009-03-30 21:35:00 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
Mark Slee9f0c6512007-02-28 23:58:26 +000019
Mark Slee2f6404d2006-10-10 01:37:40 +000020#ifndef _THRIFT_SERVER_TNONBLOCKINGSERVER_H_
21#define _THRIFT_SERVER_TNONBLOCKINGSERVER_H_ 1
22
Roger Meier49ff8b12012-04-13 09:12:31 +000023#include <thrift/Thrift.h>
cyy316723a2019-01-05 16:35:14 +080024#include <memory>
Roger Meier49ff8b12012-04-13 09:12:31 +000025#include <thrift/server/TServer.h>
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -040026#include <thrift/transport/PlatformSocket.h>
Roger Meier49ff8b12012-04-13 09:12:31 +000027#include <thrift/transport/TBufferTransports.h>
28#include <thrift/transport/TSocket.h>
Divya Thaluru808d1432017-08-06 16:36:36 -070029#include <thrift/transport/TNonblockingServerTransport.h>
Roger Meier49ff8b12012-04-13 09:12:31 +000030#include <thrift/concurrency/ThreadManager.h>
David Reiss01fe1532010-03-09 05:19:25 +000031#include <climits>
Roger Meier49ff8b12012-04-13 09:12:31 +000032#include <thrift/concurrency/Thread.h>
cyyca8af9b2019-01-11 22:13:12 +080033#include <thrift/concurrency/ThreadFactory.h>
Roger Meier49ff8b12012-04-13 09:12:31 +000034#include <thrift/concurrency/Mutex.h>
Mark Slee2f6404d2006-10-10 01:37:40 +000035#include <stack>
Jake Farrellb0d95602011-12-06 01:17:26 +000036#include <vector>
David Reiss9b209552008-04-08 06:26:05 +000037#include <string>
David Reissd7a16f42008-02-19 22:47:29 +000038#include <cstdlib>
Bryan Duxbury266b1732011-09-01 16:50:28 +000039#ifdef HAVE_UNISTD_H
David Reiss5105b2e2009-05-21 02:28:27 +000040#include <unistd.h>
Bryan Duxbury266b1732011-09-01 16:50:28 +000041#endif
Mark Slee2f6404d2006-10-10 01:37:40 +000042#include <event.h>
Ben Craig7207c222015-07-06 08:40:35 -050043#include <event2/event_compat.h>
44#include <event2/event_struct.h>
Mark Slee2f6404d2006-10-10 01:37:40 +000045
Konrad Grochowski16a23a62014-11-13 15:33:38 +010046namespace apache {
47namespace thrift {
48namespace server {
Mark Slee2f6404d2006-10-10 01:37:40 +000049
T Jake Lucianib5e62212009-01-31 22:36:20 +000050using apache::thrift::transport::TMemoryBuffer;
David Reiss105961d2010-10-06 17:10:17 +000051using apache::thrift::transport::TSocket;
Divya Thaluru808d1432017-08-06 16:36:36 -070052using apache::thrift::transport::TNonblockingServerTransport;
T Jake Lucianib5e62212009-01-31 22:36:20 +000053using apache::thrift::protocol::TProtocol;
54using apache::thrift::concurrency::Runnable;
55using apache::thrift::concurrency::ThreadManager;
cyyca8af9b2019-01-11 22:13:12 +080056using apache::thrift::concurrency::ThreadFactory;
Jake Farrellb0d95602011-12-06 01:17:26 +000057using apache::thrift::concurrency::Thread;
58using apache::thrift::concurrency::Mutex;
59using apache::thrift::concurrency::Guard;
Mark Slee2f6404d2006-10-10 01:37:40 +000060
Roger Meier30aae0c2011-07-08 12:23:31 +000061#ifdef LIBEVENT_VERSION_NUMBER
62#define LIBEVENT_VERSION_MAJOR (LIBEVENT_VERSION_NUMBER >> 24)
63#define LIBEVENT_VERSION_MINOR ((LIBEVENT_VERSION_NUMBER >> 16) & 0xFF)
64#define LIBEVENT_VERSION_REL ((LIBEVENT_VERSION_NUMBER >> 8) & 0xFF)
65#else
66// assume latest version 1 series
67#define LIBEVENT_VERSION_MAJOR 1
68#define LIBEVENT_VERSION_MINOR 14
69#define LIBEVENT_VERSION_REL 13
Konrad Grochowski16a23a62014-11-13 15:33:38 +010070#define LIBEVENT_VERSION_NUMBER \
71 ((LIBEVENT_VERSION_MAJOR << 24) | (LIBEVENT_VERSION_MINOR << 16) | (LIBEVENT_VERSION_REL << 8))
Roger Meier30aae0c2011-07-08 12:23:31 +000072#endif
73
74#if LIBEVENT_VERSION_NUMBER < 0x02000000
Konrad Grochowski16a23a62014-11-13 15:33:38 +010075typedef THRIFT_SOCKET evutil_socket_t;
Roger Meier30aae0c2011-07-08 12:23:31 +000076#endif
77
78#ifndef SOCKOPT_CAST_T
Konrad Grochowski16a23a62014-11-13 15:33:38 +010079#ifndef _WIN32
80#define SOCKOPT_CAST_T void
81#else
82#define SOCKOPT_CAST_T char
83#endif // _WIN32
Roger Meier30aae0c2011-07-08 12:23:31 +000084#endif
85
Konrad Grochowski16a23a62014-11-13 15:33:38 +010086template <class T>
Roger Meier30aae0c2011-07-08 12:23:31 +000087inline const SOCKOPT_CAST_T* const_cast_sockopt(const T* v) {
88 return reinterpret_cast<const SOCKOPT_CAST_T*>(v);
89}
90
Konrad Grochowski16a23a62014-11-13 15:33:38 +010091template <class T>
Roger Meier30aae0c2011-07-08 12:23:31 +000092inline SOCKOPT_CAST_T* cast_sockopt(T* v) {
93 return reinterpret_cast<SOCKOPT_CAST_T*>(v);
94}
95
Mark Slee2f6404d2006-10-10 01:37:40 +000096/**
Jake Farrellb0d95602011-12-06 01:17:26 +000097 * This is a non-blocking server in C++ for high performance that
98 * operates a set of IO threads (by default only one). It assumes that
99 * all incoming requests are framed with a 4 byte length indicator and
100 * writes out responses using the same framing.
Mark Slee2f6404d2006-10-10 01:37:40 +0000101 */
David Reiss01fe1532010-03-09 05:19:25 +0000102
David Reiss01fe1532010-03-09 05:19:25 +0000103/// Overload condition actions.
104enum TOverloadAction {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100105 T_OVERLOAD_NO_ACTION, ///< Don't handle overload */
106 T_OVERLOAD_CLOSE_ON_ACCEPT, ///< Drop new connections immediately */
107 T_OVERLOAD_DRAIN_TASK_QUEUE ///< Drop some tasks from head of task queue */
David Reiss01fe1532010-03-09 05:19:25 +0000108};
109
Jake Farrellb0d95602011-12-06 01:17:26 +0000110class TNonblockingIOThread;
111
Mark Slee2f6404d2006-10-10 01:37:40 +0000112class TNonblockingServer : public TServer {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100113private:
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000114 class TConnection;
115
Jake Farrellb0d95602011-12-06 01:17:26 +0000116 friend class TNonblockingIOThread;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100117
118private:
David Reiss01fe1532010-03-09 05:19:25 +0000119 /// Listen backlog
Mark Slee2f6404d2006-10-10 01:37:40 +0000120 static const int LISTEN_BACKLOG = 1024;
121
David Reiss01fe1532010-03-09 05:19:25 +0000122 /// Default limit on size of idle connection pool
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000123 static const size_t CONNECTION_STACK_LIMIT = 1024;
124
Roger Meier3781c242011-12-11 20:07:21 +0000125 /// Default limit on frame size
126 static const int MAX_FRAME_SIZE = 256 * 1024 * 1024;
127
David Reiss01fe1532010-03-09 05:19:25 +0000128 /// Default limit on total number of connected sockets
129 static const int MAX_CONNECTIONS = INT_MAX;
130
131 /// Default limit on connections in handler/task processing
132 static const int MAX_ACTIVE_PROCESSORS = INT_MAX;
133
David Reiss89a12942010-10-06 17:10:52 +0000134 /// Default size of write buffer
135 static const int WRITE_BUFFER_DEFAULT_SIZE = 1024;
136
David Reiss54bec5d2010-10-06 17:10:45 +0000137 /// Maximum size of read buffer allocated to idle connection (0 = unlimited)
138 static const int IDLE_READ_BUFFER_LIMIT = 1024;
139
140 /// Maximum size of write buffer allocated to idle connection (0 = unlimited)
141 static const int IDLE_WRITE_BUFFER_LIMIT = 1024;
142
143 /// # of calls before resizing oversized buffers (0 = check only on close)
144 static const int RESIZE_BUFFER_EVERY_N = 512;
145
Jake Farrellb0d95602011-12-06 01:17:26 +0000146 /// # of IO threads to use by default
147 static const int DEFAULT_IO_THREADS = 1;
148
Jake Farrellb0d95602011-12-06 01:17:26 +0000149 /// # of IO threads this server will use
150 size_t numIOThreads_;
151
152 /// Whether to set high scheduling priority for IO threads
153 bool useHighPriorityIOThreads_;
154
David Reiss01fe1532010-03-09 05:19:25 +0000155 /// Server socket file descriptor
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -0400156 THRIFT_SOCKET serverSocket_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000157
Roger Meier6f2a5032013-07-08 23:35:25 +0200158 /// The optional user-provided event-base (for single-thread servers)
159 event_base* userEventBase_;
160
zeshuai00726681fb2020-06-03 17:24:38 +0800161 /// For processing via thread pool, may be nullptr
cyy316723a2019-01-05 16:35:14 +0800162 std::shared_ptr<ThreadManager> threadManager_;
Mark Sleee02385b2007-06-09 01:21:16 +0000163
David Reiss01fe1532010-03-09 05:19:25 +0000164 /// Is thread pool processing?
Mark Sleee02385b2007-06-09 01:21:16 +0000165 bool threadPoolProcessing_;
166
Jake Farrellb0d95602011-12-06 01:17:26 +0000167 // Factory to create the IO threads
cyyca8af9b2019-01-11 22:13:12 +0800168 std::shared_ptr<ThreadFactory> ioThreadFactory_;
Mark Slee79b16942007-11-26 19:05:29 +0000169
Jake Farrellb0d95602011-12-06 01:17:26 +0000170 // Vector of IOThread objects that will handle our IO
cyy316723a2019-01-05 16:35:14 +0800171 std::vector<std::shared_ptr<TNonblockingIOThread> > ioThreads_;
Mark Slee79b16942007-11-26 19:05:29 +0000172
Jake Farrellb0d95602011-12-06 01:17:26 +0000173 // Index of next IO Thread to be used (for round-robin)
Roger Meierd0cdecf2011-12-08 19:34:01 +0000174 uint32_t nextIOThread_;
Jake Farrellb0d95602011-12-06 01:17:26 +0000175
176 // Synchronizes access to connection stack and similar data
177 Mutex connMutex_;
David Reiss01fe1532010-03-09 05:19:25 +0000178
179 /// Number of TConnection object we've created
David Reiss1997f102008-04-29 00:29:41 +0000180 size_t numTConnections_;
181
David Reiss9e8073c2010-03-09 05:19:39 +0000182 /// Number of Connections processing or waiting to process
David Reiss01fe1532010-03-09 05:19:25 +0000183 size_t numActiveProcessors_;
184
185 /// Limit for how many TConnection objects to cache
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000186 size_t connectionStackLimit_;
187
David Reiss01fe1532010-03-09 05:19:25 +0000188 /// Limit for number of connections processing or waiting to process
189 size_t maxActiveProcessors_;
190
191 /// Limit for number of open connections
192 size_t maxConnections_;
193
Roger Meier3781c242011-12-11 20:07:21 +0000194 /// Limit for frame size
195 size_t maxFrameSize_;
196
David Reiss068f4162010-03-09 05:19:45 +0000197 /// Time in milliseconds before an unperformed task expires (0 == infinite).
198 int64_t taskExpireTime_;
199
David Reiss01fe1532010-03-09 05:19:25 +0000200 /**
201 * Hysteresis for overload state. This is the fraction of the overload
202 * value that needs to be reached before the overload state is cleared;
203 * must be <= 1.0.
204 */
205 double overloadHysteresis_;
206
207 /// Action to take when we're overloaded.
208 TOverloadAction overloadAction_;
209
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000210 /**
David Reiss89a12942010-10-06 17:10:52 +0000211 * The write buffer is initialized (and when idleWriteBufferLimit_ is checked
212 * and found to be exceeded, reinitialized) to this size.
213 */
214 size_t writeBufferDefaultSize_;
215
216 /**
David Reiss54bec5d2010-10-06 17:10:45 +0000217 * Max read buffer size for an idle TConnection. When we place an idle
218 * TConnection into connectionStack_ or on every resizeBufferEveryN_ calls,
David Reiss89a12942010-10-06 17:10:52 +0000219 * we will free the buffer (such that it will be reinitialized by the next
220 * received frame) if it has exceeded this limit. 0 disables this check.
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000221 */
David Reiss54bec5d2010-10-06 17:10:45 +0000222 size_t idleReadBufferLimit_;
223
224 /**
225 * Max write buffer size for an idle connection. When we place an idle
226 * TConnection into connectionStack_ or on every resizeBufferEveryN_ calls,
227 * we insure that its write buffer is <= to this size; otherwise we
David Reiss89a12942010-10-06 17:10:52 +0000228 * replace it with a new one of writeBufferDefaultSize_ bytes to insure that
229 * idle connections don't hog memory. 0 disables this check.
David Reiss54bec5d2010-10-06 17:10:45 +0000230 */
231 size_t idleWriteBufferLimit_;
232
233 /**
234 * Every N calls we check the buffer size limits on a connected TConnection.
235 * 0 disables (i.e. the checks are only done when a connection closes).
236 */
237 int32_t resizeBufferEveryN_;
David Reiss01fe1532010-03-09 05:19:25 +0000238
239 /// Set if we are currently in an overloaded state.
240 bool overloaded_;
241
242 /// Count of connections dropped since overload started
243 uint32_t nConnectionsDropped_;
244
245 /// Count of connections dropped on overload since server started
246 uint64_t nTotalConnectionsDropped_;
247
Mark Slee2f6404d2006-10-10 01:37:40 +0000248 /**
249 * This is a stack of all the objects that have been created but that
250 * are NOT currently in use. When we close a connection, we place it on this
251 * stack so that the object can be reused later, rather than freeing the
252 * memory and reallocating a new object later.
253 */
254 std::stack<TConnection*> connectionStack_;
255
David Reiss01fe1532010-03-09 05:19:25 +0000256 /**
Roger Meier0c04fcc2013-03-22 19:52:08 +0100257 * This container holds pointers to all active connections. This container
258 * allows the server to clean up unlcosed connection objects at destruction,
259 * which in turn allows their transports, protocols, processors and handlers
260 * to deallocate and clean up correctly.
261 */
262 std::vector<TConnection*> activeConnections_;
263
Divya Thaluru808d1432017-08-06 16:36:36 -0700264 /*
265 */
cyy316723a2019-01-05 16:35:14 +0800266 std::shared_ptr<TNonblockingServerTransport> serverTransport_;
Divya Thaluru808d1432017-08-06 16:36:36 -0700267
Roger Meier0c04fcc2013-03-22 19:52:08 +0100268 /**
David Reiss01fe1532010-03-09 05:19:25 +0000269 * Called when server socket had something happen. We accept all waiting
270 * client connections on listen socket fd and assign TConnection objects
271 * to handle those requests.
272 *
David Reiss01fe1532010-03-09 05:19:25 +0000273 * @param which the event flag that triggered the handler.
274 */
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -0400275 void handleEvent(THRIFT_SOCKET fd, short which);
Mark Slee2f6404d2006-10-10 01:37:40 +0000276
Divya Thaluru808d1432017-08-06 16:36:36 -0700277 void init() {
Roger Meier0be9ffa2013-07-19 21:10:01 +0200278 serverSocket_ = THRIFT_INVALID_SOCKET;
Jake Farrellb0d95602011-12-06 01:17:26 +0000279 numIOThreads_ = DEFAULT_IO_THREADS;
280 nextIOThread_ = 0;
281 useHighPriorityIOThreads_ = false;
Sebastian Zenker042580f2019-01-29 15:48:12 +0100282 userEventBase_ = nullptr;
Bryan Duxburyc7fed1f2011-08-29 18:01:24 +0000283 threadPoolProcessing_ = false;
Bryan Duxburyc7fed1f2011-08-29 18:01:24 +0000284 numTConnections_ = 0;
285 numActiveProcessors_ = 0;
286 connectionStackLimit_ = CONNECTION_STACK_LIMIT;
287 maxActiveProcessors_ = MAX_ACTIVE_PROCESSORS;
288 maxConnections_ = MAX_CONNECTIONS;
Roger Meier3781c242011-12-11 20:07:21 +0000289 maxFrameSize_ = MAX_FRAME_SIZE;
Bryan Duxburyc7fed1f2011-08-29 18:01:24 +0000290 taskExpireTime_ = 0;
291 overloadHysteresis_ = 0.8;
292 overloadAction_ = T_OVERLOAD_NO_ACTION;
293 writeBufferDefaultSize_ = WRITE_BUFFER_DEFAULT_SIZE;
294 idleReadBufferLimit_ = IDLE_READ_BUFFER_LIMIT;
295 idleWriteBufferLimit_ = IDLE_WRITE_BUFFER_LIMIT;
296 resizeBufferEveryN_ = RESIZE_BUFFER_EVERY_N;
297 overloaded_ = false;
298 nConnectionsDropped_ = 0;
299 nTotalConnectionsDropped_ = 0;
300 }
Mark Sleef9373392007-01-24 19:41:57 +0000301
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100302public:
cyy316723a2019-01-05 16:35:14 +0800303 TNonblockingServer(const std::shared_ptr<TProcessorFactory>& processorFactory,
304 const std::shared_ptr<apache::thrift::transport::TNonblockingServerTransport>& serverTransport)
Divya Thaluru808d1432017-08-06 16:36:36 -0700305 : TServer(processorFactory), serverTransport_(serverTransport) {
306 init();
Bryan Duxbury7a9fb812011-09-01 18:31:53 +0000307 }
308
cyy316723a2019-01-05 16:35:14 +0800309 TNonblockingServer(const std::shared_ptr<TProcessor>& processor,
310 const std::shared_ptr<apache::thrift::transport::TNonblockingServerTransport>& serverTransport)
Divya Thaluru808d1432017-08-06 16:36:36 -0700311 : TServer(processor), serverTransport_(serverTransport) {
312 init();
Bryan Duxburyc7fed1f2011-08-29 18:01:24 +0000313 }
314
Bryan Duxbury7a9fb812011-09-01 18:31:53 +0000315
cyy316723a2019-01-05 16:35:14 +0800316 TNonblockingServer(const std::shared_ptr<TProcessorFactory>& processorFactory,
317 const std::shared_ptr<TProtocolFactory>& protocolFactory,
318 const std::shared_ptr<apache::thrift::transport::TNonblockingServerTransport>& serverTransport,
319 const std::shared_ptr<ThreadManager>& threadManager
320 = std::shared_ptr<ThreadManager>())
James E. King, III82ae9572017-08-05 12:23:54 -0400321 : TServer(processorFactory), serverTransport_(serverTransport) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700322 init();
Bryan Duxbury7a9fb812011-09-01 18:31:53 +0000323
324 setInputProtocolFactory(protocolFactory);
325 setOutputProtocolFactory(protocolFactory);
326 setThreadManager(threadManager);
327 }
328
cyy316723a2019-01-05 16:35:14 +0800329 TNonblockingServer(const std::shared_ptr<TProcessor>& processor,
330 const std::shared_ptr<TProtocolFactory>& protocolFactory,
331 const std::shared_ptr<apache::thrift::transport::TNonblockingServerTransport>& serverTransport,
332 const std::shared_ptr<ThreadManager>& threadManager
333 = std::shared_ptr<ThreadManager>())
Divya Thaluru808d1432017-08-06 16:36:36 -0700334 : TServer(processor), serverTransport_(serverTransport) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700335 init();
Bryan Duxburyc7fed1f2011-08-29 18:01:24 +0000336
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000337 setInputProtocolFactory(protocolFactory);
338 setOutputProtocolFactory(protocolFactory);
Mark Sleee02385b2007-06-09 01:21:16 +0000339 setThreadManager(threadManager);
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000340 }
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000341
cyy316723a2019-01-05 16:35:14 +0800342 TNonblockingServer(const std::shared_ptr<TProcessorFactory>& processorFactory,
343 const std::shared_ptr<TTransportFactory>& inputTransportFactory,
344 const std::shared_ptr<TTransportFactory>& outputTransportFactory,
345 const std::shared_ptr<TProtocolFactory>& inputProtocolFactory,
346 const std::shared_ptr<TProtocolFactory>& outputProtocolFactory,
347 const std::shared_ptr<apache::thrift::transport::TNonblockingServerTransport>& serverTransport,
348 const std::shared_ptr<ThreadManager>& threadManager
349 = std::shared_ptr<ThreadManager>())
Divya Thaluru808d1432017-08-06 16:36:36 -0700350 : TServer(processorFactory), serverTransport_(serverTransport) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700351 init();
Bryan Duxbury7a9fb812011-09-01 18:31:53 +0000352
353 setInputTransportFactory(inputTransportFactory);
354 setOutputTransportFactory(outputTransportFactory);
355 setInputProtocolFactory(inputProtocolFactory);
356 setOutputProtocolFactory(outputProtocolFactory);
357 setThreadManager(threadManager);
358 }
359
cyy316723a2019-01-05 16:35:14 +0800360 TNonblockingServer(const std::shared_ptr<TProcessor>& processor,
361 const std::shared_ptr<TTransportFactory>& inputTransportFactory,
362 const std::shared_ptr<TTransportFactory>& outputTransportFactory,
363 const std::shared_ptr<TProtocolFactory>& inputProtocolFactory,
364 const std::shared_ptr<TProtocolFactory>& outputProtocolFactory,
365 const std::shared_ptr<apache::thrift::transport::TNonblockingServerTransport>& serverTransport,
366 const std::shared_ptr<ThreadManager>& threadManager
367 = std::shared_ptr<ThreadManager>())
Divya Thaluru808d1432017-08-06 16:36:36 -0700368 : TServer(processor), serverTransport_(serverTransport) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700369 init();
Bryan Duxburyc7fed1f2011-08-29 18:01:24 +0000370
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000371 setInputTransportFactory(inputTransportFactory);
372 setOutputTransportFactory(outputTransportFactory);
373 setInputProtocolFactory(inputProtocolFactory);
374 setOutputProtocolFactory(outputProtocolFactory);
Mark Sleee02385b2007-06-09 01:21:16 +0000375 setThreadManager(threadManager);
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000376 }
Mark Slee79b16942007-11-26 19:05:29 +0000377
Sebastian Zenker042580f2019-01-29 15:48:12 +0100378 ~TNonblockingServer() override;
Mark Slee2f6404d2006-10-10 01:37:40 +0000379
cyy316723a2019-01-05 16:35:14 +0800380 void setThreadManager(std::shared_ptr<ThreadManager> threadManager);
Mark Sleee02385b2007-06-09 01:21:16 +0000381
Divya Thaluru808d1432017-08-06 16:36:36 -0700382 int getListenPort() { return serverTransport_->getListenPort(); }
Nobuaki Sukegawad0d7a652014-12-07 21:36:51 +0900383
cyy316723a2019-01-05 16:35:14 +0800384 std::shared_ptr<ThreadManager> getThreadManager() { return threadManager_; }
David Reiss1997f102008-04-29 00:29:41 +0000385
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000386 /**
Jake Farrellb0d95602011-12-06 01:17:26 +0000387 * Sets the number of IO threads used by this server. Can only be used before
cyyca8af9b2019-01-11 22:13:12 +0800388 * the call to serve() and has no effect afterwards.
Jake Farrellb0d95602011-12-06 01:17:26 +0000389 */
Nobuaki Sukegawa8016af82015-01-02 23:14:22 +0900390 void setNumIOThreads(size_t numThreads) {
391 numIOThreads_ = numThreads;
392 // User-provided event-base doesn't works for multi-threaded servers
393 assert(numIOThreads_ <= 1 || !userEventBase_);
394 }
Jake Farrellb0d95602011-12-06 01:17:26 +0000395
396 /** Return whether the IO threads will get high scheduling priority */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100397 bool useHighPriorityIOThreads() const { return useHighPriorityIOThreads_; }
Jake Farrellb0d95602011-12-06 01:17:26 +0000398
399 /** Set whether the IO threads will get high scheduling priority. */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100400 void setUseHighPriorityIOThreads(bool val) { useHighPriorityIOThreads_ = val; }
Jake Farrellb0d95602011-12-06 01:17:26 +0000401
402 /** Return the number of IO threads used by this server. */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100403 size_t getNumIOThreads() const { return numIOThreads_; }
Jake Farrellb0d95602011-12-06 01:17:26 +0000404
405 /**
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000406 * Get the maximum number of unused TConnection we will hold in reserve.
407 *
408 * @return the current limit on TConnection pool size.
409 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100410 size_t getConnectionStackLimit() const { return connectionStackLimit_; }
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000411
412 /**
413 * Set the maximum number of unused TConnection we will hold in reserve.
414 *
415 * @param sz the new limit for TConnection pool size.
416 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100417 void setConnectionStackLimit(size_t sz) { connectionStackLimit_ = sz; }
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000418
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100419 bool isThreadPoolProcessing() const { return threadPoolProcessing_; }
Mark Sleee02385b2007-06-09 01:21:16 +0000420
cyy316723a2019-01-05 16:35:14 +0800421 void addTask(std::shared_ptr<Runnable> task) {
David Reiss068f4162010-03-09 05:19:45 +0000422 threadManager_->add(task, 0LL, taskExpireTime_);
Mark Sleee02385b2007-06-09 01:21:16 +0000423 }
424
David Reiss01fe1532010-03-09 05:19:25 +0000425 /**
426 * Return the count of sockets currently connected to.
427 *
428 * @return count of connected sockets.
429 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100430 size_t getNumConnections() const { return numTConnections_; }
David Reiss1997f102008-04-29 00:29:41 +0000431
David Reiss01fe1532010-03-09 05:19:25 +0000432 /**
Roger Meierec8027f2012-04-11 21:43:25 +0000433 * Return the count of sockets currently connected to.
434 *
435 * @return count of connected sockets.
436 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100437 size_t getNumActiveConnections() const { return getNumConnections() - getNumIdleConnections(); }
Roger Meierec8027f2012-04-11 21:43:25 +0000438
439 /**
David Reiss01fe1532010-03-09 05:19:25 +0000440 * Return the count of connection objects allocated but not in use.
441 *
442 * @return count of idle connection objects.
443 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100444 size_t getNumIdleConnections() const { return connectionStack_.size(); }
David Reiss1997f102008-04-29 00:29:41 +0000445
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000446 /**
David Reiss01fe1532010-03-09 05:19:25 +0000447 * Return count of number of connections which are currently processing.
448 * This is defined as a connection where all data has been received and
449 * either assigned a task (when threading) or passed to a handler (when
450 * not threading), and where the handler has not yet returned.
451 *
452 * @return # of connections currently processing.
453 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100454 size_t getNumActiveProcessors() const { return numActiveProcessors_; }
David Reiss01fe1532010-03-09 05:19:25 +0000455
456 /// Increment the count of connections currently processing.
457 void incrementActiveProcessors() {
Jake Farrellb0d95602011-12-06 01:17:26 +0000458 Guard g(connMutex_);
David Reiss01fe1532010-03-09 05:19:25 +0000459 ++numActiveProcessors_;
460 }
461
462 /// Decrement the count of connections currently processing.
463 void decrementActiveProcessors() {
Jake Farrellb0d95602011-12-06 01:17:26 +0000464 Guard g(connMutex_);
David Reiss01fe1532010-03-09 05:19:25 +0000465 if (numActiveProcessors_ > 0) {
466 --numActiveProcessors_;
467 }
468 }
469
470 /**
471 * Get the maximum # of connections allowed before overload.
472 *
473 * @return current setting.
474 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100475 size_t getMaxConnections() const { return maxConnections_; }
David Reiss01fe1532010-03-09 05:19:25 +0000476
477 /**
478 * Set the maximum # of connections allowed before overload.
479 *
480 * @param maxConnections new setting for maximum # of connections.
481 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100482 void setMaxConnections(size_t maxConnections) { maxConnections_ = maxConnections; }
David Reiss01fe1532010-03-09 05:19:25 +0000483
484 /**
485 * Get the maximum # of connections waiting in handler/task before overload.
486 *
487 * @return current setting.
488 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100489 size_t getMaxActiveProcessors() const { return maxActiveProcessors_; }
David Reiss01fe1532010-03-09 05:19:25 +0000490
491 /**
492 * Set the maximum # of connections waiting in handler/task before overload.
493 *
494 * @param maxActiveProcessors new setting for maximum # of active processes.
495 */
496 void setMaxActiveProcessors(size_t maxActiveProcessors) {
497 maxActiveProcessors_ = maxActiveProcessors;
498 }
499
500 /**
Roger Meier3781c242011-12-11 20:07:21 +0000501 * Get the maximum allowed frame size.
502 *
503 * If a client tries to send a message larger than this limit,
504 * its connection will be closed.
505 *
506 * @return Maxium frame size, in bytes.
507 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100508 size_t getMaxFrameSize() const { return maxFrameSize_; }
Roger Meier3781c242011-12-11 20:07:21 +0000509
510 /**
511 * Set the maximum allowed frame size.
512 *
513 * @param maxFrameSize The new maximum frame size.
514 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100515 void setMaxFrameSize(size_t maxFrameSize) { maxFrameSize_ = maxFrameSize; }
Roger Meier3781c242011-12-11 20:07:21 +0000516
517 /**
David Reiss01fe1532010-03-09 05:19:25 +0000518 * Get fraction of maximum limits before an overload condition is cleared.
519 *
520 * @return hysteresis fraction
521 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100522 double getOverloadHysteresis() const { return overloadHysteresis_; }
David Reiss01fe1532010-03-09 05:19:25 +0000523
524 /**
525 * Set fraction of maximum limits before an overload condition is cleared.
526 * A good value would probably be between 0.5 and 0.9.
527 *
528 * @param hysteresisFraction fraction <= 1.0.
529 */
530 void setOverloadHysteresis(double hysteresisFraction) {
531 if (hysteresisFraction <= 1.0 && hysteresisFraction > 0.0) {
532 overloadHysteresis_ = hysteresisFraction;
533 }
534 }
535
536 /**
537 * Get the action the server will take on overload.
538 *
539 * @return a TOverloadAction enum value for the currently set action.
540 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100541 TOverloadAction getOverloadAction() const { return overloadAction_; }
David Reiss01fe1532010-03-09 05:19:25 +0000542
543 /**
544 * Set the action the server is to take on overload.
545 *
546 * @param overloadAction a TOverloadAction enum value for the action.
547 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100548 void setOverloadAction(TOverloadAction overloadAction) { overloadAction_ = overloadAction; }
David Reiss01fe1532010-03-09 05:19:25 +0000549
550 /**
David Reiss068f4162010-03-09 05:19:45 +0000551 * Get the time in milliseconds after which a task expires (0 == infinite).
552 *
553 * @return a 64-bit time in milliseconds.
554 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100555 int64_t getTaskExpireTime() const { return taskExpireTime_; }
David Reiss068f4162010-03-09 05:19:45 +0000556
557 /**
558 * Set the time in milliseconds after which a task expires (0 == infinite).
559 *
560 * @param taskExpireTime a 64-bit time in milliseconds.
561 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100562 void setTaskExpireTime(int64_t taskExpireTime) { taskExpireTime_ = taskExpireTime; }
David Reiss068f4162010-03-09 05:19:45 +0000563
564 /**
David Reiss01fe1532010-03-09 05:19:25 +0000565 * Determine if the server is currently overloaded.
566 * This function checks the maximums for open connections and connections
567 * currently in processing, and sets an overload condition if they are
568 * exceeded. The overload will persist until both values are below the
569 * current hysteresis fraction of their maximums.
570 *
571 * @return true if an overload condition exists, false if not.
572 */
573 bool serverOverloaded();
574
575 /** Pop and discard next task on threadpool wait queue.
576 *
577 * @return true if a task was discarded, false if the wait queue was empty.
578 */
579 bool drainPendingTask();
580
581 /**
David Reiss89a12942010-10-06 17:10:52 +0000582 * Get the starting size of a TConnection object's write buffer.
583 *
584 * @return # bytes we initialize a TConnection object's write buffer to.
585 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100586 size_t getWriteBufferDefaultSize() const { return writeBufferDefaultSize_; }
David Reiss89a12942010-10-06 17:10:52 +0000587
588 /**
589 * Set the starting size of a TConnection object's write buffer.
590 *
591 * @param size # bytes we initialize a TConnection object's write buffer to.
592 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100593 void setWriteBufferDefaultSize(size_t size) { writeBufferDefaultSize_ = size; }
David Reiss89a12942010-10-06 17:10:52 +0000594
595 /**
David Reiss54bec5d2010-10-06 17:10:45 +0000596 * Get the maximum size of read buffer allocated to idle TConnection objects.
597 *
David Reiss89a12942010-10-06 17:10:52 +0000598 * @return # bytes beyond which we will dealloc idle buffer.
David Reiss54bec5d2010-10-06 17:10:45 +0000599 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100600 size_t getIdleReadBufferLimit() const { return idleReadBufferLimit_; }
David Reiss54bec5d2010-10-06 17:10:45 +0000601
602 /**
603 * [NOTE: This is for backwards compatibility, use getIdleReadBufferLimit().]
604 * Get the maximum size of read buffer allocated to idle TConnection objects.
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000605 *
David Reiss89a12942010-10-06 17:10:52 +0000606 * @return # bytes beyond which we will dealloc idle buffer.
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000607 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100608 size_t getIdleBufferMemLimit() const { return idleReadBufferLimit_; }
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000609
610 /**
David Reiss54bec5d2010-10-06 17:10:45 +0000611 * Set the maximum size read buffer allocated to idle TConnection objects.
612 * If a TConnection object is found (either on connection close or between
613 * calls when resizeBufferEveryN_ is set) with more than this much memory
David Reiss89a12942010-10-06 17:10:52 +0000614 * allocated to its read buffer, we free it and allow it to be reinitialized
615 * on the next received frame.
David Reiss54bec5d2010-10-06 17:10:45 +0000616 *
617 * @param limit of bytes beyond which we will shrink buffers when checked.
618 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100619 void setIdleReadBufferLimit(size_t limit) { idleReadBufferLimit_ = limit; }
David Reiss54bec5d2010-10-06 17:10:45 +0000620
621 /**
622 * [NOTE: This is for backwards compatibility, use setIdleReadBufferLimit().]
623 * Set the maximum size read buffer allocated to idle TConnection objects.
624 * If a TConnection object is found (either on connection close or between
625 * calls when resizeBufferEveryN_ is set) with more than this much memory
David Reiss89a12942010-10-06 17:10:52 +0000626 * allocated to its read buffer, we free it and allow it to be reinitialized
627 * on the next received frame.
David Reiss54bec5d2010-10-06 17:10:45 +0000628 *
629 * @param limit of bytes beyond which we will shrink buffers when checked.
630 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100631 void setIdleBufferMemLimit(size_t limit) { idleReadBufferLimit_ = limit; }
David Reiss54bec5d2010-10-06 17:10:45 +0000632
633 /**
634 * Get the maximum size of write buffer allocated to idle TConnection objects.
635 *
636 * @return # bytes beyond which we will reallocate buffers when checked.
637 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100638 size_t getIdleWriteBufferLimit() const { return idleWriteBufferLimit_; }
David Reiss54bec5d2010-10-06 17:10:45 +0000639
640 /**
641 * Set the maximum size write buffer allocated to idle TConnection objects.
642 * If a TConnection object is found (either on connection close or between
643 * calls when resizeBufferEveryN_ is set) with more than this much memory
David Reiss89a12942010-10-06 17:10:52 +0000644 * allocated to its write buffer, we destroy and construct that buffer with
645 * writeBufferDefaultSize_ bytes.
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000646 *
647 * @param limit of bytes beyond which we will shrink buffers when idle.
648 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100649 void setIdleWriteBufferLimit(size_t limit) { idleWriteBufferLimit_ = limit; }
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000650
David Reiss01fe1532010-03-09 05:19:25 +0000651 /**
David Reiss54bec5d2010-10-06 17:10:45 +0000652 * Get # of calls made between buffer size checks. 0 means disabled.
653 *
654 * @return # of calls between buffer size checks.
655 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100656 int32_t getResizeBufferEveryN() const { return resizeBufferEveryN_; }
David Reiss54bec5d2010-10-06 17:10:45 +0000657
658 /**
659 * Check buffer sizes every "count" calls. This allows buffer limits
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +0100660 * to be enforced for persistent connections with a controllable degree
David Reiss54bec5d2010-10-06 17:10:45 +0000661 * of overhead. 0 disables checks except at connection close.
662 *
663 * @param count the number of calls between checks, or 0 to disable
664 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100665 void setResizeBufferEveryN(int32_t count) { resizeBufferEveryN_ = count; }
David Reiss54bec5d2010-10-06 17:10:45 +0000666
Jake Farrellb0d95602011-12-06 01:17:26 +0000667 /**
668 * Main workhorse function, starts up the server listening on a port and
669 * loops over the libevent handler.
670 */
Sebastian Zenker042580f2019-01-29 15:48:12 +0100671 void serve() override;
David Reiss54bec5d2010-10-06 17:10:45 +0000672
Jake Farrellb0d95602011-12-06 01:17:26 +0000673 /**
674 * Causes the server to terminate gracefully (can be called from any thread).
675 */
Sebastian Zenker042580f2019-01-29 15:48:12 +0100676 void stop() override;
David Reiss54bec5d2010-10-06 17:10:45 +0000677
Jake Farrellb0d95602011-12-06 01:17:26 +0000678 /// Creates a socket to listen on and binds it to the local port.
679 void createAndListenOnSocket();
James E. King, III82ae9572017-08-05 12:23:54 -0400680
Roger Meier6f2a5032013-07-08 23:35:25 +0200681 /**
682 * Register the optional user-provided event-base (for single-thread servers)
683 *
684 * This method should be used when the server is running in a single-thread
685 * mode, and the event base is provided by the user (i.e., the caller).
686 *
687 * @param user_event_base the user-provided event-base. The user is
688 * responsible for freeing the event base memory.
689 */
690 void registerEvents(event_base* user_event_base);
691
692 /**
693 * Returns the optional user-provided event-base (for single-thread servers).
694 */
695 event_base* getUserEventBase() const { return userEventBase_; }
696
Dave Watson792db4e2015-01-16 11:22:01 -0800697 /** Some transports, like THeaderTransport, require passing through
698 * the framing size instead of stripping it.
699 */
700 bool getHeaderTransport();
701
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100702private:
Roger Meier6f2a5032013-07-08 23:35:25 +0200703 /**
704 * Callback function that the threadmanager calls when a task reaches
705 * its expiration time. It is needed to clean up the expired connection.
706 *
707 * @param task the runnable associated with the expired task.
708 */
cyy316723a2019-01-05 16:35:14 +0800709 void expireClose(std::shared_ptr<Runnable> task);
Roger Meier6f2a5032013-07-08 23:35:25 +0200710
David Reiss54bec5d2010-10-06 17:10:45 +0000711 /**
David Reiss01fe1532010-03-09 05:19:25 +0000712 * Return an initialized connection object. Creates or recovers from
713 * pool a TConnection and initializes it with the provided socket FD
714 * and flags.
715 *
716 * @param socket FD of socket associated with this connection.
David Reiss105961d2010-10-06 17:10:17 +0000717 * @param addr the sockaddr of the client
718 * @param addrLen the length of addr
David Reiss01fe1532010-03-09 05:19:25 +0000719 * @return pointer to initialized TConnection object.
720 */
cyy316723a2019-01-05 16:35:14 +0800721 TConnection* createConnection(std::shared_ptr<TSocket> socket);
Mark Slee2f6404d2006-10-10 01:37:40 +0000722
David Reiss01fe1532010-03-09 05:19:25 +0000723 /**
724 * Returns a connection to pool or deletion. If the connection pool
725 * (a stack) isn't full, place the connection object on it, otherwise
726 * just delete it.
727 *
728 * @param connection the TConection being returned.
729 */
Mark Slee2f6404d2006-10-10 01:37:40 +0000730 void returnConnection(TConnection* connection);
Jake Farrellb0d95602011-12-06 01:17:26 +0000731};
Mark Slee2f6404d2006-10-10 01:37:40 +0000732
Jake Farrellb0d95602011-12-06 01:17:26 +0000733class TNonblockingIOThread : public Runnable {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100734public:
Jake Farrellb0d95602011-12-06 01:17:26 +0000735 // Creates an IO thread and sets up the event base. The listenSocket should
736 // be a valid FD on which listen() has already been called. If the
737 // listenSocket is < 0, accepting will not be done.
738 TNonblockingIOThread(TNonblockingServer* server,
739 int number,
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -0400740 THRIFT_SOCKET listenSocket,
Jake Farrellb0d95602011-12-06 01:17:26 +0000741 bool useHighPriority);
742
Sebastian Zenker042580f2019-01-29 15:48:12 +0100743 ~TNonblockingIOThread() override;
Jake Farrellb0d95602011-12-06 01:17:26 +0000744
745 // Returns the event-base for this thread.
746 event_base* getEventBase() const { return eventBase_; }
747
748 // Returns the server for this thread.
749 TNonblockingServer* getServer() const { return server_; }
750
751 // Returns the number of this IO thread.
752 int getThreadNumber() const { return number_; }
753
754 // Returns the thread id associated with this object. This should
755 // only be called after the thread has been started.
Roger Meier12d70532011-12-14 23:35:28 +0000756 Thread::id_t getThreadId() const { return threadId_; }
Jake Farrellb0d95602011-12-06 01:17:26 +0000757
758 // Returns the send-fd for task complete notifications.
Roger Meier12d70532011-12-14 23:35:28 +0000759 evutil_socket_t getNotificationSendFD() const { return notificationPipeFDs_[1]; }
Jake Farrellb0d95602011-12-06 01:17:26 +0000760
761 // Returns the read-fd for task complete notifications.
Roger Meier12d70532011-12-14 23:35:28 +0000762 evutil_socket_t getNotificationRecvFD() const { return notificationPipeFDs_[0]; }
Jake Farrellb0d95602011-12-06 01:17:26 +0000763
764 // Returns the actual thread object associated with this IO thread.
cyy316723a2019-01-05 16:35:14 +0800765 std::shared_ptr<Thread> getThread() const { return thread_; }
Jake Farrellb0d95602011-12-06 01:17:26 +0000766
767 // Sets the actual thread object associated with this IO thread.
cyy316723a2019-01-05 16:35:14 +0800768 void setThread(const std::shared_ptr<Thread>& t) { thread_ = t; }
Jake Farrellb0d95602011-12-06 01:17:26 +0000769
770 // Used by TConnection objects to indicate processing has finished.
771 bool notify(TNonblockingServer::TConnection* conn);
772
773 // Enters the event loop and does not return until a call to stop().
Sebastian Zenker042580f2019-01-29 15:48:12 +0100774 void run() override;
Jake Farrellb0d95602011-12-06 01:17:26 +0000775
776 // Exits the event loop as soon as possible.
777 void stop();
778
779 // Ensures that the event-loop thread is fully finished and shut down.
780 void join();
781
Roger Meier6f2a5032013-07-08 23:35:25 +0200782 /// Registers the events for the notification & listen sockets
783 void registerEvents();
784
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100785private:
David Reiss01fe1532010-03-09 05:19:25 +0000786 /**
Jake Farrellb0d95602011-12-06 01:17:26 +0000787 * C-callable event handler for signaling task completion. Provides a
788 * callback that libevent can understand that will read a connection
789 * object's address from a pipe and call connection->transition() for
790 * that object.
David Reiss068f4162010-03-09 05:19:45 +0000791 *
Jake Farrellb0d95602011-12-06 01:17:26 +0000792 * @param fd the descriptor the event occurred on.
David Reiss068f4162010-03-09 05:19:45 +0000793 */
Roger Meier12d70532011-12-14 23:35:28 +0000794 static void notifyHandler(evutil_socket_t fd, short which, void* v);
David Reiss068f4162010-03-09 05:19:45 +0000795
796 /**
David Reiss01fe1532010-03-09 05:19:25 +0000797 * C-callable event handler for listener events. Provides a callback
798 * that libevent can understand which invokes server->handleEvent().
799 *
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +0100800 * @param fd the descriptor the event occurred on.
David Reiss01fe1532010-03-09 05:19:25 +0000801 * @param which the flags associated with the event.
802 * @param v void* callback arg where we placed TNonblockingServer's "this".
803 */
Jake Farrellb0d95602011-12-06 01:17:26 +0000804 static void listenHandler(evutil_socket_t fd, short which, void* v) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000805 ((TNonblockingServer*)v)->handleEvent(fd, which);
806 }
807
Jake Farrellb0d95602011-12-06 01:17:26 +0000808 /// Exits the loop ASAP in case of shutdown or error.
809 void breakLoop(bool error);
Mark Slee79b16942007-11-26 19:05:29 +0000810
David Reiss01fe1532010-03-09 05:19:25 +0000811 /// Create the pipe used to notify I/O process of task completion.
812 void createNotificationPipe();
813
Jake Farrellb0d95602011-12-06 01:17:26 +0000814 /// Unregisters our events for notification and listen sockets.
815 void cleanupEvents();
David Reiss01fe1532010-03-09 05:19:25 +0000816
Jake Farrellb0d95602011-12-06 01:17:26 +0000817 /// Sets (or clears) high priority scheduling status for the current thread.
818 void setCurrentThreadHighPriority(bool value);
David Reiss01fe1532010-03-09 05:19:25 +0000819
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100820private:
Jake Farrellb0d95602011-12-06 01:17:26 +0000821 /// associated server
822 TNonblockingServer* server_;
Mark Slee79b16942007-11-26 19:05:29 +0000823
Jake Farrellb0d95602011-12-06 01:17:26 +0000824 /// thread number (for debugging).
825 const int number_;
Bryan Duxbury76c43682011-08-24 21:26:48 +0000826
Jake Farrellb0d95602011-12-06 01:17:26 +0000827 /// The actual physical thread id.
Roger Meier12d70532011-12-14 23:35:28 +0000828 Thread::id_t threadId_;
Jake Farrellb0d95602011-12-06 01:17:26 +0000829
830 /// If listenSocket_ >= 0, adds an event on the event_base to accept conns
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -0400831 THRIFT_SOCKET listenSocket_;
Jake Farrellb0d95602011-12-06 01:17:26 +0000832
833 /// Sets a high scheduling priority when running
834 bool useHighPriority_;
835
836 /// pointer to eventbase to be used for looping
837 event_base* eventBase_;
838
Roger Meier6f2a5032013-07-08 23:35:25 +0200839 /// Set to true if this class is responsible for freeing the event base
840 /// memory.
841 bool ownEventBase_;
842
Jake Farrellb0d95602011-12-06 01:17:26 +0000843 /// Used with eventBase_ for connection events (only in listener thread)
844 struct event serverEvent_;
845
846 /// Used with eventBase_ for task completion notification
847 struct event notificationEvent_;
848
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100849 /// File descriptors for pipe used for task completion notification.
Roger Meier12d70532011-12-14 23:35:28 +0000850 evutil_socket_t notificationPipeFDs_[2];
Jake Farrellb0d95602011-12-06 01:17:26 +0000851
852 /// Actual IO Thread
cyy316723a2019-01-05 16:35:14 +0800853 std::shared_ptr<Thread> thread_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000854};
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100855}
856}
857} // apache::thrift::server
Mark Slee2f6404d2006-10-10 01:37:40 +0000858
Jake Farrellb0d95602011-12-06 01:17:26 +0000859#endif // #ifndef _THRIFT_SERVER_TNONBLOCKINGSERVER_H_