blob: 84833067860e96fd7ffa618235ef7ebef817469f [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>
15#include <event.h>
16
Mark Slee79b16942007-11-26 19:05:29 +000017namespace facebook { namespace thrift { namespace server {
Mark Slee2f6404d2006-10-10 01:37:40 +000018
Mark Slee5ea15f92007-03-05 22:55:59 +000019using facebook::thrift::transport::TMemoryBuffer;
20using facebook::thrift::protocol::TProtocol;
Mark Sleee02385b2007-06-09 01:21:16 +000021using facebook::thrift::concurrency::Runnable;
22using facebook::thrift::concurrency::ThreadManager;
Mark Slee2f6404d2006-10-10 01:37:40 +000023
24// Forward declaration of class
25class TConnection;
26
27/**
28 * This is a non-blocking server in C++ for high performance that operates a
29 * single IO thread. It assumes that all incoming requests are framed with a
30 * 4 byte length indicator and writes out responses using the same framing.
31 *
32 * It does not use the TServerTransport framework, but rather has socket
33 * operations hardcoded for use with select.
34 *
35 * @author Mark Slee <mcslee@facebook.com>
36 */
37class TNonblockingServer : public TServer {
38 private:
39
40 // Listen backlog
41 static const int LISTEN_BACKLOG = 1024;
42
43 // Server socket file descriptor
44 int serverSocket_;
45
46 // Port server runs on
47 int port_;
48
Mark Slee92f00fb2006-10-25 01:28:17 +000049 // Whether to frame responses
50 bool frameResponses_;
51
Mark Sleee02385b2007-06-09 01:21:16 +000052 // For processing via thread pool, may be NULL
53 boost::shared_ptr<ThreadManager> threadManager_;
54
55 // Is thread pool processing?
56 bool threadPoolProcessing_;
57
Mark Slee79b16942007-11-26 19:05:29 +000058 // The event base for libevent
59 event_base* eventBase_;
60
61 // Event struct, for use with eventBase_
62 struct event serverEvent_;
63
Mark Slee2f6404d2006-10-10 01:37:40 +000064 /**
65 * This is a stack of all the objects that have been created but that
66 * are NOT currently in use. When we close a connection, we place it on this
67 * stack so that the object can be reused later, rather than freeing the
68 * memory and reallocating a new object later.
69 */
70 std::stack<TConnection*> connectionStack_;
71
72 void handleEvent(int fd, short which);
73
74 public:
Mark Slee5ea15f92007-03-05 22:55:59 +000075 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
Mark Sleef9373392007-01-24 19:41:57 +000076 int port) :
77 TServer(processor),
Mark Slee79b16942007-11-26 19:05:29 +000078 serverSocket_(-1),
Mark Sleef9373392007-01-24 19:41:57 +000079 port_(port),
Mark Slee8eceaea2007-06-15 01:43:21 +000080 frameResponses_(true),
dweatherford58985992007-06-19 23:10:19 +000081 threadPoolProcessing_(false),
Mark Sleeb4d3e7b2007-11-28 01:51:43 +000082 eventBase_(NULL) {}
Mark Sleef9373392007-01-24 19:41:57 +000083
Mark Slee79b16942007-11-26 19:05:29 +000084 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
Mark Slee5ea15f92007-03-05 22:55:59 +000085 boost::shared_ptr<TProtocolFactory> protocolFactory,
Mark Sleee02385b2007-06-09 01:21:16 +000086 int port,
87 boost::shared_ptr<ThreadManager> threadManager = boost::shared_ptr<ThreadManager>()) :
Aditya Agarwal9abb0d62007-01-24 22:53:54 +000088 TServer(processor),
Mark Slee79b16942007-11-26 19:05:29 +000089 serverSocket_(-1),
Mark Slee92f00fb2006-10-25 01:28:17 +000090 port_(port),
Mark Sleee02385b2007-06-09 01:21:16 +000091 frameResponses_(true),
Mark Slee79b16942007-11-26 19:05:29 +000092 threadManager_(threadManager),
Mark Sleeb4d3e7b2007-11-28 01:51:43 +000093 eventBase_(NULL) {
Mark Slee5ea15f92007-03-05 22:55:59 +000094 setInputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
95 setOutputTransportFactory(boost::shared_ptr<TTransportFactory>(new TTransportFactory()));
Aditya Agarwal9abb0d62007-01-24 22:53:54 +000096 setInputProtocolFactory(protocolFactory);
97 setOutputProtocolFactory(protocolFactory);
Mark Sleee02385b2007-06-09 01:21:16 +000098 setThreadManager(threadManager);
Aditya Agarwal9abb0d62007-01-24 22:53:54 +000099 }
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000100
Mark Slee5ea15f92007-03-05 22:55:59 +0000101 TNonblockingServer(boost::shared_ptr<TProcessor> processor,
102 boost::shared_ptr<TTransportFactory> inputTransportFactory,
103 boost::shared_ptr<TTransportFactory> outputTransportFactory,
104 boost::shared_ptr<TProtocolFactory> inputProtocolFactory,
105 boost::shared_ptr<TProtocolFactory> outputProtocolFactory,
Mark Sleee02385b2007-06-09 01:21:16 +0000106 int port,
107 boost::shared_ptr<ThreadManager> threadManager = boost::shared_ptr<ThreadManager>()) :
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000108 TServer(processor),
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000109 serverSocket_(0),
110 port_(port),
Mark Sleee02385b2007-06-09 01:21:16 +0000111 frameResponses_(true),
Mark Sleeb4d3e7b2007-11-28 01:51:43 +0000112 threadManager_(threadManager) {
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000113 setInputTransportFactory(inputTransportFactory);
114 setOutputTransportFactory(outputTransportFactory);
115 setInputProtocolFactory(inputProtocolFactory);
116 setOutputProtocolFactory(outputProtocolFactory);
Mark Sleee02385b2007-06-09 01:21:16 +0000117 setThreadManager(threadManager);
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000118 }
Mark Slee79b16942007-11-26 19:05:29 +0000119
Mark Slee2f6404d2006-10-10 01:37:40 +0000120 ~TNonblockingServer() {}
121
Mark Sleee02385b2007-06-09 01:21:16 +0000122 void setThreadManager(boost::shared_ptr<ThreadManager> threadManager) {
123 threadManager_ = threadManager;
124 threadPoolProcessing_ = (threadManager != NULL);
125 }
126
Mark Slee79b16942007-11-26 19:05:29 +0000127 bool isThreadPoolProcessing() const {
Mark Sleee02385b2007-06-09 01:21:16 +0000128 return threadPoolProcessing_;
129 }
130
131 void addTask(boost::shared_ptr<Runnable> task) {
132 threadManager_->add(task);
133 }
134
Mark Slee92f00fb2006-10-25 01:28:17 +0000135 void setFrameResponses(bool frameResponses) {
136 frameResponses_ = frameResponses;
137 }
138
Mark Slee79b16942007-11-26 19:05:29 +0000139 bool getFrameResponses() const {
Mark Slee92f00fb2006-10-25 01:28:17 +0000140 return frameResponses_;
141 }
142
Mark Slee79b16942007-11-26 19:05:29 +0000143 event_base* getEventBase() const {
144 return eventBase_;
145 }
146
Mark Slee2f6404d2006-10-10 01:37:40 +0000147 TConnection* createConnection(int socket, short flags);
148
149 void returnConnection(TConnection* connection);
150
151 static void eventHandler(int fd, short which, void* v) {
152 ((TNonblockingServer*)v)->handleEvent(fd, which);
153 }
154
Mark Slee79b16942007-11-26 19:05:29 +0000155 void listenSocket();
156
157 void listenSocket(int fd);
158
159 void registerEvents(event_base* base);
160
Mark Slee2f6404d2006-10-10 01:37:40 +0000161 void serve();
dweatherford58985992007-06-19 23:10:19 +0000162
Mark Slee2f6404d2006-10-10 01:37:40 +0000163};
164
165/**
166 * Two states for sockets, recv and send mode
167 */
168enum TSocketState {
169 SOCKET_RECV,
170 SOCKET_SEND
171};
172
173/**
174 * Four states for the nonblocking servr:
175 * 1) initialize
176 * 2) read 4 byte frame size
177 * 3) read frame of data
178 * 4) send back data (if any)
179 */
180enum TAppState {
181 APP_INIT,
182 APP_READ_FRAME_SIZE,
183 APP_READ_REQUEST,
Mark Sleee02385b2007-06-09 01:21:16 +0000184 APP_WAIT_TASK,
Mark Slee92f00fb2006-10-25 01:28:17 +0000185 APP_SEND_FRAME_SIZE,
Mark Slee2f6404d2006-10-10 01:37:40 +0000186 APP_SEND_RESULT
187};
188
189/**
190 * Represents a connection that is handled via libevent. This connection
191 * essentially encapsulates a socket that has some associated libevent state.
192 */
193class TConnection {
194 private:
195
Mark Sleee02385b2007-06-09 01:21:16 +0000196 class Task;
197
Mark Slee2f6404d2006-10-10 01:37:40 +0000198 // Server handle
199 TNonblockingServer* server_;
200
201 // Socket handle
202 int socket_;
203
204 // Libevent object
205 struct event event_;
206
207 // Libevent flags
208 short eventFlags_;
209
210 // Socket mode
211 TSocketState socketState_;
212
213 // Application state
214 TAppState appState_;
215
216 // How much data needed to read
217 uint32_t readWant_;
218
219 // Where in the read buffer are we
220 uint32_t readBufferPos_;
221
222 // Read buffer
223 uint8_t* readBuffer_;
224
225 // Read buffer size
226 uint32_t readBufferSize_;
227
228 // Write buffer
229 uint8_t* writeBuffer_;
Mark Slee79b16942007-11-26 19:05:29 +0000230
Mark Slee2f6404d2006-10-10 01:37:40 +0000231 // Write buffer size
232 uint32_t writeBufferSize_;
233
234 // How far through writing are we?
235 uint32_t writeBufferPos_;
236
Mark Slee92f00fb2006-10-25 01:28:17 +0000237 // Frame size
238 int32_t frameSize_;
239
Mark Sleee02385b2007-06-09 01:21:16 +0000240 // Task handle
241 int taskHandle_;
242
243 // Task event
244 struct event taskEvent_;
245
Mark Slee2f6404d2006-10-10 01:37:40 +0000246 // Transport to read from
Mark Slee5ea15f92007-03-05 22:55:59 +0000247 boost::shared_ptr<TMemoryBuffer> inputTransport_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000248
249 // Transport that processor writes to
Mark Slee5ea15f92007-03-05 22:55:59 +0000250 boost::shared_ptr<TMemoryBuffer> outputTransport_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000251
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000252 // extra transport generated by transport factory (e.g. BufferedRouterTransport)
Mark Slee5ea15f92007-03-05 22:55:59 +0000253 boost::shared_ptr<TTransport> factoryInputTransport_;
254 boost::shared_ptr<TTransport> factoryOutputTransport_;
Mark Slee4af6ed72006-10-25 19:02:49 +0000255
256 // Protocol decoder
Mark Slee5ea15f92007-03-05 22:55:59 +0000257 boost::shared_ptr<TProtocol> inputProtocol_;
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000258
259 // Protocol encoder
Mark Slee5ea15f92007-03-05 22:55:59 +0000260 boost::shared_ptr<TProtocol> outputProtocol_;
Mark Slee79b16942007-11-26 19:05:29 +0000261
Mark Slee2f6404d2006-10-10 01:37:40 +0000262 // Go into read mode
263 void setRead() {
264 setFlags(EV_READ | EV_PERSIST);
265 }
266
267 // Go into write mode
268 void setWrite() {
269 setFlags(EV_WRITE | EV_PERSIST);
270 }
271
Mark Slee402ee282007-08-23 01:43:20 +0000272 // Set socket idle
273 void setIdle() {
274 setFlags(0);
275 }
276
Mark Slee2f6404d2006-10-10 01:37:40 +0000277 // Set event flags
278 void setFlags(short eventFlags);
279
280 // Libevent handlers
281 void workSocket();
282
283 // Close this client and reset
284 void close();
285
286 public:
287
288 // Constructor
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000289 TConnection(int socket, short eventFlags, TNonblockingServer *s) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000290 readBuffer_ = (uint8_t*)malloc(1024);
291 if (readBuffer_ == NULL) {
Mark Sleeb9ff32a2006-11-16 01:00:24 +0000292 throw new facebook::thrift::TException("Out of memory.");
Mark Slee2f6404d2006-10-10 01:37:40 +0000293 }
294 readBufferSize_ = 1024;
Mark Slee79b16942007-11-26 19:05:29 +0000295
Mark Slee2f6404d2006-10-10 01:37:40 +0000296 // Allocate input and output tranpsorts
Mark Slee79b16942007-11-26 19:05:29 +0000297 // these only need to be allocated once per TConnection (they don't need to be
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000298 // reallocated on init() call)
Mark Slee5ea15f92007-03-05 22:55:59 +0000299 inputTransport_ = boost::shared_ptr<TMemoryBuffer>(new TMemoryBuffer(readBuffer_, readBufferSize_));
300 outputTransport_ = boost::shared_ptr<TMemoryBuffer>(new TMemoryBuffer());
Mark Slee79b16942007-11-26 19:05:29 +0000301
Mark Slee2f6404d2006-10-10 01:37:40 +0000302 init(socket, eventFlags, s);
303 }
304
305 // Initialize
306 void init(int socket, short eventFlags, TNonblockingServer *s);
307
308 // Transition into a new state
309 void transition();
310
311 // Handler wrapper
312 static void eventHandler(int fd, short which, void* v) {
Mark Sleee02385b2007-06-09 01:21:16 +0000313 assert(fd == ((TConnection*)v)->socket_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000314 ((TConnection*)v)->workSocket();
315 }
Mark Slee79b16942007-11-26 19:05:29 +0000316
Mark Sleee02385b2007-06-09 01:21:16 +0000317 // Handler wrapper for task block
318 static void taskHandler(int fd, short which, void* v) {
319 assert(fd == ((TConnection*)v)->taskHandle_);
320 if (-1 == ::close(((TConnection*)v)->taskHandle_)) {
321 GlobalOutput("TConnection::taskHandler close handle failed, resource leak");
322 }
323 ((TConnection*)v)->transition();
324 }
325
Mark Slee2f6404d2006-10-10 01:37:40 +0000326};
327
328}}} // facebook::thrift::server
329
330#endif // #ifndef _THRIFT_SERVER_TSIMPLESERVER_H_