blob: cd7951d34841c4361a475f886d158693da223b2c [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"
8
Mark Sleee02385b2007-06-09 01:21:16 +00009#include <iostream>
Mark Slee2f6404d2006-10-10 01:37:40 +000010#include <sys/socket.h>
11#include <netinet/in.h>
12#include <netinet/tcp.h>
Mark Sleefb4b5142007-11-20 01:27:08 +000013#include <netdb.h>
Mark Slee2f6404d2006-10-10 01:37:40 +000014#include <fcntl.h>
15#include <errno.h>
16#include <assert.h>
17
Mark Slee79b16942007-11-26 19:05:29 +000018namespace facebook { namespace thrift { namespace server {
Mark Slee2f6404d2006-10-10 01:37:40 +000019
Mark Slee5ea15f92007-03-05 22:55:59 +000020using namespace facebook::thrift::protocol;
21using namespace facebook::thrift::transport;
Mark Sleee02385b2007-06-09 01:21:16 +000022using namespace std;
23
24class TConnection::Task: public Runnable {
25 public:
26 Task(boost::shared_ptr<TProcessor> processor,
27 boost::shared_ptr<TProtocol> input,
28 boost::shared_ptr<TProtocol> output,
29 int taskHandle) :
30 processor_(processor),
31 input_(input),
32 output_(output),
33 taskHandle_(taskHandle) {}
34
35 void run() {
36 try {
37 while (processor_->process(input_, output_)) {
38 if (!input_->getTransport()->peek()) {
39 break;
40 }
41 }
42 } catch (TTransportException& ttx) {
David Reissa79e4882008-03-05 07:51:47 +000043 cerr << "TNonblockingServer client died: " << ttx.what() << endl;
Mark Sleee02385b2007-06-09 01:21:16 +000044 } catch (TException& x) {
David Reissa79e4882008-03-05 07:51:47 +000045 cerr << "TNonblockingServer exception: " << x.what() << endl;
Mark Sleee02385b2007-06-09 01:21:16 +000046 } catch (...) {
David Reissa79e4882008-03-05 07:51:47 +000047 cerr << "TNonblockingServer uncaught exception." << endl;
Mark Sleee02385b2007-06-09 01:21:16 +000048 }
Mark Slee79b16942007-11-26 19:05:29 +000049
Mark Sleee02385b2007-06-09 01:21:16 +000050 // Signal completion back to the libevent thread via a socketpair
51 int8_t b = 0;
52 if (-1 == send(taskHandle_, &b, sizeof(int8_t), 0)) {
David Reiss9b209552008-04-08 06:26:05 +000053 string errStr = "TNonblockingServer::Task: send " + TOutput::strerror_s(errno);
54 GlobalOutput(errStr.c_str());
Mark Sleee02385b2007-06-09 01:21:16 +000055 }
56 if (-1 == ::close(taskHandle_)) {
David Reiss9b209552008-04-08 06:26:05 +000057 string errStr = "TNonblockingServer::Task: close, possible resource leak " + TOutput::strerror_s(errno);
58 GlobalOutput(errStr.c_str());
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 Reiss9b209552008-04-08 06:26:05 +0000144 string errStr = "TConnection::workSocket() recv -1 " + TOutput::strerror_s(errno);
145 GlobalOutput(errStr.c_str());
Mark Slee2f6404d2006-10-10 01:37:40 +0000146 }
147 }
148
149 // Whenever we get down here it means a remote disconnect
150 close();
Mark Slee79b16942007-11-26 19:05:29 +0000151
Mark Slee2f6404d2006-10-10 01:37:40 +0000152 return;
153
154 case SOCKET_SEND:
155 // Should never have position past size
156 assert(writeBufferPos_ <= writeBufferSize_);
157
158 // If there is no data to send, then let us move on
159 if (writeBufferPos_ == writeBufferSize_) {
Mark Slee79b16942007-11-26 19:05:29 +0000160 GlobalOutput("WARNING: Send state with no data to send\n");
Mark Slee2f6404d2006-10-10 01:37:40 +0000161 transition();
162 return;
163 }
164
165 flags = 0;
166 #ifdef MSG_NOSIGNAL
167 // Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we
168 // check for the EPIPE return condition and close the socket in that case
169 flags |= MSG_NOSIGNAL;
170 #endif // ifdef MSG_NOSIGNAL
171
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000172 left = writeBufferSize_ - writeBufferPos_;
173 sent = send(socket_, writeBuffer_ + writeBufferPos_, left, flags);
Mark Slee2f6404d2006-10-10 01:37:40 +0000174
175 if (sent <= 0) {
176 // Blocking errors are okay, just move on
177 if (errno == EAGAIN || errno == EWOULDBLOCK) {
178 return;
179 }
180 if (errno != EPIPE) {
David Reiss9b209552008-04-08 06:26:05 +0000181 string errStr = "TConnection::workSocket() send -1 " + TOutput::strerror_s(errno);
182 GlobalOutput(errStr.c_str());
Mark Slee2f6404d2006-10-10 01:37:40 +0000183 }
184 close();
185 return;
186 }
187
188 writeBufferPos_ += sent;
189
190 // Did we overdo it?
191 assert(writeBufferPos_ <= writeBufferSize_);
192
Mark Slee79b16942007-11-26 19:05:29 +0000193 // We are done!
Mark Slee2f6404d2006-10-10 01:37:40 +0000194 if (writeBufferPos_ == writeBufferSize_) {
195 transition();
196 }
197
198 return;
199
200 default:
201 fprintf(stderr, "Shit Got Ill. Socket State %d\n", socketState_);
202 assert(0);
203 }
204}
205
206/**
207 * This is called when the application transitions from one state into
208 * another. This means that it has finished writing the data that it needed
209 * to, or finished receiving the data that it needed to.
210 */
211void TConnection::transition() {
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000212
213 int sz = 0;
214
Mark Slee2f6404d2006-10-10 01:37:40 +0000215 // Switch upon the state that we are currently in and move to a new state
216 switch (appState_) {
217
218 case APP_READ_REQUEST:
219 // We are done reading the request, package the read buffer into transport
220 // and get back some data from the dispatch function
221 inputTransport_->resetBuffer(readBuffer_, readBufferPos_);
222 outputTransport_->resetBuffer();
David Reiss52cb7a72008-06-30 21:40:35 +0000223 // Prepend four bytes of blank space to the buffer so we can
224 // write the frame size there later.
225 outputTransport_->getWritePtr(4);
226 outputTransport_->wroteBytes(4);
Mark Slee79b16942007-11-26 19:05:29 +0000227
Mark Sleee02385b2007-06-09 01:21:16 +0000228 if (server_->isThreadPoolProcessing()) {
229 // We are setting up a Task to do this work and we will wait on it
230 int sv[2];
231 if (-1 == socketpair(AF_LOCAL, SOCK_STREAM, 0, sv)) {
David Reiss9b209552008-04-08 06:26:05 +0000232 string errStr = "TConnection::socketpair() failed " + TOutput::strerror_s(errno);
233 GlobalOutput(errStr.c_str());
Mark Sleee02385b2007-06-09 01:21:16 +0000234 // Now we will fall through to the APP_WAIT_TASK block with no response
235 } else {
236 // Create task and dispatch to the thread manager
237 boost::shared_ptr<Runnable> task =
238 boost::shared_ptr<Runnable>(new Task(server_->getProcessor(),
239 inputProtocol_,
240 outputProtocol_,
241 sv[1]));
Mark Slee79b16942007-11-26 19:05:29 +0000242 // The application is now waiting on the task to finish
Mark Sleee02385b2007-06-09 01:21:16 +0000243 appState_ = APP_WAIT_TASK;
Mark Slee79b16942007-11-26 19:05:29 +0000244
245 // Create an event to be notified when the task finishes
Mark Sleee02385b2007-06-09 01:21:16 +0000246 event_set(&taskEvent_,
247 taskHandle_ = sv[0],
248 EV_READ,
249 TConnection::taskHandler,
250 this);
Mark Slee2f6404d2006-10-10 01:37:40 +0000251
Mark Slee79b16942007-11-26 19:05:29 +0000252 // Attach to the base
253 event_base_set(server_->getEventBase(), &taskEvent_);
254
Mark Sleee02385b2007-06-09 01:21:16 +0000255 // Add the event and start up the server
256 if (-1 == event_add(&taskEvent_, 0)) {
257 GlobalOutput("TNonblockingServer::serve(): coult not event_add");
258 return;
259 }
260 server_->addTask(task);
Mark Slee402ee282007-08-23 01:43:20 +0000261
262 // Set this connection idle so that libevent doesn't process more
263 // data on it while we're still waiting for the threadmanager to
264 // finish this task
265 setIdle();
Mark Sleee02385b2007-06-09 01:21:16 +0000266 return;
267 }
268 } else {
269 try {
270 // Invoke the processor
271 server_->getProcessor()->process(inputProtocol_, outputProtocol_);
272 } catch (TTransportException &ttx) {
273 fprintf(stderr, "TTransportException: Server::process() %s\n", ttx.what());
274 close();
275 return;
276 } catch (TException &x) {
277 fprintf(stderr, "TException: Server::process() %s\n", x.what());
Mark Slee79b16942007-11-26 19:05:29 +0000278 close();
Mark Sleee02385b2007-06-09 01:21:16 +0000279 return;
280 } catch (...) {
281 fprintf(stderr, "Server::process() unknown exception\n");
282 close();
283 return;
284 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000285 }
286
Mark Slee402ee282007-08-23 01:43:20 +0000287 // Intentionally fall through here, the call to process has written into
288 // the writeBuffer_
289
Mark Sleee02385b2007-06-09 01:21:16 +0000290 case APP_WAIT_TASK:
291 // We have now finished processing a task and the result has been written
292 // into the outputTransport_, so we grab its contents and place them into
293 // the writeBuffer_ for actual writing by the libevent thread
294
Mark Slee2f6404d2006-10-10 01:37:40 +0000295 // Get the result of the operation
296 outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_);
297
298 // If the function call generated return data, then move into the send
299 // state and get going
David Reiss52cb7a72008-06-30 21:40:35 +0000300 if (writeBufferSize_ > 4) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000301
302 // Move into write state
303 writeBufferPos_ = 0;
304 socketState_ = SOCKET_SEND;
Mark Slee92f00fb2006-10-25 01:28:17 +0000305
306 if (server_->getFrameResponses()) {
307 // Put the frame size into the write buffer
David Reiss52cb7a72008-06-30 21:40:35 +0000308 int32_t frameSize = (int32_t)htonl(writeBufferSize_ - 4);
309 memcpy(writeBuffer_, &frameSize, 4);
Mark Slee92f00fb2006-10-25 01:28:17 +0000310 } else {
311 // Go straight into sending the result, do not frame it
David Reiss52cb7a72008-06-30 21:40:35 +0000312 writeBufferPos_ = 4;
Mark Slee92f00fb2006-10-25 01:28:17 +0000313 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000314
315 // Socket into write mode
David Reiss52cb7a72008-06-30 21:40:35 +0000316 appState_ = APP_SEND_RESULT;
Mark Slee2f6404d2006-10-10 01:37:40 +0000317 setWrite();
318
319 // Try to work the socket immediately
Mark Sleee02385b2007-06-09 01:21:16 +0000320 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000321
322 return;
323 }
324
325 // In this case, the request was asynchronous and we should fall through
326 // right back into the read frame header state
Mark Slee92f00fb2006-10-25 01:28:17 +0000327 goto LABEL_APP_INIT;
328
Mark Slee2f6404d2006-10-10 01:37:40 +0000329 case APP_SEND_RESULT:
330
331 // N.B.: We also intentionally fall through here into the INIT state!
332
Mark Slee92f00fb2006-10-25 01:28:17 +0000333 LABEL_APP_INIT:
Mark Slee2f6404d2006-10-10 01:37:40 +0000334 case APP_INIT:
335
336 // Clear write buffer variables
337 writeBuffer_ = NULL;
338 writeBufferPos_ = 0;
339 writeBufferSize_ = 0;
340
341 // Set up read buffer for getting 4 bytes
342 readBufferPos_ = 0;
343 readWant_ = 4;
344
345 // Into read4 state we go
346 socketState_ = SOCKET_RECV;
347 appState_ = APP_READ_FRAME_SIZE;
348
349 // Register read event
350 setRead();
David Reiss84e63ab2008-03-07 20:12:28 +0000351
Mark Slee2f6404d2006-10-10 01:37:40 +0000352 // Try to work the socket right away
Mark Sleee02385b2007-06-09 01:21:16 +0000353 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000354
355 return;
356
357 case APP_READ_FRAME_SIZE:
358 // We just read the request length, deserialize it
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000359 sz = *(int32_t*)readBuffer_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000360 sz = (int32_t)ntohl(sz);
361
362 if (sz <= 0) {
363 fprintf(stderr, "TConnection:transition() Negative frame size %d, remote side not using TFramedTransport?", sz);
364 close();
365 return;
366 }
367
368 // Reset the read buffer
369 readWant_ = (uint32_t)sz;
370 readBufferPos_= 0;
371
372 // Move into read request state
373 appState_ = APP_READ_REQUEST;
374
375 // Work the socket right away
Mark Sleee02385b2007-06-09 01:21:16 +0000376 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000377
378 return;
379
380 default:
381 fprintf(stderr, "Totally Fucked. Application State %d\n", appState_);
382 assert(0);
383 }
384}
385
386void TConnection::setFlags(short eventFlags) {
387 // Catch the do nothing case
388 if (eventFlags_ == eventFlags) {
389 return;
390 }
391
392 // Delete a previously existing event
393 if (eventFlags_ != 0) {
394 if (event_del(&event_) == -1) {
boz6ded7752007-06-05 22:41:18 +0000395 GlobalOutput("TConnection::setFlags event_del");
Mark Slee2f6404d2006-10-10 01:37:40 +0000396 return;
397 }
398 }
399
400 // Update in memory structure
401 eventFlags_ = eventFlags;
402
Mark Slee402ee282007-08-23 01:43:20 +0000403 // Do not call event_set if there are no flags
404 if (!eventFlags_) {
405 return;
406 }
407
Mark Slee2f6404d2006-10-10 01:37:40 +0000408 /**
409 * event_set:
410 *
411 * Prepares the event structure &event to be used in future calls to
412 * event_add() and event_del(). The event will be prepared to call the
Mark Sleee02385b2007-06-09 01:21:16 +0000413 * eventHandler using the 'sock' file descriptor to monitor events.
Mark Slee2f6404d2006-10-10 01:37:40 +0000414 *
415 * The events can be either EV_READ, EV_WRITE, or both, indicating
416 * that an application can read or write from the file respectively without
417 * blocking.
418 *
Mark Sleee02385b2007-06-09 01:21:16 +0000419 * The eventHandler will be called with the file descriptor that triggered
Mark Slee2f6404d2006-10-10 01:37:40 +0000420 * the event and the type of event which will be one of: EV_TIMEOUT,
421 * EV_SIGNAL, EV_READ, EV_WRITE.
422 *
423 * The additional flag EV_PERSIST makes an event_add() persistent until
424 * event_del() has been called.
425 *
426 * Once initialized, the &event struct can be used repeatedly with
427 * event_add() and event_del() and does not need to be reinitialized unless
Mark Sleee02385b2007-06-09 01:21:16 +0000428 * the eventHandler and/or the argument to it are to be changed. However,
Mark Slee2f6404d2006-10-10 01:37:40 +0000429 * when an ev structure has been added to libevent using event_add() the
430 * structure must persist until the event occurs (assuming EV_PERSIST
431 * is not set) or is removed using event_del(). You may not reuse the same
432 * ev structure for multiple monitored descriptors; each descriptor needs
433 * its own ev.
434 */
435 event_set(&event_, socket_, eventFlags_, TConnection::eventHandler, this);
Mark Slee79b16942007-11-26 19:05:29 +0000436 event_base_set(server_->getEventBase(), &event_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000437
438 // Add the event
439 if (event_add(&event_, 0) == -1) {
Mark Slee17496a02007-08-02 06:37:40 +0000440 GlobalOutput("TConnection::setFlags(): could not event_add");
Mark Slee2f6404d2006-10-10 01:37:40 +0000441 }
442}
443
444/**
445 * Closes a connection
446 */
447void TConnection::close() {
448 // Delete the registered libevent
449 if (event_del(&event_) == -1) {
boz6ded7752007-06-05 22:41:18 +0000450 GlobalOutput("TConnection::close() event_del");
Mark Slee2f6404d2006-10-10 01:37:40 +0000451 }
452
453 // Close the socket
454 if (socket_ > 0) {
455 ::close(socket_);
456 }
457 socket_ = 0;
458
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000459 // close any factory produced transports
460 factoryInputTransport_->close();
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000461 factoryOutputTransport_->close();
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000462
Mark Slee2f6404d2006-10-10 01:37:40 +0000463 // Give this object back to the server that owns it
464 server_->returnConnection(this);
465}
466
467/**
468 * Creates a new connection either by reusing an object off the stack or
469 * by allocating a new one entirely
470 */
471TConnection* TNonblockingServer::createConnection(int socket, short flags) {
472 // Check the stack
473 if (connectionStack_.empty()) {
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000474 return new TConnection(socket, flags, this);
Mark Slee2f6404d2006-10-10 01:37:40 +0000475 } else {
476 TConnection* result = connectionStack_.top();
477 connectionStack_.pop();
478 result->init(socket, flags, this);
479 return result;
480 }
481}
482
483/**
484 * Returns a connection to the stack
485 */
486void TNonblockingServer::returnConnection(TConnection* connection) {
487 connectionStack_.push(connection);
488}
489
490/**
David Reissa79e4882008-03-05 07:51:47 +0000491 * Server socket had something happen. We accept all waiting client
492 * connections on fd and assign TConnection objects to handle those requests.
Mark Slee2f6404d2006-10-10 01:37:40 +0000493 */
494void TNonblockingServer::handleEvent(int fd, short which) {
495 // Make sure that libevent didn't fuck up the socket handles
496 assert(fd == serverSocket_);
Mark Slee79b16942007-11-26 19:05:29 +0000497
Mark Slee2f6404d2006-10-10 01:37:40 +0000498 // Server socket accepted a new connection
499 socklen_t addrLen;
500 struct sockaddr addr;
Mark Slee79b16942007-11-26 19:05:29 +0000501 addrLen = sizeof(addr);
502
Mark Slee2f6404d2006-10-10 01:37:40 +0000503 // Going to accept a new client socket
504 int clientSocket;
Mark Slee79b16942007-11-26 19:05:29 +0000505
Mark Slee2f6404d2006-10-10 01:37:40 +0000506 // Accept as many new clients as possible, even though libevent signaled only
507 // one, this helps us to avoid having to go back into the libevent engine so
508 // many times
509 while ((clientSocket = accept(fd, &addr, &addrLen)) != -1) {
510
511 // Explicitly set this socket to NONBLOCK mode
512 int flags;
513 if ((flags = fcntl(clientSocket, F_GETFL, 0)) < 0 ||
514 fcntl(clientSocket, F_SETFL, flags | O_NONBLOCK) < 0) {
David Reiss9b209552008-04-08 06:26:05 +0000515 string errStr = "thriftServerEventHandler: set O_NONBLOCK (fcntl) " + TOutput::strerror_s(errno);
516 GlobalOutput(errStr.c_str());
Mark Slee2f6404d2006-10-10 01:37:40 +0000517 close(clientSocket);
518 return;
519 }
520
521 // Create a new TConnection for this client socket.
522 TConnection* clientConnection =
523 createConnection(clientSocket, EV_READ | EV_PERSIST);
524
525 // Fail fast if we could not create a TConnection object
526 if (clientConnection == NULL) {
527 fprintf(stderr, "thriftServerEventHandler: failed TConnection factory");
528 close(clientSocket);
529 return;
530 }
531
532 // Put this client connection into the proper state
533 clientConnection->transition();
534 }
Mark Slee79b16942007-11-26 19:05:29 +0000535
Mark Slee2f6404d2006-10-10 01:37:40 +0000536 // Done looping accept, now we have to make sure the error is due to
537 // blocking. Any other error is a problem
538 if (errno != EAGAIN && errno != EWOULDBLOCK) {
David Reiss9b209552008-04-08 06:26:05 +0000539 string errStr = "thriftServerEventHandler: accept() " + TOutput::strerror_s(errno);
540 GlobalOutput(errStr.c_str());
Mark Slee2f6404d2006-10-10 01:37:40 +0000541 }
542}
543
544/**
Mark Slee79b16942007-11-26 19:05:29 +0000545 * Creates a socket to listen on and binds it to the local port.
Mark Slee2f6404d2006-10-10 01:37:40 +0000546 */
Mark Slee79b16942007-11-26 19:05:29 +0000547void TNonblockingServer::listenSocket() {
548 int s;
Mark Sleefb4b5142007-11-20 01:27:08 +0000549 struct addrinfo hints, *res, *res0;
550 int error;
Mark Slee79b16942007-11-26 19:05:29 +0000551
Mark Sleefb4b5142007-11-20 01:27:08 +0000552 char port[sizeof("65536") + 1];
553 memset(&hints, 0, sizeof(hints));
554 hints.ai_family = PF_UNSPEC;
555 hints.ai_socktype = SOCK_STREAM;
Mark Slee256bdc42007-11-27 08:42:19 +0000556 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
Mark Sleefb4b5142007-11-20 01:27:08 +0000557 sprintf(port, "%d", port_);
558
559 // Wildcard address
560 error = getaddrinfo(NULL, port, &hints, &res0);
561 if (error) {
David Reiss9b209552008-04-08 06:26:05 +0000562 string errStr = "TNonblockingServer::serve() getaddrinfo " + string(gai_strerror(error));
563 GlobalOutput(errStr.c_str());
Mark Sleefb4b5142007-11-20 01:27:08 +0000564 return;
565 }
566
567 // Pick the ipv6 address first since ipv4 addresses can be mapped
568 // into ipv6 space.
569 for (res = res0; res; res = res->ai_next) {
570 if (res->ai_family == AF_INET6 || res->ai_next == NULL)
571 break;
572 }
573
Mark Slee2f6404d2006-10-10 01:37:40 +0000574 // Create the server socket
Mark Slee79b16942007-11-26 19:05:29 +0000575 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
576 if (s == -1) {
577 freeaddrinfo(res0);
578 throw TException("TNonblockingServer::serve() socket() -1");
Mark Slee2f6404d2006-10-10 01:37:40 +0000579 }
580
David Reiss13aea462008-06-10 22:56:04 +0000581 #ifdef IPV6_V6ONLY
582 int zero = 0;
583 if (-1 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero))) {
584 GlobalOutput("TServerSocket::listen() IPV6_V6ONLY");
585 }
586 #endif // #ifdef IPV6_V6ONLY
587
588
Mark Slee79b16942007-11-26 19:05:29 +0000589 int one = 1;
590
591 // Set reuseaddr to avoid 2MSL delay on server restart
592 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
593
594 if (bind(s, res->ai_addr, res->ai_addrlen) == -1) {
595 close(s);
596 freeaddrinfo(res0);
597 throw TException("TNonblockingServer::serve() bind");
598 }
599
600 // Done with the addr info
601 freeaddrinfo(res0);
602
603 // Set up this file descriptor for listening
604 listenSocket(s);
605}
606
607/**
608 * Takes a socket created by listenSocket() and sets various options on it
609 * to prepare for use in the server.
610 */
611void TNonblockingServer::listenSocket(int s) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000612 // Set socket to nonblocking mode
613 int flags;
Mark Slee79b16942007-11-26 19:05:29 +0000614 if ((flags = fcntl(s, F_GETFL, 0)) < 0 ||
615 fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
616 close(s);
617 throw TException("TNonblockingServer::serve() O_NONBLOCK");
Mark Slee2f6404d2006-10-10 01:37:40 +0000618 }
619
620 int one = 1;
621 struct linger ling = {0, 0};
Mark Slee2f6404d2006-10-10 01:37:40 +0000622
623 // Keepalive to ensure full result flushing
Mark Slee79b16942007-11-26 19:05:29 +0000624 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
Mark Slee2f6404d2006-10-10 01:37:40 +0000625
626 // Turn linger off to avoid hung sockets
Mark Slee79b16942007-11-26 19:05:29 +0000627 setsockopt(s, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
Mark Slee2f6404d2006-10-10 01:37:40 +0000628
629 // Set TCP nodelay if available, MAC OS X Hack
630 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
631 #ifndef TCP_NOPUSH
Mark Slee79b16942007-11-26 19:05:29 +0000632 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
Mark Slee2f6404d2006-10-10 01:37:40 +0000633 #endif
634
Mark Slee79b16942007-11-26 19:05:29 +0000635 if (listen(s, LISTEN_BACKLOG) == -1) {
636 close(s);
637 throw TException("TNonblockingServer::serve() listen");
Mark Slee2f6404d2006-10-10 01:37:40 +0000638 }
639
Mark Slee79b16942007-11-26 19:05:29 +0000640 // Cool, this socket is good to go, set it as the serverSocket_
641 serverSocket_ = s;
642}
643
644/**
645 * Register the core libevent events onto the proper base.
646 */
647void TNonblockingServer::registerEvents(event_base* base) {
648 assert(serverSocket_ != -1);
649 assert(!eventBase_);
650 eventBase_ = base;
651
652 // Print some libevent stats
653 fprintf(stderr,
654 "libevent %s method %s\n",
655 event_get_version(),
656 event_get_method());
Mark Slee2f6404d2006-10-10 01:37:40 +0000657
658 // Register the server event
Mark Slee79b16942007-11-26 19:05:29 +0000659 event_set(&serverEvent_,
Mark Slee2f6404d2006-10-10 01:37:40 +0000660 serverSocket_,
661 EV_READ | EV_PERSIST,
662 TNonblockingServer::eventHandler,
663 this);
Mark Slee79b16942007-11-26 19:05:29 +0000664 event_base_set(eventBase_, &serverEvent_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000665
666 // Add the event and start up the server
Mark Slee79b16942007-11-26 19:05:29 +0000667 if (-1 == event_add(&serverEvent_, 0)) {
668 throw TException("TNonblockingServer::serve(): coult not event_add");
Mark Slee2f6404d2006-10-10 01:37:40 +0000669 }
Mark Slee79b16942007-11-26 19:05:29 +0000670}
671
672/**
673 * Main workhorse function, starts up the server listening on a port and
674 * loops over the libevent handler.
675 */
676void TNonblockingServer::serve() {
677 // Init socket
678 listenSocket();
679
680 // Initialize libevent core
681 registerEvents(static_cast<event_base*>(event_init()));
Mark Slee2f6404d2006-10-10 01:37:40 +0000682
Mark Sleeb4d3e7b2007-11-28 01:51:43 +0000683 // Run the preServe event
684 if (eventHandler_ != NULL) {
685 eventHandler_->preServe();
dweatherford58985992007-06-19 23:10:19 +0000686 }
687
Mark Sleee02385b2007-06-09 01:21:16 +0000688 // Run libevent engine, never returns, invokes calls to eventHandler
Mark Slee79b16942007-11-26 19:05:29 +0000689 event_base_loop(eventBase_, 0);
Mark Slee2f6404d2006-10-10 01:37:40 +0000690}
691
692}}} // facebook::thrift::server