blob: 864452669ed78548a7d0f5c2d7e0cb17b50b1765 [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#include "TNonblockingServer.h"
David Reisse11f3072008-10-07 21:39:19 +00008#include <concurrency/Exception.h>
Mark Slee2f6404d2006-10-10 01:37:40 +00009
Mark Sleee02385b2007-06-09 01:21:16 +000010#include <iostream>
Mark Slee2f6404d2006-10-10 01:37:40 +000011#include <sys/socket.h>
12#include <netinet/in.h>
13#include <netinet/tcp.h>
Mark Sleefb4b5142007-11-20 01:27:08 +000014#include <netdb.h>
Mark Slee2f6404d2006-10-10 01:37:40 +000015#include <fcntl.h>
16#include <errno.h>
17#include <assert.h>
18
T Jake Lucianib5e62212009-01-31 22:36:20 +000019namespace apache { namespace thrift { namespace server {
Mark Slee2f6404d2006-10-10 01:37:40 +000020
T Jake Lucianib5e62212009-01-31 22:36:20 +000021using namespace apache::thrift::protocol;
22using namespace apache::thrift::transport;
23using namespace apache::thrift::concurrency;
Mark Sleee02385b2007-06-09 01:21:16 +000024using namespace std;
25
26class TConnection::Task: public Runnable {
27 public:
28 Task(boost::shared_ptr<TProcessor> processor,
29 boost::shared_ptr<TProtocol> input,
30 boost::shared_ptr<TProtocol> output,
31 int taskHandle) :
32 processor_(processor),
33 input_(input),
34 output_(output),
35 taskHandle_(taskHandle) {}
36
37 void run() {
38 try {
39 while (processor_->process(input_, output_)) {
40 if (!input_->getTransport()->peek()) {
41 break;
42 }
43 }
44 } catch (TTransportException& ttx) {
David Reissa79e4882008-03-05 07:51:47 +000045 cerr << "TNonblockingServer client died: " << ttx.what() << endl;
Mark Sleee02385b2007-06-09 01:21:16 +000046 } catch (TException& x) {
David Reissa79e4882008-03-05 07:51:47 +000047 cerr << "TNonblockingServer exception: " << x.what() << endl;
Mark Sleee02385b2007-06-09 01:21:16 +000048 } catch (...) {
David Reissa79e4882008-03-05 07:51:47 +000049 cerr << "TNonblockingServer uncaught exception." << endl;
Mark Sleee02385b2007-06-09 01:21:16 +000050 }
Mark Slee79b16942007-11-26 19:05:29 +000051
Mark Sleee02385b2007-06-09 01:21:16 +000052 // Signal completion back to the libevent thread via a socketpair
53 int8_t b = 0;
54 if (-1 == send(taskHandle_, &b, sizeof(int8_t), 0)) {
David Reiss01e55c12008-07-13 22:18:51 +000055 GlobalOutput.perror("TNonblockingServer::Task: send ", errno);
Mark Sleee02385b2007-06-09 01:21:16 +000056 }
57 if (-1 == ::close(taskHandle_)) {
David Reiss01e55c12008-07-13 22:18:51 +000058 GlobalOutput.perror("TNonblockingServer::Task: close, possible resource leak ", errno);
Mark Sleee02385b2007-06-09 01:21:16 +000059 }
60 }
61
62 private:
63 boost::shared_ptr<TProcessor> processor_;
64 boost::shared_ptr<TProtocol> input_;
65 boost::shared_ptr<TProtocol> output_;
66 int taskHandle_;
67};
Mark Slee5ea15f92007-03-05 22:55:59 +000068
69void TConnection::init(int socket, short eventFlags, TNonblockingServer* s) {
Mark Slee2f6404d2006-10-10 01:37:40 +000070 socket_ = socket;
71 server_ = s;
72 appState_ = APP_INIT;
73 eventFlags_ = 0;
74
75 readBufferPos_ = 0;
76 readWant_ = 0;
77
78 writeBuffer_ = NULL;
79 writeBufferSize_ = 0;
80 writeBufferPos_ = 0;
81
82 socketState_ = SOCKET_RECV;
83 appState_ = APP_INIT;
Mark Slee79b16942007-11-26 19:05:29 +000084
Mark Sleee02385b2007-06-09 01:21:16 +000085 taskHandle_ = -1;
86
Mark Slee2f6404d2006-10-10 01:37:40 +000087 // Set flags, which also registers the event
88 setFlags(eventFlags);
Aditya Agarwal1ea90522007-01-19 02:02:12 +000089
Aditya Agarwal9abb0d62007-01-24 22:53:54 +000090 // get input/transports
91 factoryInputTransport_ = s->getInputTransportFactory()->getTransport(inputTransport_);
92 factoryOutputTransport_ = s->getOutputTransportFactory()->getTransport(outputTransport_);
Aditya Agarwal1ea90522007-01-19 02:02:12 +000093
94 // Create protocol
Aditya Agarwal9abb0d62007-01-24 22:53:54 +000095 inputProtocol_ = s->getInputProtocolFactory()->getProtocol(factoryInputTransport_);
96 outputProtocol_ = s->getOutputProtocolFactory()->getProtocol(factoryOutputTransport_);
Mark Slee2f6404d2006-10-10 01:37:40 +000097}
98
99void TConnection::workSocket() {
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000100 int flags=0, got=0, left=0, sent=0;
101 uint32_t fetch = 0;
Mark Slee2f6404d2006-10-10 01:37:40 +0000102
103 switch (socketState_) {
104 case SOCKET_RECV:
105 // It is an error to be in this state if we already have all the data
106 assert(readBufferPos_ < readWant_);
107
Mark Slee2f6404d2006-10-10 01:37:40 +0000108 // Double the buffer size until it is big enough
robert79511192006-12-20 19:25:38 +0000109 if (readWant_ > readBufferSize_) {
110 while (readWant_ > readBufferSize_) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000111 readBufferSize_ *= 2;
112 }
David Reissd7a16f42008-02-19 22:47:29 +0000113 readBuffer_ = (uint8_t*)std::realloc(readBuffer_, readBufferSize_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000114 if (readBuffer_ == NULL) {
boz6ded7752007-06-05 22:41:18 +0000115 GlobalOutput("TConnection::workSocket() realloc");
Mark Slee2f6404d2006-10-10 01:37:40 +0000116 close();
117 return;
118 }
119 }
120
121 // Read from the socket
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000122 fetch = readWant_ - readBufferPos_;
123 got = recv(socket_, readBuffer_ + readBufferPos_, fetch, 0);
Mark Slee79b16942007-11-26 19:05:29 +0000124
Mark Slee2f6404d2006-10-10 01:37:40 +0000125 if (got > 0) {
126 // Move along in the buffer
127 readBufferPos_ += got;
128
129 // Check that we did not overdo it
130 assert(readBufferPos_ <= readWant_);
Mark Slee79b16942007-11-26 19:05:29 +0000131
Mark Slee2f6404d2006-10-10 01:37:40 +0000132 // We are done reading, move onto the next state
133 if (readBufferPos_ == readWant_) {
134 transition();
135 }
136 return;
137 } else if (got == -1) {
138 // Blocking errors are okay, just move on
139 if (errno == EAGAIN || errno == EWOULDBLOCK) {
140 return;
141 }
142
143 if (errno != ECONNRESET) {
David Reiss01e55c12008-07-13 22:18:51 +0000144 GlobalOutput.perror("TConnection::workSocket() recv -1 ", errno);
Mark Slee2f6404d2006-10-10 01:37:40 +0000145 }
146 }
147
148 // Whenever we get down here it means a remote disconnect
149 close();
Mark Slee79b16942007-11-26 19:05:29 +0000150
Mark Slee2f6404d2006-10-10 01:37:40 +0000151 return;
152
153 case SOCKET_SEND:
154 // Should never have position past size
155 assert(writeBufferPos_ <= writeBufferSize_);
156
157 // If there is no data to send, then let us move on
158 if (writeBufferPos_ == writeBufferSize_) {
Mark Slee79b16942007-11-26 19:05:29 +0000159 GlobalOutput("WARNING: Send state with no data to send\n");
Mark Slee2f6404d2006-10-10 01:37:40 +0000160 transition();
161 return;
162 }
163
164 flags = 0;
165 #ifdef MSG_NOSIGNAL
166 // Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we
167 // check for the EPIPE return condition and close the socket in that case
168 flags |= MSG_NOSIGNAL;
169 #endif // ifdef MSG_NOSIGNAL
170
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000171 left = writeBufferSize_ - writeBufferPos_;
172 sent = send(socket_, writeBuffer_ + writeBufferPos_, left, flags);
Mark Slee2f6404d2006-10-10 01:37:40 +0000173
174 if (sent <= 0) {
175 // Blocking errors are okay, just move on
176 if (errno == EAGAIN || errno == EWOULDBLOCK) {
177 return;
178 }
179 if (errno != EPIPE) {
David Reiss01e55c12008-07-13 22:18:51 +0000180 GlobalOutput.perror("TConnection::workSocket() send -1 ", errno);
Mark Slee2f6404d2006-10-10 01:37:40 +0000181 }
182 close();
183 return;
184 }
185
186 writeBufferPos_ += sent;
187
188 // Did we overdo it?
189 assert(writeBufferPos_ <= writeBufferSize_);
190
Mark Slee79b16942007-11-26 19:05:29 +0000191 // We are done!
Mark Slee2f6404d2006-10-10 01:37:40 +0000192 if (writeBufferPos_ == writeBufferSize_) {
193 transition();
194 }
195
196 return;
197
198 default:
David Reiss01e55c12008-07-13 22:18:51 +0000199 GlobalOutput.printf("Shit Got Ill. Socket State %d", socketState_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000200 assert(0);
201 }
202}
203
204/**
205 * This is called when the application transitions from one state into
206 * another. This means that it has finished writing the data that it needed
207 * to, or finished receiving the data that it needed to.
208 */
209void TConnection::transition() {
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000210
211 int sz = 0;
212
Mark Slee2f6404d2006-10-10 01:37:40 +0000213 // Switch upon the state that we are currently in and move to a new state
214 switch (appState_) {
215
216 case APP_READ_REQUEST:
217 // We are done reading the request, package the read buffer into transport
218 // and get back some data from the dispatch function
219 inputTransport_->resetBuffer(readBuffer_, readBufferPos_);
220 outputTransport_->resetBuffer();
David Reiss52cb7a72008-06-30 21:40:35 +0000221 // Prepend four bytes of blank space to the buffer so we can
222 // write the frame size there later.
223 outputTransport_->getWritePtr(4);
224 outputTransport_->wroteBytes(4);
Mark Slee79b16942007-11-26 19:05:29 +0000225
Mark Sleee02385b2007-06-09 01:21:16 +0000226 if (server_->isThreadPoolProcessing()) {
227 // We are setting up a Task to do this work and we will wait on it
228 int sv[2];
229 if (-1 == socketpair(AF_LOCAL, SOCK_STREAM, 0, sv)) {
David Reiss01e55c12008-07-13 22:18:51 +0000230 GlobalOutput.perror("TConnection::socketpair() failed ", errno);
Mark Sleee02385b2007-06-09 01:21:16 +0000231 // Now we will fall through to the APP_WAIT_TASK block with no response
232 } else {
233 // Create task and dispatch to the thread manager
234 boost::shared_ptr<Runnable> task =
235 boost::shared_ptr<Runnable>(new Task(server_->getProcessor(),
236 inputProtocol_,
237 outputProtocol_,
238 sv[1]));
Mark Slee79b16942007-11-26 19:05:29 +0000239 // The application is now waiting on the task to finish
Mark Sleee02385b2007-06-09 01:21:16 +0000240 appState_ = APP_WAIT_TASK;
Mark Slee79b16942007-11-26 19:05:29 +0000241
242 // Create an event to be notified when the task finishes
Mark Sleee02385b2007-06-09 01:21:16 +0000243 event_set(&taskEvent_,
244 taskHandle_ = sv[0],
245 EV_READ,
246 TConnection::taskHandler,
247 this);
Mark Slee2f6404d2006-10-10 01:37:40 +0000248
Mark Slee79b16942007-11-26 19:05:29 +0000249 // Attach to the base
250 event_base_set(server_->getEventBase(), &taskEvent_);
251
Mark Sleee02385b2007-06-09 01:21:16 +0000252 // Add the event and start up the server
253 if (-1 == event_add(&taskEvent_, 0)) {
254 GlobalOutput("TNonblockingServer::serve(): coult not event_add");
255 return;
256 }
David Reisse11f3072008-10-07 21:39:19 +0000257 try {
258 server_->addTask(task);
259 } catch (IllegalStateException & ise) {
260 // The ThreadManager is not ready to handle any more tasks (it's probably shutting down).
David Reissc53a5942008-10-07 23:55:24 +0000261 GlobalOutput.printf("IllegalStateException: Server::process() %s", ise.what());
David Reisse11f3072008-10-07 21:39:19 +0000262 close();
263 }
Mark Slee402ee282007-08-23 01:43:20 +0000264
265 // Set this connection idle so that libevent doesn't process more
266 // data on it while we're still waiting for the threadmanager to
267 // finish this task
268 setIdle();
Mark Sleee02385b2007-06-09 01:21:16 +0000269 return;
270 }
271 } else {
272 try {
273 // Invoke the processor
274 server_->getProcessor()->process(inputProtocol_, outputProtocol_);
275 } catch (TTransportException &ttx) {
David Reiss01e55c12008-07-13 22:18:51 +0000276 GlobalOutput.printf("TTransportException: Server::process() %s", ttx.what());
Mark Sleee02385b2007-06-09 01:21:16 +0000277 close();
278 return;
279 } catch (TException &x) {
David Reiss01e55c12008-07-13 22:18:51 +0000280 GlobalOutput.printf("TException: Server::process() %s", x.what());
Mark Slee79b16942007-11-26 19:05:29 +0000281 close();
Mark Sleee02385b2007-06-09 01:21:16 +0000282 return;
283 } catch (...) {
David Reiss01e55c12008-07-13 22:18:51 +0000284 GlobalOutput.printf("Server::process() unknown exception");
Mark Sleee02385b2007-06-09 01:21:16 +0000285 close();
286 return;
287 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000288 }
289
Mark Slee402ee282007-08-23 01:43:20 +0000290 // Intentionally fall through here, the call to process has written into
291 // the writeBuffer_
292
Mark Sleee02385b2007-06-09 01:21:16 +0000293 case APP_WAIT_TASK:
294 // We have now finished processing a task and the result has been written
295 // into the outputTransport_, so we grab its contents and place them into
296 // the writeBuffer_ for actual writing by the libevent thread
297
Mark Slee2f6404d2006-10-10 01:37:40 +0000298 // Get the result of the operation
299 outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_);
300
301 // If the function call generated return data, then move into the send
302 // state and get going
David Reissaf787782008-07-03 20:29:34 +0000303 // 4 bytes were reserved for frame size
David Reiss52cb7a72008-06-30 21:40:35 +0000304 if (writeBufferSize_ > 4) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000305
306 // Move into write state
307 writeBufferPos_ = 0;
308 socketState_ = SOCKET_SEND;
Mark Slee92f00fb2006-10-25 01:28:17 +0000309
David Reissaf787782008-07-03 20:29:34 +0000310 // Put the frame size into the write buffer
311 int32_t frameSize = (int32_t)htonl(writeBufferSize_ - 4);
312 memcpy(writeBuffer_, &frameSize, 4);
Mark Slee2f6404d2006-10-10 01:37:40 +0000313
314 // Socket into write mode
David Reiss52cb7a72008-06-30 21:40:35 +0000315 appState_ = APP_SEND_RESULT;
Mark Slee2f6404d2006-10-10 01:37:40 +0000316 setWrite();
317
318 // Try to work the socket immediately
Mark Sleee02385b2007-06-09 01:21:16 +0000319 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000320
321 return;
322 }
323
324 // In this case, the request was asynchronous and we should fall through
325 // right back into the read frame header state
Mark Slee92f00fb2006-10-25 01:28:17 +0000326 goto LABEL_APP_INIT;
327
Mark Slee2f6404d2006-10-10 01:37:40 +0000328 case APP_SEND_RESULT:
329
330 // N.B.: We also intentionally fall through here into the INIT state!
331
Mark Slee92f00fb2006-10-25 01:28:17 +0000332 LABEL_APP_INIT:
Mark Slee2f6404d2006-10-10 01:37:40 +0000333 case APP_INIT:
334
335 // Clear write buffer variables
336 writeBuffer_ = NULL;
337 writeBufferPos_ = 0;
338 writeBufferSize_ = 0;
339
340 // Set up read buffer for getting 4 bytes
341 readBufferPos_ = 0;
342 readWant_ = 4;
343
344 // Into read4 state we go
345 socketState_ = SOCKET_RECV;
346 appState_ = APP_READ_FRAME_SIZE;
347
348 // Register read event
349 setRead();
David Reiss84e63ab2008-03-07 20:12:28 +0000350
Mark Slee2f6404d2006-10-10 01:37:40 +0000351 // Try to work the socket right away
Mark Sleee02385b2007-06-09 01:21:16 +0000352 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000353
354 return;
355
356 case APP_READ_FRAME_SIZE:
357 // We just read the request length, deserialize it
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000358 sz = *(int32_t*)readBuffer_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000359 sz = (int32_t)ntohl(sz);
360
361 if (sz <= 0) {
David Reiss01e55c12008-07-13 22:18:51 +0000362 GlobalOutput.printf("TConnection:transition() Negative frame size %d, remote side not using TFramedTransport?", sz);
Mark Slee2f6404d2006-10-10 01:37:40 +0000363 close();
364 return;
365 }
366
367 // Reset the read buffer
368 readWant_ = (uint32_t)sz;
369 readBufferPos_= 0;
370
371 // Move into read request state
372 appState_ = APP_READ_REQUEST;
373
374 // Work the socket right away
Mark Sleee02385b2007-06-09 01:21:16 +0000375 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000376
377 return;
378
379 default:
David Reiss01e55c12008-07-13 22:18:51 +0000380 GlobalOutput.printf("Totally Fucked. Application State %d", appState_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000381 assert(0);
382 }
383}
384
385void TConnection::setFlags(short eventFlags) {
386 // Catch the do nothing case
387 if (eventFlags_ == eventFlags) {
388 return;
389 }
390
391 // Delete a previously existing event
392 if (eventFlags_ != 0) {
393 if (event_del(&event_) == -1) {
boz6ded7752007-06-05 22:41:18 +0000394 GlobalOutput("TConnection::setFlags event_del");
Mark Slee2f6404d2006-10-10 01:37:40 +0000395 return;
396 }
397 }
398
399 // Update in memory structure
400 eventFlags_ = eventFlags;
401
Mark Slee402ee282007-08-23 01:43:20 +0000402 // Do not call event_set if there are no flags
403 if (!eventFlags_) {
404 return;
405 }
406
Mark Slee2f6404d2006-10-10 01:37:40 +0000407 /**
408 * event_set:
409 *
410 * Prepares the event structure &event to be used in future calls to
411 * event_add() and event_del(). The event will be prepared to call the
Mark Sleee02385b2007-06-09 01:21:16 +0000412 * eventHandler using the 'sock' file descriptor to monitor events.
Mark Slee2f6404d2006-10-10 01:37:40 +0000413 *
414 * The events can be either EV_READ, EV_WRITE, or both, indicating
415 * that an application can read or write from the file respectively without
416 * blocking.
417 *
Mark Sleee02385b2007-06-09 01:21:16 +0000418 * The eventHandler will be called with the file descriptor that triggered
Mark Slee2f6404d2006-10-10 01:37:40 +0000419 * the event and the type of event which will be one of: EV_TIMEOUT,
420 * EV_SIGNAL, EV_READ, EV_WRITE.
421 *
422 * The additional flag EV_PERSIST makes an event_add() persistent until
423 * event_del() has been called.
424 *
425 * Once initialized, the &event struct can be used repeatedly with
426 * event_add() and event_del() and does not need to be reinitialized unless
Mark Sleee02385b2007-06-09 01:21:16 +0000427 * the eventHandler and/or the argument to it are to be changed. However,
Mark Slee2f6404d2006-10-10 01:37:40 +0000428 * when an ev structure has been added to libevent using event_add() the
429 * structure must persist until the event occurs (assuming EV_PERSIST
430 * is not set) or is removed using event_del(). You may not reuse the same
431 * ev structure for multiple monitored descriptors; each descriptor needs
432 * its own ev.
433 */
434 event_set(&event_, socket_, eventFlags_, TConnection::eventHandler, this);
Mark Slee79b16942007-11-26 19:05:29 +0000435 event_base_set(server_->getEventBase(), &event_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000436
437 // Add the event
438 if (event_add(&event_, 0) == -1) {
Mark Slee17496a02007-08-02 06:37:40 +0000439 GlobalOutput("TConnection::setFlags(): could not event_add");
Mark Slee2f6404d2006-10-10 01:37:40 +0000440 }
441}
442
443/**
444 * Closes a connection
445 */
446void TConnection::close() {
447 // Delete the registered libevent
448 if (event_del(&event_) == -1) {
boz6ded7752007-06-05 22:41:18 +0000449 GlobalOutput("TConnection::close() event_del");
Mark Slee2f6404d2006-10-10 01:37:40 +0000450 }
451
452 // Close the socket
453 if (socket_ > 0) {
454 ::close(socket_);
455 }
456 socket_ = 0;
457
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000458 // close any factory produced transports
459 factoryInputTransport_->close();
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000460 factoryOutputTransport_->close();
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000461
Mark Slee2f6404d2006-10-10 01:37:40 +0000462 // Give this object back to the server that owns it
463 server_->returnConnection(this);
464}
465
466/**
467 * Creates a new connection either by reusing an object off the stack or
468 * by allocating a new one entirely
469 */
470TConnection* TNonblockingServer::createConnection(int socket, short flags) {
471 // Check the stack
472 if (connectionStack_.empty()) {
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000473 return new TConnection(socket, flags, this);
Mark Slee2f6404d2006-10-10 01:37:40 +0000474 } else {
475 TConnection* result = connectionStack_.top();
476 connectionStack_.pop();
477 result->init(socket, flags, this);
478 return result;
479 }
480}
481
482/**
483 * Returns a connection to the stack
484 */
485void TNonblockingServer::returnConnection(TConnection* connection) {
486 connectionStack_.push(connection);
487}
488
489/**
David Reissa79e4882008-03-05 07:51:47 +0000490 * Server socket had something happen. We accept all waiting client
491 * connections on fd and assign TConnection objects to handle those requests.
Mark Slee2f6404d2006-10-10 01:37:40 +0000492 */
493void TNonblockingServer::handleEvent(int fd, short which) {
494 // Make sure that libevent didn't fuck up the socket handles
495 assert(fd == serverSocket_);
Mark Slee79b16942007-11-26 19:05:29 +0000496
Mark Slee2f6404d2006-10-10 01:37:40 +0000497 // Server socket accepted a new connection
498 socklen_t addrLen;
499 struct sockaddr addr;
Mark Slee79b16942007-11-26 19:05:29 +0000500 addrLen = sizeof(addr);
501
Mark Slee2f6404d2006-10-10 01:37:40 +0000502 // Going to accept a new client socket
503 int clientSocket;
Mark Slee79b16942007-11-26 19:05:29 +0000504
Mark Slee2f6404d2006-10-10 01:37:40 +0000505 // Accept as many new clients as possible, even though libevent signaled only
506 // one, this helps us to avoid having to go back into the libevent engine so
507 // many times
508 while ((clientSocket = accept(fd, &addr, &addrLen)) != -1) {
509
510 // Explicitly set this socket to NONBLOCK mode
511 int flags;
512 if ((flags = fcntl(clientSocket, F_GETFL, 0)) < 0 ||
513 fcntl(clientSocket, F_SETFL, flags | O_NONBLOCK) < 0) {
David Reiss01e55c12008-07-13 22:18:51 +0000514 GlobalOutput.perror("thriftServerEventHandler: set O_NONBLOCK (fcntl) ", errno);
Mark Slee2f6404d2006-10-10 01:37:40 +0000515 close(clientSocket);
516 return;
517 }
518
519 // Create a new TConnection for this client socket.
520 TConnection* clientConnection =
521 createConnection(clientSocket, EV_READ | EV_PERSIST);
522
523 // Fail fast if we could not create a TConnection object
524 if (clientConnection == NULL) {
David Reiss01e55c12008-07-13 22:18:51 +0000525 GlobalOutput.printf("thriftServerEventHandler: failed TConnection factory");
Mark Slee2f6404d2006-10-10 01:37:40 +0000526 close(clientSocket);
527 return;
528 }
529
530 // Put this client connection into the proper state
531 clientConnection->transition();
532 }
Mark Slee79b16942007-11-26 19:05:29 +0000533
Mark Slee2f6404d2006-10-10 01:37:40 +0000534 // Done looping accept, now we have to make sure the error is due to
535 // blocking. Any other error is a problem
536 if (errno != EAGAIN && errno != EWOULDBLOCK) {
David Reiss01e55c12008-07-13 22:18:51 +0000537 GlobalOutput.perror("thriftServerEventHandler: accept() ", errno);
Mark Slee2f6404d2006-10-10 01:37:40 +0000538 }
539}
540
541/**
Mark Slee79b16942007-11-26 19:05:29 +0000542 * Creates a socket to listen on and binds it to the local port.
Mark Slee2f6404d2006-10-10 01:37:40 +0000543 */
Mark Slee79b16942007-11-26 19:05:29 +0000544void TNonblockingServer::listenSocket() {
545 int s;
Mark Sleefb4b5142007-11-20 01:27:08 +0000546 struct addrinfo hints, *res, *res0;
547 int error;
Mark Slee79b16942007-11-26 19:05:29 +0000548
Mark Sleefb4b5142007-11-20 01:27:08 +0000549 char port[sizeof("65536") + 1];
550 memset(&hints, 0, sizeof(hints));
551 hints.ai_family = PF_UNSPEC;
552 hints.ai_socktype = SOCK_STREAM;
Mark Slee256bdc42007-11-27 08:42:19 +0000553 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
Mark Sleefb4b5142007-11-20 01:27:08 +0000554 sprintf(port, "%d", port_);
555
556 // Wildcard address
557 error = getaddrinfo(NULL, port, &hints, &res0);
558 if (error) {
David Reiss9b209552008-04-08 06:26:05 +0000559 string errStr = "TNonblockingServer::serve() getaddrinfo " + string(gai_strerror(error));
560 GlobalOutput(errStr.c_str());
Mark Sleefb4b5142007-11-20 01:27:08 +0000561 return;
562 }
563
564 // Pick the ipv6 address first since ipv4 addresses can be mapped
565 // into ipv6 space.
566 for (res = res0; res; res = res->ai_next) {
567 if (res->ai_family == AF_INET6 || res->ai_next == NULL)
568 break;
569 }
570
Mark Slee2f6404d2006-10-10 01:37:40 +0000571 // Create the server socket
Mark Slee79b16942007-11-26 19:05:29 +0000572 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
573 if (s == -1) {
574 freeaddrinfo(res0);
575 throw TException("TNonblockingServer::serve() socket() -1");
Mark Slee2f6404d2006-10-10 01:37:40 +0000576 }
577
David Reiss13aea462008-06-10 22:56:04 +0000578 #ifdef IPV6_V6ONLY
579 int zero = 0;
580 if (-1 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero))) {
581 GlobalOutput("TServerSocket::listen() IPV6_V6ONLY");
582 }
583 #endif // #ifdef IPV6_V6ONLY
584
585
Mark Slee79b16942007-11-26 19:05:29 +0000586 int one = 1;
587
588 // Set reuseaddr to avoid 2MSL delay on server restart
589 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
590
591 if (bind(s, res->ai_addr, res->ai_addrlen) == -1) {
592 close(s);
593 freeaddrinfo(res0);
594 throw TException("TNonblockingServer::serve() bind");
595 }
596
597 // Done with the addr info
598 freeaddrinfo(res0);
599
600 // Set up this file descriptor for listening
601 listenSocket(s);
602}
603
604/**
605 * Takes a socket created by listenSocket() and sets various options on it
606 * to prepare for use in the server.
607 */
608void TNonblockingServer::listenSocket(int s) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000609 // Set socket to nonblocking mode
610 int flags;
Mark Slee79b16942007-11-26 19:05:29 +0000611 if ((flags = fcntl(s, F_GETFL, 0)) < 0 ||
612 fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
613 close(s);
614 throw TException("TNonblockingServer::serve() O_NONBLOCK");
Mark Slee2f6404d2006-10-10 01:37:40 +0000615 }
616
617 int one = 1;
618 struct linger ling = {0, 0};
Mark Slee2f6404d2006-10-10 01:37:40 +0000619
620 // Keepalive to ensure full result flushing
Mark Slee79b16942007-11-26 19:05:29 +0000621 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
Mark Slee2f6404d2006-10-10 01:37:40 +0000622
623 // Turn linger off to avoid hung sockets
Mark Slee79b16942007-11-26 19:05:29 +0000624 setsockopt(s, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
Mark Slee2f6404d2006-10-10 01:37:40 +0000625
626 // Set TCP nodelay if available, MAC OS X Hack
627 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
628 #ifndef TCP_NOPUSH
Mark Slee79b16942007-11-26 19:05:29 +0000629 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
Mark Slee2f6404d2006-10-10 01:37:40 +0000630 #endif
631
Mark Slee79b16942007-11-26 19:05:29 +0000632 if (listen(s, LISTEN_BACKLOG) == -1) {
633 close(s);
634 throw TException("TNonblockingServer::serve() listen");
Mark Slee2f6404d2006-10-10 01:37:40 +0000635 }
636
Mark Slee79b16942007-11-26 19:05:29 +0000637 // Cool, this socket is good to go, set it as the serverSocket_
638 serverSocket_ = s;
639}
640
641/**
642 * Register the core libevent events onto the proper base.
643 */
644void TNonblockingServer::registerEvents(event_base* base) {
645 assert(serverSocket_ != -1);
646 assert(!eventBase_);
647 eventBase_ = base;
648
649 // Print some libevent stats
David Reiss01e55c12008-07-13 22:18:51 +0000650 GlobalOutput.printf("libevent %s method %s",
Mark Slee79b16942007-11-26 19:05:29 +0000651 event_get_version(),
652 event_get_method());
Mark Slee2f6404d2006-10-10 01:37:40 +0000653
654 // Register the server event
Mark Slee79b16942007-11-26 19:05:29 +0000655 event_set(&serverEvent_,
Mark Slee2f6404d2006-10-10 01:37:40 +0000656 serverSocket_,
657 EV_READ | EV_PERSIST,
658 TNonblockingServer::eventHandler,
659 this);
Mark Slee79b16942007-11-26 19:05:29 +0000660 event_base_set(eventBase_, &serverEvent_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000661
662 // Add the event and start up the server
Mark Slee79b16942007-11-26 19:05:29 +0000663 if (-1 == event_add(&serverEvent_, 0)) {
664 throw TException("TNonblockingServer::serve(): coult not event_add");
Mark Slee2f6404d2006-10-10 01:37:40 +0000665 }
Mark Slee79b16942007-11-26 19:05:29 +0000666}
667
668/**
669 * Main workhorse function, starts up the server listening on a port and
670 * loops over the libevent handler.
671 */
672void TNonblockingServer::serve() {
673 // Init socket
674 listenSocket();
675
676 // Initialize libevent core
677 registerEvents(static_cast<event_base*>(event_init()));
Mark Slee2f6404d2006-10-10 01:37:40 +0000678
Mark Sleeb4d3e7b2007-11-28 01:51:43 +0000679 // Run the preServe event
680 if (eventHandler_ != NULL) {
681 eventHandler_->preServe();
dweatherford58985992007-06-19 23:10:19 +0000682 }
683
Mark Sleee02385b2007-06-09 01:21:16 +0000684 // Run libevent engine, never returns, invokes calls to eventHandler
Mark Slee79b16942007-11-26 19:05:29 +0000685 event_base_loop(eventBase_, 0);
Mark Slee2f6404d2006-10-10 01:37:40 +0000686}
687
T Jake Lucianib5e62212009-01-31 22:36:20 +0000688}}} // apache::thrift::server