blob: 8aec9d81fe049830cc5230c9be1f1539c5b44440 [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 Reissaf787782008-07-03 20:29:34 +0000300 // 4 bytes were reserved for frame size
David Reiss52cb7a72008-06-30 21:40:35 +0000301 if (writeBufferSize_ > 4) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000302
303 // Move into write state
304 writeBufferPos_ = 0;
305 socketState_ = SOCKET_SEND;
Mark Slee92f00fb2006-10-25 01:28:17 +0000306
David Reissaf787782008-07-03 20:29:34 +0000307 // Put the frame size into the write buffer
308 int32_t frameSize = (int32_t)htonl(writeBufferSize_ - 4);
309 memcpy(writeBuffer_, &frameSize, 4);
Mark Slee2f6404d2006-10-10 01:37:40 +0000310
311 // Socket into write mode
David Reiss52cb7a72008-06-30 21:40:35 +0000312 appState_ = APP_SEND_RESULT;
Mark Slee2f6404d2006-10-10 01:37:40 +0000313 setWrite();
314
315 // Try to work the socket immediately
Mark Sleee02385b2007-06-09 01:21:16 +0000316 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000317
318 return;
319 }
320
321 // In this case, the request was asynchronous and we should fall through
322 // right back into the read frame header state
Mark Slee92f00fb2006-10-25 01:28:17 +0000323 goto LABEL_APP_INIT;
324
Mark Slee2f6404d2006-10-10 01:37:40 +0000325 case APP_SEND_RESULT:
326
327 // N.B.: We also intentionally fall through here into the INIT state!
328
Mark Slee92f00fb2006-10-25 01:28:17 +0000329 LABEL_APP_INIT:
Mark Slee2f6404d2006-10-10 01:37:40 +0000330 case APP_INIT:
331
332 // Clear write buffer variables
333 writeBuffer_ = NULL;
334 writeBufferPos_ = 0;
335 writeBufferSize_ = 0;
336
337 // Set up read buffer for getting 4 bytes
338 readBufferPos_ = 0;
339 readWant_ = 4;
340
341 // Into read4 state we go
342 socketState_ = SOCKET_RECV;
343 appState_ = APP_READ_FRAME_SIZE;
344
345 // Register read event
346 setRead();
David Reiss84e63ab2008-03-07 20:12:28 +0000347
Mark Slee2f6404d2006-10-10 01:37:40 +0000348 // Try to work the socket right away
Mark Sleee02385b2007-06-09 01:21:16 +0000349 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000350
351 return;
352
353 case APP_READ_FRAME_SIZE:
354 // We just read the request length, deserialize it
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000355 sz = *(int32_t*)readBuffer_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000356 sz = (int32_t)ntohl(sz);
357
358 if (sz <= 0) {
359 fprintf(stderr, "TConnection:transition() Negative frame size %d, remote side not using TFramedTransport?", sz);
360 close();
361 return;
362 }
363
364 // Reset the read buffer
365 readWant_ = (uint32_t)sz;
366 readBufferPos_= 0;
367
368 // Move into read request state
369 appState_ = APP_READ_REQUEST;
370
371 // Work the socket right away
Mark Sleee02385b2007-06-09 01:21:16 +0000372 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000373
374 return;
375
376 default:
377 fprintf(stderr, "Totally Fucked. Application State %d\n", appState_);
378 assert(0);
379 }
380}
381
382void TConnection::setFlags(short eventFlags) {
383 // Catch the do nothing case
384 if (eventFlags_ == eventFlags) {
385 return;
386 }
387
388 // Delete a previously existing event
389 if (eventFlags_ != 0) {
390 if (event_del(&event_) == -1) {
boz6ded7752007-06-05 22:41:18 +0000391 GlobalOutput("TConnection::setFlags event_del");
Mark Slee2f6404d2006-10-10 01:37:40 +0000392 return;
393 }
394 }
395
396 // Update in memory structure
397 eventFlags_ = eventFlags;
398
Mark Slee402ee282007-08-23 01:43:20 +0000399 // Do not call event_set if there are no flags
400 if (!eventFlags_) {
401 return;
402 }
403
Mark Slee2f6404d2006-10-10 01:37:40 +0000404 /**
405 * event_set:
406 *
407 * Prepares the event structure &event to be used in future calls to
408 * event_add() and event_del(). The event will be prepared to call the
Mark Sleee02385b2007-06-09 01:21:16 +0000409 * eventHandler using the 'sock' file descriptor to monitor events.
Mark Slee2f6404d2006-10-10 01:37:40 +0000410 *
411 * The events can be either EV_READ, EV_WRITE, or both, indicating
412 * that an application can read or write from the file respectively without
413 * blocking.
414 *
Mark Sleee02385b2007-06-09 01:21:16 +0000415 * The eventHandler will be called with the file descriptor that triggered
Mark Slee2f6404d2006-10-10 01:37:40 +0000416 * the event and the type of event which will be one of: EV_TIMEOUT,
417 * EV_SIGNAL, EV_READ, EV_WRITE.
418 *
419 * The additional flag EV_PERSIST makes an event_add() persistent until
420 * event_del() has been called.
421 *
422 * Once initialized, the &event struct can be used repeatedly with
423 * event_add() and event_del() and does not need to be reinitialized unless
Mark Sleee02385b2007-06-09 01:21:16 +0000424 * the eventHandler and/or the argument to it are to be changed. However,
Mark Slee2f6404d2006-10-10 01:37:40 +0000425 * when an ev structure has been added to libevent using event_add() the
426 * structure must persist until the event occurs (assuming EV_PERSIST
427 * is not set) or is removed using event_del(). You may not reuse the same
428 * ev structure for multiple monitored descriptors; each descriptor needs
429 * its own ev.
430 */
431 event_set(&event_, socket_, eventFlags_, TConnection::eventHandler, this);
Mark Slee79b16942007-11-26 19:05:29 +0000432 event_base_set(server_->getEventBase(), &event_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000433
434 // Add the event
435 if (event_add(&event_, 0) == -1) {
Mark Slee17496a02007-08-02 06:37:40 +0000436 GlobalOutput("TConnection::setFlags(): could not event_add");
Mark Slee2f6404d2006-10-10 01:37:40 +0000437 }
438}
439
440/**
441 * Closes a connection
442 */
443void TConnection::close() {
444 // Delete the registered libevent
445 if (event_del(&event_) == -1) {
boz6ded7752007-06-05 22:41:18 +0000446 GlobalOutput("TConnection::close() event_del");
Mark Slee2f6404d2006-10-10 01:37:40 +0000447 }
448
449 // Close the socket
450 if (socket_ > 0) {
451 ::close(socket_);
452 }
453 socket_ = 0;
454
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000455 // close any factory produced transports
456 factoryInputTransport_->close();
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000457 factoryOutputTransport_->close();
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000458
Mark Slee2f6404d2006-10-10 01:37:40 +0000459 // Give this object back to the server that owns it
460 server_->returnConnection(this);
461}
462
463/**
464 * Creates a new connection either by reusing an object off the stack or
465 * by allocating a new one entirely
466 */
467TConnection* TNonblockingServer::createConnection(int socket, short flags) {
468 // Check the stack
469 if (connectionStack_.empty()) {
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000470 return new TConnection(socket, flags, this);
Mark Slee2f6404d2006-10-10 01:37:40 +0000471 } else {
472 TConnection* result = connectionStack_.top();
473 connectionStack_.pop();
474 result->init(socket, flags, this);
475 return result;
476 }
477}
478
479/**
480 * Returns a connection to the stack
481 */
482void TNonblockingServer::returnConnection(TConnection* connection) {
483 connectionStack_.push(connection);
484}
485
486/**
David Reissa79e4882008-03-05 07:51:47 +0000487 * Server socket had something happen. We accept all waiting client
488 * connections on fd and assign TConnection objects to handle those requests.
Mark Slee2f6404d2006-10-10 01:37:40 +0000489 */
490void TNonblockingServer::handleEvent(int fd, short which) {
491 // Make sure that libevent didn't fuck up the socket handles
492 assert(fd == serverSocket_);
Mark Slee79b16942007-11-26 19:05:29 +0000493
Mark Slee2f6404d2006-10-10 01:37:40 +0000494 // Server socket accepted a new connection
495 socklen_t addrLen;
496 struct sockaddr addr;
Mark Slee79b16942007-11-26 19:05:29 +0000497 addrLen = sizeof(addr);
498
Mark Slee2f6404d2006-10-10 01:37:40 +0000499 // Going to accept a new client socket
500 int clientSocket;
Mark Slee79b16942007-11-26 19:05:29 +0000501
Mark Slee2f6404d2006-10-10 01:37:40 +0000502 // Accept as many new clients as possible, even though libevent signaled only
503 // one, this helps us to avoid having to go back into the libevent engine so
504 // many times
505 while ((clientSocket = accept(fd, &addr, &addrLen)) != -1) {
506
507 // Explicitly set this socket to NONBLOCK mode
508 int flags;
509 if ((flags = fcntl(clientSocket, F_GETFL, 0)) < 0 ||
510 fcntl(clientSocket, F_SETFL, flags | O_NONBLOCK) < 0) {
David Reiss9b209552008-04-08 06:26:05 +0000511 string errStr = "thriftServerEventHandler: set O_NONBLOCK (fcntl) " + TOutput::strerror_s(errno);
512 GlobalOutput(errStr.c_str());
Mark Slee2f6404d2006-10-10 01:37:40 +0000513 close(clientSocket);
514 return;
515 }
516
517 // Create a new TConnection for this client socket.
518 TConnection* clientConnection =
519 createConnection(clientSocket, EV_READ | EV_PERSIST);
520
521 // Fail fast if we could not create a TConnection object
522 if (clientConnection == NULL) {
523 fprintf(stderr, "thriftServerEventHandler: failed TConnection factory");
524 close(clientSocket);
525 return;
526 }
527
528 // Put this client connection into the proper state
529 clientConnection->transition();
530 }
Mark Slee79b16942007-11-26 19:05:29 +0000531
Mark Slee2f6404d2006-10-10 01:37:40 +0000532 // Done looping accept, now we have to make sure the error is due to
533 // blocking. Any other error is a problem
534 if (errno != EAGAIN && errno != EWOULDBLOCK) {
David Reiss9b209552008-04-08 06:26:05 +0000535 string errStr = "thriftServerEventHandler: accept() " + TOutput::strerror_s(errno);
536 GlobalOutput(errStr.c_str());
Mark Slee2f6404d2006-10-10 01:37:40 +0000537 }
538}
539
540/**
Mark Slee79b16942007-11-26 19:05:29 +0000541 * Creates a socket to listen on and binds it to the local port.
Mark Slee2f6404d2006-10-10 01:37:40 +0000542 */
Mark Slee79b16942007-11-26 19:05:29 +0000543void TNonblockingServer::listenSocket() {
544 int s;
Mark Sleefb4b5142007-11-20 01:27:08 +0000545 struct addrinfo hints, *res, *res0;
546 int error;
Mark Slee79b16942007-11-26 19:05:29 +0000547
Mark Sleefb4b5142007-11-20 01:27:08 +0000548 char port[sizeof("65536") + 1];
549 memset(&hints, 0, sizeof(hints));
550 hints.ai_family = PF_UNSPEC;
551 hints.ai_socktype = SOCK_STREAM;
Mark Slee256bdc42007-11-27 08:42:19 +0000552 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
Mark Sleefb4b5142007-11-20 01:27:08 +0000553 sprintf(port, "%d", port_);
554
555 // Wildcard address
556 error = getaddrinfo(NULL, port, &hints, &res0);
557 if (error) {
David Reiss9b209552008-04-08 06:26:05 +0000558 string errStr = "TNonblockingServer::serve() getaddrinfo " + string(gai_strerror(error));
559 GlobalOutput(errStr.c_str());
Mark Sleefb4b5142007-11-20 01:27:08 +0000560 return;
561 }
562
563 // Pick the ipv6 address first since ipv4 addresses can be mapped
564 // into ipv6 space.
565 for (res = res0; res; res = res->ai_next) {
566 if (res->ai_family == AF_INET6 || res->ai_next == NULL)
567 break;
568 }
569
Mark Slee2f6404d2006-10-10 01:37:40 +0000570 // Create the server socket
Mark Slee79b16942007-11-26 19:05:29 +0000571 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
572 if (s == -1) {
573 freeaddrinfo(res0);
574 throw TException("TNonblockingServer::serve() socket() -1");
Mark Slee2f6404d2006-10-10 01:37:40 +0000575 }
576
David Reiss13aea462008-06-10 22:56:04 +0000577 #ifdef IPV6_V6ONLY
578 int zero = 0;
579 if (-1 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero))) {
580 GlobalOutput("TServerSocket::listen() IPV6_V6ONLY");
581 }
582 #endif // #ifdef IPV6_V6ONLY
583
584
Mark Slee79b16942007-11-26 19:05:29 +0000585 int one = 1;
586
587 // Set reuseaddr to avoid 2MSL delay on server restart
588 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
589
590 if (bind(s, res->ai_addr, res->ai_addrlen) == -1) {
591 close(s);
592 freeaddrinfo(res0);
593 throw TException("TNonblockingServer::serve() bind");
594 }
595
596 // Done with the addr info
597 freeaddrinfo(res0);
598
599 // Set up this file descriptor for listening
600 listenSocket(s);
601}
602
603/**
604 * Takes a socket created by listenSocket() and sets various options on it
605 * to prepare for use in the server.
606 */
607void TNonblockingServer::listenSocket(int s) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000608 // Set socket to nonblocking mode
609 int flags;
Mark Slee79b16942007-11-26 19:05:29 +0000610 if ((flags = fcntl(s, F_GETFL, 0)) < 0 ||
611 fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
612 close(s);
613 throw TException("TNonblockingServer::serve() O_NONBLOCK");
Mark Slee2f6404d2006-10-10 01:37:40 +0000614 }
615
616 int one = 1;
617 struct linger ling = {0, 0};
Mark Slee2f6404d2006-10-10 01:37:40 +0000618
619 // Keepalive to ensure full result flushing
Mark Slee79b16942007-11-26 19:05:29 +0000620 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
Mark Slee2f6404d2006-10-10 01:37:40 +0000621
622 // Turn linger off to avoid hung sockets
Mark Slee79b16942007-11-26 19:05:29 +0000623 setsockopt(s, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
Mark Slee2f6404d2006-10-10 01:37:40 +0000624
625 // Set TCP nodelay if available, MAC OS X Hack
626 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
627 #ifndef TCP_NOPUSH
Mark Slee79b16942007-11-26 19:05:29 +0000628 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
Mark Slee2f6404d2006-10-10 01:37:40 +0000629 #endif
630
Mark Slee79b16942007-11-26 19:05:29 +0000631 if (listen(s, LISTEN_BACKLOG) == -1) {
632 close(s);
633 throw TException("TNonblockingServer::serve() listen");
Mark Slee2f6404d2006-10-10 01:37:40 +0000634 }
635
Mark Slee79b16942007-11-26 19:05:29 +0000636 // Cool, this socket is good to go, set it as the serverSocket_
637 serverSocket_ = s;
638}
639
640/**
641 * Register the core libevent events onto the proper base.
642 */
643void TNonblockingServer::registerEvents(event_base* base) {
644 assert(serverSocket_ != -1);
645 assert(!eventBase_);
646 eventBase_ = base;
647
648 // Print some libevent stats
649 fprintf(stderr,
650 "libevent %s method %s\n",
651 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
688}}} // facebook::thrift::server