blob: 0c3c6d54a9bcb60c6c5756cb25b68252282e0215 [file] [log] [blame]
Mark Slee9f0c6512007-02-28 23:58:26 +00001// Copyright (c) 2006- Facebook
2// Distributed under the Thrift Software License
3//
4// See accompanying file LICENSE or visit the Thrift site at:
5// http://developers.facebook.com/thrift/
6
Mark Slee2f6404d2006-10-10 01:37:40 +00007#ifndef _THRIFT_SERVER_TNONBLOCKINGSERVER_H_
8#define _THRIFT_SERVER_TNONBLOCKINGSERVER_H_ 1
9
Mark Slee4af6ed72006-10-25 19:02:49 +000010#include <Thrift.h>
11#include <server/TServer.h>
12#include <transport/TTransportUtils.h>
Mark Sleee02385b2007-06-09 01:21:16 +000013#include <concurrency/ThreadManager.h>
Mark Slee2f6404d2006-10-10 01:37:40 +000014#include <stack>
David Reiss9b209552008-04-08 06:26:05 +000015#include <string>
16#include <errno.h>
David Reissd7a16f42008-02-19 22:47:29 +000017#include <cstdlib>
Mark Slee2f6404d2006-10-10 01:37:40 +000018#include <event.h>
19
Mark Slee79b16942007-11-26 19:05:29 +000020namespace facebook { namespace thrift { namespace server {
Mark Slee2f6404d2006-10-10 01:37:40 +000021
Mark Slee5ea15f92007-03-05 22:55:59 +000022using facebook::thrift::transport::TMemoryBuffer;
23using facebook::thrift::protocol::TProtocol;
Mark Sleee02385b2007-06-09 01:21:16 +000024using facebook::thrift::concurrency::Runnable;
25using facebook::thrift::concurrency::ThreadManager;
Mark Slee2f6404d2006-10-10 01:37:40 +000026
27// Forward declaration of class
28class TConnection;
29
30/**
31 * This is a non-blocking server in C++ for high performance that operates a
32 * single IO thread. It assumes that all incoming requests are framed with a
33 * 4 byte length indicator and writes out responses using the same framing.
34 *
35 * It does not use the TServerTransport framework, but rather has socket
36 * operations hardcoded for use with select.
37 *
38 * @author Mark Slee <mcslee@facebook.com>
39 */
40class TNonblockingServer : public TServer {
41 private:
42
43 // Listen backlog
44 static const int LISTEN_BACKLOG = 1024;
45
46 // Server socket file descriptor
47 int serverSocket_;
48
49 // Port server runs on
50 int port_;
51
Mark Slee92f00fb2006-10-25 01:28:17 +000052 // Whether to frame responses
53 bool frameResponses_;
54
Mark Sleee02385b2007-06-09 01:21:16 +000055 // For processing via thread pool, may be NULL
56 boost::shared_ptr<ThreadManager> threadManager_;
57
58 // Is thread pool processing?
59 bool threadPoolProcessing_;
60
Mark Slee79b16942007-11-26 19:05:29 +000061 // The event base for libevent
62 event_base* eventBase_;
63
64 // Event struct, for use with eventBase_
65 struct event serverEvent_;
66
David Reiss1997f102008-04-29 00:29:41 +000067 // Number of TConnection object we've created
68 size_t numTConnections_;
69
Mark Slee2f6404d2006-10-10 01:37:40 +000070 /**
71 * This is a stack of all the objects that have been created but that
72 * are NOT currently in use. When we close a connection, we place it on this
73 * stack so that the object can be reused later, rather than freeing the
74 * memory and reallocating a new object later.
75 */
76 std::stack<TConnection*> connectionStack_;
77
78 void handleEvent(int fd, short which);
79
80 public:
Mark Slee5ea15f92007-03-05 22:55:59 +000081 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
Mark Sleef9373392007-01-24 19:41:57 +000082 int port) :
83 TServer(processor),
Mark Slee79b16942007-11-26 19:05:29 +000084 serverSocket_(-1),
Mark Sleef9373392007-01-24 19:41:57 +000085 port_(port),
Mark Slee8eceaea2007-06-15 01:43:21 +000086 frameResponses_(true),
dweatherford58985992007-06-19 23:10:19 +000087 threadPoolProcessing_(false),
David Reiss1997f102008-04-29 00:29:41 +000088 eventBase_(NULL),
89 numTConnections_(0) {}
Mark Sleef9373392007-01-24 19:41:57 +000090
Mark Slee79b16942007-11-26 19:05:29 +000091 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
Mark Slee5ea15f92007-03-05 22:55:59 +000092 boost::shared_ptr<TProtocolFactory> protocolFactory,
Mark Sleee02385b2007-06-09 01:21:16 +000093 int port,
94 boost::shared_ptr<ThreadManager> threadManager = boost::shared_ptr<ThreadManager>()) :
Aditya Agarwal9abb0d62007-01-24 22:53:54 +000095 TServer(processor),
Mark Slee79b16942007-11-26 19:05:29 +000096 serverSocket_(-1),
Mark Slee92f00fb2006-10-25 01:28:17 +000097 port_(port),
Mark Sleee02385b2007-06-09 01:21:16 +000098 frameResponses_(true),
Mark Slee79b16942007-11-26 19:05:29 +000099 threadManager_(threadManager),
David Reiss1997f102008-04-29 00:29:41 +0000100 eventBase_(NULL),
101 numTConnections_(0) {
Mark Slee5ea15f92007-03-05 22:55:59 +0000102 setInputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
103 setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000104 setInputProtocolFactory(protocolFactory);
105 setOutputProtocolFactory(protocolFactory);
Mark Sleee02385b2007-06-09 01:21:16 +0000106 setThreadManager(threadManager);
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000107 }
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000108
Mark Slee5ea15f92007-03-05 22:55:59 +0000109 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
110 boost::shared_ptr<TTransportFactory> inputTransportFactory,
111 boost::shared_ptr<TTransportFactory> outputTransportFactory,
112 boost::shared_ptr<TProtocolFactory> inputProtocolFactory,
113 boost::shared_ptr<TProtocolFactory> outputProtocolFactory,
Mark Sleee02385b2007-06-09 01:21:16 +0000114 int port,
115 boost::shared_ptr<ThreadManager> threadManager = boost::shared_ptr<ThreadManager>()) :
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000116 TServer(processor),
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000117 serverSocket_(0),
118 port_(port),
Mark Sleee02385b2007-06-09 01:21:16 +0000119 frameResponses_(true),
Mark Slee5d1784a2007-12-05 23:20:54 +0000120 threadManager_(threadManager),
David Reiss1997f102008-04-29 00:29:41 +0000121 eventBase_(NULL),
122 numTConnections_(0) {
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000123 setInputTransportFactory(inputTransportFactory);
124 setOutputTransportFactory(outputTransportFactory);
125 setInputProtocolFactory(inputProtocolFactory);
126 setOutputProtocolFactory(outputProtocolFactory);
Mark Sleee02385b2007-06-09 01:21:16 +0000127 setThreadManager(threadManager);
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000128 }
Mark Slee79b16942007-11-26 19:05:29 +0000129
Mark Slee2f6404d2006-10-10 01:37:40 +0000130 ~TNonblockingServer() {}
131
Mark Sleee02385b2007-06-09 01:21:16 +0000132 void setThreadManager(boost::shared_ptr<ThreadManager> threadManager) {
133 threadManager_ = threadManager;
134 threadPoolProcessing_ = (threadManager != NULL);
135 }
136
David Reiss1997f102008-04-29 00:29:41 +0000137 boost::shared_ptr<ThreadManager> getThreadManager() {
138 return threadManager_;
139 }
140
Mark Slee79b16942007-11-26 19:05:29 +0000141 bool isThreadPoolProcessing() const {
Mark Sleee02385b2007-06-09 01:21:16 +0000142 return threadPoolProcessing_;
143 }
144
145 void addTask(boost::shared_ptr<Runnable> task) {
146 threadManager_->add(task);
147 }
148
Mark Slee92f00fb2006-10-25 01:28:17 +0000149 void setFrameResponses(bool frameResponses) {
150 frameResponses_ = frameResponses;
151 }
152
Mark Slee79b16942007-11-26 19:05:29 +0000153 bool getFrameResponses() const {
Mark Slee92f00fb2006-10-25 01:28:17 +0000154 return frameResponses_;
155 }
156
Mark Slee79b16942007-11-26 19:05:29 +0000157 event_base* getEventBase() const {
158 return eventBase_;
159 }
160
David Reiss1997f102008-04-29 00:29:41 +0000161 void incrementNumConnections(size_t incr=1) {
162 numTConnections_ += incr;
163 }
164
165 size_t getNumConnections() {
166 return numTConnections_;
167 }
168
169 size_t getNumIdleConnections() {
170 return connectionStack_.size();
171 }
172
Mark Slee2f6404d2006-10-10 01:37:40 +0000173 TConnection* createConnection(int socket, short flags);
174
175 void returnConnection(TConnection* connection);
176
177 static void eventHandler(int fd, short which, void* v) {
178 ((TNonblockingServer*)v)->handleEvent(fd, which);
179 }
180
Mark Slee79b16942007-11-26 19:05:29 +0000181 void listenSocket();
182
183 void listenSocket(int fd);
184
185 void registerEvents(event_base* base);
186
Mark Slee2f6404d2006-10-10 01:37:40 +0000187 void serve();
188};
189
190/**
191 * Two states for sockets, recv and send mode
192 */
193enum TSocketState {
194 SOCKET_RECV,
195 SOCKET_SEND
196};
197
198/**
199 * Four states for the nonblocking servr:
200 * 1) initialize
201 * 2) read 4 byte frame size
202 * 3) read frame of data
203 * 4) send back data (if any)
204 */
205enum TAppState {
206 APP_INIT,
207 APP_READ_FRAME_SIZE,
208 APP_READ_REQUEST,
Mark Sleee02385b2007-06-09 01:21:16 +0000209 APP_WAIT_TASK,
Mark Slee92f00fb2006-10-25 01:28:17 +0000210 APP_SEND_FRAME_SIZE,
Mark Slee2f6404d2006-10-10 01:37:40 +0000211 APP_SEND_RESULT
212};
213
214/**
215 * Represents a connection that is handled via libevent. This connection
216 * essentially encapsulates a socket that has some associated libevent state.
217 */
218class TConnection {
219 private:
220
Mark Sleee02385b2007-06-09 01:21:16 +0000221 class Task;
222
Mark Slee2f6404d2006-10-10 01:37:40 +0000223 // Server handle
224 TNonblockingServer* server_;
225
226 // Socket handle
227 int socket_;
228
229 // Libevent object
230 struct event event_;
231
232 // Libevent flags
233 short eventFlags_;
234
235 // Socket mode
236 TSocketState socketState_;
237
238 // Application state
239 TAppState appState_;
240
241 // How much data needed to read
242 uint32_t readWant_;
243
244 // Where in the read buffer are we
245 uint32_t readBufferPos_;
246
247 // Read buffer
248 uint8_t* readBuffer_;
249
250 // Read buffer size
251 uint32_t readBufferSize_;
252
253 // Write buffer
254 uint8_t* writeBuffer_;
Mark Slee79b16942007-11-26 19:05:29 +0000255
Mark Slee2f6404d2006-10-10 01:37:40 +0000256 // Write buffer size
257 uint32_t writeBufferSize_;
258
259 // How far through writing are we?
260 uint32_t writeBufferPos_;
261
Mark Slee92f00fb2006-10-25 01:28:17 +0000262 // Frame size
263 int32_t frameSize_;
264
Mark Sleee02385b2007-06-09 01:21:16 +0000265 // Task handle
266 int taskHandle_;
267
268 // Task event
269 struct event taskEvent_;
270
Mark Slee2f6404d2006-10-10 01:37:40 +0000271 // Transport to read from
Mark Slee5ea15f92007-03-05 22:55:59 +0000272 boost::shared_ptr<TMemoryBuffer> inputTransport_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000273
274 // Transport that processor writes to
Mark Slee5ea15f92007-03-05 22:55:59 +0000275 boost::shared_ptr<TMemoryBuffer> outputTransport_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000276
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000277 // extra transport generated by transport factory (e.g. BufferedRouterTransport)
Mark Slee5ea15f92007-03-05 22:55:59 +0000278 boost::shared_ptr<TTransport> factoryInputTransport_;
279 boost::shared_ptr<TTransport> factoryOutputTransport_;
Mark Slee4af6ed72006-10-25 19:02:49 +0000280
281 // Protocol decoder
Mark Slee5ea15f92007-03-05 22:55:59 +0000282 boost::shared_ptr<TProtocol> inputProtocol_;
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000283
284 // Protocol encoder
Mark Slee5ea15f92007-03-05 22:55:59 +0000285 boost::shared_ptr<TProtocol> outputProtocol_;
Mark Slee79b16942007-11-26 19:05:29 +0000286
Mark Slee2f6404d2006-10-10 01:37:40 +0000287 // Go into read mode
288 void setRead() {
289 setFlags(EV_READ | EV_PERSIST);
290 }
291
292 // Go into write mode
293 void setWrite() {
294 setFlags(EV_WRITE | EV_PERSIST);
295 }
296
Mark Slee402ee282007-08-23 01:43:20 +0000297 // Set socket idle
298 void setIdle() {
299 setFlags(0);
300 }
301
Mark Slee2f6404d2006-10-10 01:37:40 +0000302 // Set event flags
303 void setFlags(short eventFlags);
304
305 // Libevent handlers
306 void workSocket();
307
308 // Close this client and reset
309 void close();
310
311 public:
312
313 // Constructor
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000314 TConnection(int socket, short eventFlags, TNonblockingServer *s) {
David Reissd7a16f42008-02-19 22:47:29 +0000315 readBuffer_ = (uint8_t*)std::malloc(1024);
Mark Slee2f6404d2006-10-10 01:37:40 +0000316 if (readBuffer_ == NULL) {
Mark Sleeb9ff32a2006-11-16 01:00:24 +0000317 throw new facebook::thrift::TException("Out of memory.");
Mark Slee2f6404d2006-10-10 01:37:40 +0000318 }
319 readBufferSize_ = 1024;
Mark Slee79b16942007-11-26 19:05:29 +0000320
Mark Slee2f6404d2006-10-10 01:37:40 +0000321 // Allocate input and output tranpsorts
Mark Slee79b16942007-11-26 19:05:29 +0000322 // these only need to be allocated once per TConnection (they don't need to be
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000323 // reallocated on init() call)
Mark Slee5ea15f92007-03-05 22:55:59 +0000324 inputTransport_ = boost::shared_ptr<TMemoryBuffer>(new TMemoryBuffer(readBuffer_, readBufferSize_));
325 outputTransport_ = boost::shared_ptr<TMemoryBuffer>(new TMemoryBuffer());
Mark Slee79b16942007-11-26 19:05:29 +0000326
Mark Slee2f6404d2006-10-10 01:37:40 +0000327 init(socket, eventFlags, s);
David Reiss1997f102008-04-29 00:29:41 +0000328 server_->incrementNumConnections();
329 }
330
331 ~TConnection() {
332 server_->incrementNumConnections(-1);
Mark Slee2f6404d2006-10-10 01:37:40 +0000333 }
334
335 // Initialize
336 void init(int socket, short eventFlags, TNonblockingServer *s);
337
338 // Transition into a new state
339 void transition();
340
341 // Handler wrapper
Mark Sleea8de4892008-02-09 00:02:26 +0000342 static void eventHandler(int fd, short /* which */, void* v) {
Mark Sleee02385b2007-06-09 01:21:16 +0000343 assert(fd == ((TConnection*)v)->socket_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000344 ((TConnection*)v)->workSocket();
345 }
Mark Slee79b16942007-11-26 19:05:29 +0000346
Mark Sleee02385b2007-06-09 01:21:16 +0000347 // Handler wrapper for task block
Mark Sleea8de4892008-02-09 00:02:26 +0000348 static void taskHandler(int fd, short /* which */, void* v) {
Mark Sleee02385b2007-06-09 01:21:16 +0000349 assert(fd == ((TConnection*)v)->taskHandle_);
350 if (-1 == ::close(((TConnection*)v)->taskHandle_)) {
David Reiss9b209552008-04-08 06:26:05 +0000351 std::string errStr = "TConnection::taskHandler close handle failed, resource leak " + TOutput::strerror_s(errno);
352 GlobalOutput(errStr.c_str());
Mark Sleee02385b2007-06-09 01:21:16 +0000353 }
354 ((TConnection*)v)->transition();
355 }
356
Mark Slee2f6404d2006-10-10 01:37:40 +0000357};
358
359}}} // facebook::thrift::server
360
361#endif // #ifndef _THRIFT_SERVER_TSIMPLESERVER_H_