blob: 7c6bc7fa039ee054c1af4918f6d8d30fea7c0713 [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
Mark Slee2f6404d2006-10-10 01:37:40 +000067 /**
68 * This is a stack of all the objects that have been created but that
69 * are NOT currently in use. When we close a connection, we place it on this
70 * stack so that the object can be reused later, rather than freeing the
71 * memory and reallocating a new object later.
72 */
73 std::stack<TConnection*> connectionStack_;
74
75 void handleEvent(int fd, short which);
76
77 public:
Mark Slee5ea15f92007-03-05 22:55:59 +000078 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
Mark Sleef9373392007-01-24 19:41:57 +000079 int port) :
80 TServer(processor),
Mark Slee79b16942007-11-26 19:05:29 +000081 serverSocket_(-1),
Mark Sleef9373392007-01-24 19:41:57 +000082 port_(port),
Mark Slee8eceaea2007-06-15 01:43:21 +000083 frameResponses_(true),
dweatherford58985992007-06-19 23:10:19 +000084 threadPoolProcessing_(false),
Mark Sleeb4d3e7b2007-11-28 01:51:43 +000085 eventBase_(NULL) {}
Mark Sleef9373392007-01-24 19:41:57 +000086
Mark Slee79b16942007-11-26 19:05:29 +000087 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
Mark Slee5ea15f92007-03-05 22:55:59 +000088 boost::shared_ptr<TProtocolFactory> protocolFactory,
Mark Sleee02385b2007-06-09 01:21:16 +000089 int port,
90 boost::shared_ptr<ThreadManager> threadManager = boost::shared_ptr<ThreadManager>()) :
Aditya Agarwal9abb0d62007-01-24 22:53:54 +000091 TServer(processor),
Mark Slee79b16942007-11-26 19:05:29 +000092 serverSocket_(-1),
Mark Slee92f00fb2006-10-25 01:28:17 +000093 port_(port),
Mark Sleee02385b2007-06-09 01:21:16 +000094 frameResponses_(true),
Mark Slee79b16942007-11-26 19:05:29 +000095 threadManager_(threadManager),
Mark Sleeb4d3e7b2007-11-28 01:51:43 +000096 eventBase_(NULL) {
Mark Slee5ea15f92007-03-05 22:55:59 +000097 setInputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
98 setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
Aditya Agarwal9abb0d62007-01-24 22:53:54 +000099 setInputProtocolFactory(protocolFactory);
100 setOutputProtocolFactory(protocolFactory);
Mark Sleee02385b2007-06-09 01:21:16 +0000101 setThreadManager(threadManager);
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000102 }
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000103
Mark Slee5ea15f92007-03-05 22:55:59 +0000104 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
105 boost::shared_ptr<TTransportFactory> inputTransportFactory,
106 boost::shared_ptr<TTransportFactory> outputTransportFactory,
107 boost::shared_ptr<TProtocolFactory> inputProtocolFactory,
108 boost::shared_ptr<TProtocolFactory> outputProtocolFactory,
Mark Sleee02385b2007-06-09 01:21:16 +0000109 int port,
110 boost::shared_ptr<ThreadManager> threadManager = boost::shared_ptr<ThreadManager>()) :
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000111 TServer(processor),
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000112 serverSocket_(0),
113 port_(port),
Mark Sleee02385b2007-06-09 01:21:16 +0000114 frameResponses_(true),
Mark Slee5d1784a2007-12-05 23:20:54 +0000115 threadManager_(threadManager),
116 eventBase_(NULL) {
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000117 setInputTransportFactory(inputTransportFactory);
118 setOutputTransportFactory(outputTransportFactory);
119 setInputProtocolFactory(inputProtocolFactory);
120 setOutputProtocolFactory(outputProtocolFactory);
Mark Sleee02385b2007-06-09 01:21:16 +0000121 setThreadManager(threadManager);
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000122 }
Mark Slee79b16942007-11-26 19:05:29 +0000123
Mark Slee2f6404d2006-10-10 01:37:40 +0000124 ~TNonblockingServer() {}
125
Mark Sleee02385b2007-06-09 01:21:16 +0000126 void setThreadManager(boost::shared_ptr<ThreadManager> threadManager) {
127 threadManager_ = threadManager;
128 threadPoolProcessing_ = (threadManager != NULL);
129 }
130
Mark Slee79b16942007-11-26 19:05:29 +0000131 bool isThreadPoolProcessing() const {
Mark Sleee02385b2007-06-09 01:21:16 +0000132 return threadPoolProcessing_;
133 }
134
135 void addTask(boost::shared_ptr<Runnable> task) {
136 threadManager_->add(task);
137 }
138
Mark Slee92f00fb2006-10-25 01:28:17 +0000139 void setFrameResponses(bool frameResponses) {
140 frameResponses_ = frameResponses;
141 }
142
Mark Slee79b16942007-11-26 19:05:29 +0000143 bool getFrameResponses() const {
Mark Slee92f00fb2006-10-25 01:28:17 +0000144 return frameResponses_;
145 }
146
Mark Slee79b16942007-11-26 19:05:29 +0000147 event_base* getEventBase() const {
148 return eventBase_;
149 }
150
Mark Slee2f6404d2006-10-10 01:37:40 +0000151 TConnection* createConnection(int socket, short flags);
152
153 void returnConnection(TConnection* connection);
154
155 static void eventHandler(int fd, short which, void* v) {
156 ((TNonblockingServer*)v)->handleEvent(fd, which);
157 }
158
Mark Slee79b16942007-11-26 19:05:29 +0000159 void listenSocket();
160
161 void listenSocket(int fd);
162
163 void registerEvents(event_base* base);
164
Mark Slee2f6404d2006-10-10 01:37:40 +0000165 void serve();
dweatherford58985992007-06-19 23:10:19 +0000166
Mark Slee2f6404d2006-10-10 01:37:40 +0000167};
168
169/**
170 * Two states for sockets, recv and send mode
171 */
172enum TSocketState {
173 SOCKET_RECV,
174 SOCKET_SEND
175};
176
177/**
178 * Four states for the nonblocking servr:
179 * 1) initialize
180 * 2) read 4 byte frame size
181 * 3) read frame of data
182 * 4) send back data (if any)
183 */
184enum TAppState {
185 APP_INIT,
186 APP_READ_FRAME_SIZE,
187 APP_READ_REQUEST,
Mark Sleee02385b2007-06-09 01:21:16 +0000188 APP_WAIT_TASK,
Mark Slee92f00fb2006-10-25 01:28:17 +0000189 APP_SEND_FRAME_SIZE,
Mark Slee2f6404d2006-10-10 01:37:40 +0000190 APP_SEND_RESULT
191};
192
193/**
194 * Represents a connection that is handled via libevent. This connection
195 * essentially encapsulates a socket that has some associated libevent state.
196 */
197class TConnection {
198 private:
199
Mark Sleee02385b2007-06-09 01:21:16 +0000200 class Task;
201
Mark Slee2f6404d2006-10-10 01:37:40 +0000202 // Server handle
203 TNonblockingServer* server_;
204
205 // Socket handle
206 int socket_;
207
208 // Libevent object
209 struct event event_;
210
211 // Libevent flags
212 short eventFlags_;
213
214 // Socket mode
215 TSocketState socketState_;
216
217 // Application state
218 TAppState appState_;
219
220 // How much data needed to read
221 uint32_t readWant_;
222
223 // Where in the read buffer are we
224 uint32_t readBufferPos_;
225
226 // Read buffer
227 uint8_t* readBuffer_;
228
229 // Read buffer size
230 uint32_t readBufferSize_;
231
232 // Write buffer
233 uint8_t* writeBuffer_;
Mark Slee79b16942007-11-26 19:05:29 +0000234
Mark Slee2f6404d2006-10-10 01:37:40 +0000235 // Write buffer size
236 uint32_t writeBufferSize_;
237
238 // How far through writing are we?
239 uint32_t writeBufferPos_;
240
Mark Slee92f00fb2006-10-25 01:28:17 +0000241 // Frame size
242 int32_t frameSize_;
243
Mark Sleee02385b2007-06-09 01:21:16 +0000244 // Task handle
245 int taskHandle_;
246
247 // Task event
248 struct event taskEvent_;
249
Mark Slee2f6404d2006-10-10 01:37:40 +0000250 // Transport to read from
Mark Slee5ea15f92007-03-05 22:55:59 +0000251 boost::shared_ptr<TMemoryBuffer> inputTransport_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000252
253 // Transport that processor writes to
Mark Slee5ea15f92007-03-05 22:55:59 +0000254 boost::shared_ptr<TMemoryBuffer> outputTransport_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000255
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000256 // extra transport generated by transport factory (e.g. BufferedRouterTransport)
Mark Slee5ea15f92007-03-05 22:55:59 +0000257 boost::shared_ptr<TTransport> factoryInputTransport_;
258 boost::shared_ptr<TTransport> factoryOutputTransport_;
Mark Slee4af6ed72006-10-25 19:02:49 +0000259
260 // Protocol decoder
Mark Slee5ea15f92007-03-05 22:55:59 +0000261 boost::shared_ptr<TProtocol> inputProtocol_;
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000262
263 // Protocol encoder
Mark Slee5ea15f92007-03-05 22:55:59 +0000264 boost::shared_ptr<TProtocol> outputProtocol_;
Mark Slee79b16942007-11-26 19:05:29 +0000265
Mark Slee2f6404d2006-10-10 01:37:40 +0000266 // Go into read mode
267 void setRead() {
268 setFlags(EV_READ | EV_PERSIST);
269 }
270
271 // Go into write mode
272 void setWrite() {
273 setFlags(EV_WRITE | EV_PERSIST);
274 }
275
Mark Slee402ee282007-08-23 01:43:20 +0000276 // Set socket idle
277 void setIdle() {
278 setFlags(0);
279 }
280
Mark Slee2f6404d2006-10-10 01:37:40 +0000281 // Set event flags
282 void setFlags(short eventFlags);
283
284 // Libevent handlers
285 void workSocket();
286
287 // Close this client and reset
288 void close();
289
290 public:
291
292 // Constructor
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000293 TConnection(int socket, short eventFlags, TNonblockingServer *s) {
David Reissd7a16f42008-02-19 22:47:29 +0000294 readBuffer_ = (uint8_t*)std::malloc(1024);
Mark Slee2f6404d2006-10-10 01:37:40 +0000295 if (readBuffer_ == NULL) {
Mark Sleeb9ff32a2006-11-16 01:00:24 +0000296 throw new facebook::thrift::TException("Out of memory.");
Mark Slee2f6404d2006-10-10 01:37:40 +0000297 }
298 readBufferSize_ = 1024;
Mark Slee79b16942007-11-26 19:05:29 +0000299
Mark Slee2f6404d2006-10-10 01:37:40 +0000300 // Allocate input and output tranpsorts
Mark Slee79b16942007-11-26 19:05:29 +0000301 // these only need to be allocated once per TConnection (they don't need to be
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000302 // reallocated on init() call)
Mark Slee5ea15f92007-03-05 22:55:59 +0000303 inputTransport_ = boost::shared_ptr<TMemoryBuffer>(new TMemoryBuffer(readBuffer_, readBufferSize_));
304 outputTransport_ = boost::shared_ptr<TMemoryBuffer>(new TMemoryBuffer());
Mark Slee79b16942007-11-26 19:05:29 +0000305
Mark Slee2f6404d2006-10-10 01:37:40 +0000306 init(socket, eventFlags, s);
307 }
308
309 // Initialize
310 void init(int socket, short eventFlags, TNonblockingServer *s);
311
312 // Transition into a new state
313 void transition();
314
315 // Handler wrapper
Mark Sleea8de4892008-02-09 00:02:26 +0000316 static void eventHandler(int fd, short /* which */, void* v) {
Mark Sleee02385b2007-06-09 01:21:16 +0000317 assert(fd == ((TConnection*)v)->socket_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000318 ((TConnection*)v)->workSocket();
319 }
Mark Slee79b16942007-11-26 19:05:29 +0000320
Mark Sleee02385b2007-06-09 01:21:16 +0000321 // Handler wrapper for task block
Mark Sleea8de4892008-02-09 00:02:26 +0000322 static void taskHandler(int fd, short /* which */, void* v) {
Mark Sleee02385b2007-06-09 01:21:16 +0000323 assert(fd == ((TConnection*)v)->taskHandle_);
324 if (-1 == ::close(((TConnection*)v)->taskHandle_)) {
David Reiss9b209552008-04-08 06:26:05 +0000325 std::string errStr = "TConnection::taskHandler close handle failed, resource leak " + TOutput::strerror_s(errno);
326 GlobalOutput(errStr.c_str());
Mark Sleee02385b2007-06-09 01:21:16 +0000327 }
328 ((TConnection*)v)->transition();
329 }
330
Mark Slee2f6404d2006-10-10 01:37:40 +0000331};
332
333}}} // facebook::thrift::server
334
335#endif // #ifndef _THRIFT_SERVER_TSIMPLESERVER_H_