Mark Slee | 9f0c651 | 2007-02-28 23:58:26 +0000 | [diff] [blame] | 1 | // 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 Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 7 | #include "TNonblockingServer.h" |
| 8 | |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 9 | #include <iostream> |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 10 | #include <sys/socket.h> |
| 11 | #include <netinet/in.h> |
| 12 | #include <netinet/tcp.h> |
| 13 | #include <fcntl.h> |
| 14 | #include <errno.h> |
| 15 | #include <assert.h> |
| 16 | |
| 17 | namespace facebook { namespace thrift { namespace server { |
| 18 | |
Mark Slee | 5ea15f9 | 2007-03-05 22:55:59 +0000 | [diff] [blame] | 19 | using namespace facebook::thrift::protocol; |
| 20 | using namespace facebook::thrift::transport; |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 21 | using namespace std; |
| 22 | |
| 23 | class TConnection::Task: public Runnable { |
| 24 | public: |
| 25 | Task(boost::shared_ptr<TProcessor> processor, |
| 26 | boost::shared_ptr<TProtocol> input, |
| 27 | boost::shared_ptr<TProtocol> output, |
| 28 | int taskHandle) : |
| 29 | processor_(processor), |
| 30 | input_(input), |
| 31 | output_(output), |
| 32 | taskHandle_(taskHandle) {} |
| 33 | |
| 34 | void run() { |
| 35 | try { |
| 36 | while (processor_->process(input_, output_)) { |
| 37 | if (!input_->getTransport()->peek()) { |
| 38 | break; |
| 39 | } |
| 40 | } |
| 41 | } catch (TTransportException& ttx) { |
| 42 | cerr << "TThreadedServer client died: " << ttx.what() << endl; |
| 43 | } catch (TException& x) { |
| 44 | cerr << "TThreadedServer exception: " << x.what() << endl; |
| 45 | } catch (...) { |
| 46 | cerr << "TThreadedServer uncaught exception." << endl; |
| 47 | } |
| 48 | |
| 49 | // Signal completion back to the libevent thread via a socketpair |
| 50 | int8_t b = 0; |
| 51 | if (-1 == send(taskHandle_, &b, sizeof(int8_t), 0)) { |
| 52 | GlobalOutput("TNonblockingServer::Task: send"); |
| 53 | } |
| 54 | if (-1 == ::close(taskHandle_)) { |
| 55 | GlobalOutput("TNonblockingServer::Task: close, possible resource leak"); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | private: |
| 60 | boost::shared_ptr<TProcessor> processor_; |
| 61 | boost::shared_ptr<TProtocol> input_; |
| 62 | boost::shared_ptr<TProtocol> output_; |
| 63 | int taskHandle_; |
| 64 | }; |
Mark Slee | 5ea15f9 | 2007-03-05 22:55:59 +0000 | [diff] [blame] | 65 | |
| 66 | void TConnection::init(int socket, short eventFlags, TNonblockingServer* s) { |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 67 | socket_ = socket; |
| 68 | server_ = s; |
| 69 | appState_ = APP_INIT; |
| 70 | eventFlags_ = 0; |
| 71 | |
| 72 | readBufferPos_ = 0; |
| 73 | readWant_ = 0; |
| 74 | |
| 75 | writeBuffer_ = NULL; |
| 76 | writeBufferSize_ = 0; |
| 77 | writeBufferPos_ = 0; |
| 78 | |
| 79 | socketState_ = SOCKET_RECV; |
| 80 | appState_ = APP_INIT; |
| 81 | |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 82 | taskHandle_ = -1; |
| 83 | |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 84 | // Set flags, which also registers the event |
| 85 | setFlags(eventFlags); |
Aditya Agarwal | 1ea9052 | 2007-01-19 02:02:12 +0000 | [diff] [blame] | 86 | |
Aditya Agarwal | 9abb0d6 | 2007-01-24 22:53:54 +0000 | [diff] [blame] | 87 | // get input/transports |
| 88 | factoryInputTransport_ = s->getInputTransportFactory()->getTransport(inputTransport_); |
| 89 | factoryOutputTransport_ = s->getOutputTransportFactory()->getTransport(outputTransport_); |
Aditya Agarwal | 1ea9052 | 2007-01-19 02:02:12 +0000 | [diff] [blame] | 90 | |
| 91 | // Create protocol |
Aditya Agarwal | 9abb0d6 | 2007-01-24 22:53:54 +0000 | [diff] [blame] | 92 | inputProtocol_ = s->getInputProtocolFactory()->getProtocol(factoryInputTransport_); |
| 93 | outputProtocol_ = s->getOutputProtocolFactory()->getProtocol(factoryOutputTransport_); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 94 | } |
| 95 | |
| 96 | void TConnection::workSocket() { |
Mark Slee | aaa23ed | 2007-01-30 19:52:05 +0000 | [diff] [blame] | 97 | int flags=0, got=0, left=0, sent=0; |
| 98 | uint32_t fetch = 0; |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 99 | |
| 100 | switch (socketState_) { |
| 101 | case SOCKET_RECV: |
| 102 | // It is an error to be in this state if we already have all the data |
| 103 | assert(readBufferPos_ < readWant_); |
| 104 | |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 105 | // Double the buffer size until it is big enough |
robert | 7951119 | 2006-12-20 19:25:38 +0000 | [diff] [blame] | 106 | if (readWant_ > readBufferSize_) { |
| 107 | while (readWant_ > readBufferSize_) { |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 108 | readBufferSize_ *= 2; |
| 109 | } |
| 110 | readBuffer_ = (uint8_t*)realloc(readBuffer_, readBufferSize_); |
| 111 | if (readBuffer_ == NULL) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 112 | GlobalOutput("TConnection::workSocket() realloc"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 113 | close(); |
| 114 | return; |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // Read from the socket |
Mark Slee | aaa23ed | 2007-01-30 19:52:05 +0000 | [diff] [blame] | 119 | fetch = readWant_ - readBufferPos_; |
| 120 | got = recv(socket_, readBuffer_ + readBufferPos_, fetch, 0); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 121 | |
| 122 | if (got > 0) { |
| 123 | // Move along in the buffer |
| 124 | readBufferPos_ += got; |
| 125 | |
| 126 | // Check that we did not overdo it |
| 127 | assert(readBufferPos_ <= readWant_); |
| 128 | |
| 129 | // We are done reading, move onto the next state |
| 130 | if (readBufferPos_ == readWant_) { |
| 131 | transition(); |
| 132 | } |
| 133 | return; |
| 134 | } else if (got == -1) { |
| 135 | // Blocking errors are okay, just move on |
| 136 | if (errno == EAGAIN || errno == EWOULDBLOCK) { |
| 137 | return; |
| 138 | } |
| 139 | |
| 140 | if (errno != ECONNRESET) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 141 | GlobalOutput("TConnection::workSocket() recv -1"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 142 | } |
| 143 | } |
| 144 | |
| 145 | // Whenever we get down here it means a remote disconnect |
| 146 | close(); |
| 147 | |
| 148 | return; |
| 149 | |
| 150 | case SOCKET_SEND: |
| 151 | // Should never have position past size |
| 152 | assert(writeBufferPos_ <= writeBufferSize_); |
| 153 | |
| 154 | // If there is no data to send, then let us move on |
| 155 | if (writeBufferPos_ == writeBufferSize_) { |
| 156 | fprintf(stderr, "WARNING: Send state with no data to send\n"); |
| 157 | transition(); |
| 158 | return; |
| 159 | } |
| 160 | |
| 161 | flags = 0; |
| 162 | #ifdef MSG_NOSIGNAL |
| 163 | // Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we |
| 164 | // check for the EPIPE return condition and close the socket in that case |
| 165 | flags |= MSG_NOSIGNAL; |
| 166 | #endif // ifdef MSG_NOSIGNAL |
| 167 | |
Mark Slee | aaa23ed | 2007-01-30 19:52:05 +0000 | [diff] [blame] | 168 | left = writeBufferSize_ - writeBufferPos_; |
| 169 | sent = send(socket_, writeBuffer_ + writeBufferPos_, left, flags); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 170 | |
| 171 | if (sent <= 0) { |
| 172 | // Blocking errors are okay, just move on |
| 173 | if (errno == EAGAIN || errno == EWOULDBLOCK) { |
| 174 | return; |
| 175 | } |
| 176 | if (errno != EPIPE) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 177 | GlobalOutput("TConnection::workSocket() send -1"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 178 | } |
| 179 | close(); |
| 180 | return; |
| 181 | } |
| 182 | |
| 183 | writeBufferPos_ += sent; |
| 184 | |
| 185 | // Did we overdo it? |
| 186 | assert(writeBufferPos_ <= writeBufferSize_); |
| 187 | |
| 188 | // We are done! |
| 189 | if (writeBufferPos_ == writeBufferSize_) { |
| 190 | transition(); |
| 191 | } |
| 192 | |
| 193 | return; |
| 194 | |
| 195 | default: |
| 196 | fprintf(stderr, "Shit Got Ill. Socket State %d\n", socketState_); |
| 197 | assert(0); |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /** |
| 202 | * This is called when the application transitions from one state into |
| 203 | * another. This means that it has finished writing the data that it needed |
| 204 | * to, or finished receiving the data that it needed to. |
| 205 | */ |
| 206 | void TConnection::transition() { |
Mark Slee | aaa23ed | 2007-01-30 19:52:05 +0000 | [diff] [blame] | 207 | |
| 208 | int sz = 0; |
| 209 | |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 210 | // Switch upon the state that we are currently in and move to a new state |
| 211 | switch (appState_) { |
| 212 | |
| 213 | case APP_READ_REQUEST: |
| 214 | // We are done reading the request, package the read buffer into transport |
| 215 | // and get back some data from the dispatch function |
| 216 | inputTransport_->resetBuffer(readBuffer_, readBufferPos_); |
| 217 | outputTransport_->resetBuffer(); |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 218 | |
| 219 | if (server_->isThreadPoolProcessing()) { |
| 220 | // We are setting up a Task to do this work and we will wait on it |
| 221 | int sv[2]; |
| 222 | if (-1 == socketpair(AF_LOCAL, SOCK_STREAM, 0, sv)) { |
| 223 | GlobalOutput("TConnection::socketpair() failed"); |
| 224 | // Now we will fall through to the APP_WAIT_TASK block with no response |
| 225 | } else { |
| 226 | // Create task and dispatch to the thread manager |
| 227 | boost::shared_ptr<Runnable> task = |
| 228 | boost::shared_ptr<Runnable>(new Task(server_->getProcessor(), |
| 229 | inputProtocol_, |
| 230 | outputProtocol_, |
| 231 | sv[1])); |
| 232 | appState_ = APP_WAIT_TASK; |
| 233 | event_set(&taskEvent_, |
| 234 | taskHandle_ = sv[0], |
| 235 | EV_READ, |
| 236 | TConnection::taskHandler, |
| 237 | this); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 238 | |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 239 | // Add the event and start up the server |
| 240 | if (-1 == event_add(&taskEvent_, 0)) { |
| 241 | GlobalOutput("TNonblockingServer::serve(): coult not event_add"); |
| 242 | return; |
| 243 | } |
| 244 | server_->addTask(task); |
| 245 | return; |
| 246 | } |
| 247 | } else { |
| 248 | try { |
| 249 | // Invoke the processor |
| 250 | server_->getProcessor()->process(inputProtocol_, outputProtocol_); |
| 251 | } catch (TTransportException &ttx) { |
| 252 | fprintf(stderr, "TTransportException: Server::process() %s\n", ttx.what()); |
| 253 | close(); |
| 254 | return; |
| 255 | } catch (TException &x) { |
| 256 | fprintf(stderr, "TException: Server::process() %s\n", x.what()); |
| 257 | close(); |
| 258 | return; |
| 259 | } catch (...) { |
| 260 | fprintf(stderr, "Server::process() unknown exception\n"); |
| 261 | close(); |
| 262 | return; |
| 263 | } |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 264 | } |
| 265 | |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 266 | case APP_WAIT_TASK: |
| 267 | // We have now finished processing a task and the result has been written |
| 268 | // into the outputTransport_, so we grab its contents and place them into |
| 269 | // the writeBuffer_ for actual writing by the libevent thread |
| 270 | |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 271 | // Get the result of the operation |
| 272 | outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_); |
| 273 | |
| 274 | // If the function call generated return data, then move into the send |
| 275 | // state and get going |
| 276 | if (writeBufferSize_ > 0) { |
| 277 | |
| 278 | // Move into write state |
| 279 | writeBufferPos_ = 0; |
| 280 | socketState_ = SOCKET_SEND; |
Mark Slee | 92f00fb | 2006-10-25 01:28:17 +0000 | [diff] [blame] | 281 | |
| 282 | if (server_->getFrameResponses()) { |
| 283 | // Put the frame size into the write buffer |
| 284 | appState_ = APP_SEND_FRAME_SIZE; |
| 285 | frameSize_ = (int32_t)htonl(writeBufferSize_); |
| 286 | writeBuffer_ = (uint8_t*)&frameSize_; |
| 287 | writeBufferSize_ = 4; |
| 288 | } else { |
| 289 | // Go straight into sending the result, do not frame it |
| 290 | appState_ = APP_SEND_RESULT; |
| 291 | } |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 292 | |
| 293 | // Socket into write mode |
| 294 | setWrite(); |
| 295 | |
| 296 | // Try to work the socket immediately |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 297 | // workSocket(); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 298 | |
| 299 | return; |
| 300 | } |
| 301 | |
| 302 | // In this case, the request was asynchronous and we should fall through |
| 303 | // right back into the read frame header state |
Mark Slee | 92f00fb | 2006-10-25 01:28:17 +0000 | [diff] [blame] | 304 | goto LABEL_APP_INIT; |
| 305 | |
| 306 | case APP_SEND_FRAME_SIZE: |
| 307 | |
| 308 | // Refetch the result of the operation since we put the frame size into |
| 309 | // writeBuffer_ |
| 310 | outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_); |
| 311 | writeBufferPos_ = 0; |
| 312 | |
| 313 | // Now in send result state |
| 314 | appState_ = APP_SEND_RESULT; |
| 315 | |
| 316 | // Go to work on the socket right away, probably still writeable |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 317 | // workSocket(); |
Mark Slee | 92f00fb | 2006-10-25 01:28:17 +0000 | [diff] [blame] | 318 | |
| 319 | return; |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 320 | |
| 321 | case APP_SEND_RESULT: |
| 322 | |
| 323 | // N.B.: We also intentionally fall through here into the INIT state! |
| 324 | |
Mark Slee | 92f00fb | 2006-10-25 01:28:17 +0000 | [diff] [blame] | 325 | LABEL_APP_INIT: |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 326 | case APP_INIT: |
| 327 | |
| 328 | // Clear write buffer variables |
| 329 | writeBuffer_ = NULL; |
| 330 | writeBufferPos_ = 0; |
| 331 | writeBufferSize_ = 0; |
| 332 | |
| 333 | // Set up read buffer for getting 4 bytes |
| 334 | readBufferPos_ = 0; |
| 335 | readWant_ = 4; |
| 336 | |
| 337 | // Into read4 state we go |
| 338 | socketState_ = SOCKET_RECV; |
| 339 | appState_ = APP_READ_FRAME_SIZE; |
| 340 | |
| 341 | // Register read event |
| 342 | setRead(); |
| 343 | |
| 344 | // Try to work the socket right away |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 345 | // workSocket(); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 346 | |
| 347 | return; |
| 348 | |
| 349 | case APP_READ_FRAME_SIZE: |
| 350 | // We just read the request length, deserialize it |
Mark Slee | aaa23ed | 2007-01-30 19:52:05 +0000 | [diff] [blame] | 351 | sz = *(int32_t*)readBuffer_; |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 352 | sz = (int32_t)ntohl(sz); |
| 353 | |
| 354 | if (sz <= 0) { |
| 355 | fprintf(stderr, "TConnection:transition() Negative frame size %d, remote side not using TFramedTransport?", sz); |
| 356 | close(); |
| 357 | return; |
| 358 | } |
| 359 | |
| 360 | // Reset the read buffer |
| 361 | readWant_ = (uint32_t)sz; |
| 362 | readBufferPos_= 0; |
| 363 | |
| 364 | // Move into read request state |
| 365 | appState_ = APP_READ_REQUEST; |
| 366 | |
| 367 | // Work the socket right away |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 368 | // workSocket(); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 369 | |
| 370 | return; |
| 371 | |
| 372 | default: |
| 373 | fprintf(stderr, "Totally Fucked. Application State %d\n", appState_); |
| 374 | assert(0); |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | void TConnection::setFlags(short eventFlags) { |
| 379 | // Catch the do nothing case |
| 380 | if (eventFlags_ == eventFlags) { |
| 381 | return; |
| 382 | } |
| 383 | |
| 384 | // Delete a previously existing event |
| 385 | if (eventFlags_ != 0) { |
| 386 | if (event_del(&event_) == -1) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 387 | GlobalOutput("TConnection::setFlags event_del"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 388 | return; |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | // Update in memory structure |
| 393 | eventFlags_ = eventFlags; |
| 394 | |
| 395 | /** |
| 396 | * event_set: |
| 397 | * |
| 398 | * Prepares the event structure &event to be used in future calls to |
| 399 | * event_add() and event_del(). The event will be prepared to call the |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 400 | * eventHandler using the 'sock' file descriptor to monitor events. |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 401 | * |
| 402 | * The events can be either EV_READ, EV_WRITE, or both, indicating |
| 403 | * that an application can read or write from the file respectively without |
| 404 | * blocking. |
| 405 | * |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 406 | * The eventHandler will be called with the file descriptor that triggered |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 407 | * the event and the type of event which will be one of: EV_TIMEOUT, |
| 408 | * EV_SIGNAL, EV_READ, EV_WRITE. |
| 409 | * |
| 410 | * The additional flag EV_PERSIST makes an event_add() persistent until |
| 411 | * event_del() has been called. |
| 412 | * |
| 413 | * Once initialized, the &event struct can be used repeatedly with |
| 414 | * event_add() and event_del() and does not need to be reinitialized unless |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 415 | * the eventHandler and/or the argument to it are to be changed. However, |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 416 | * when an ev structure has been added to libevent using event_add() the |
| 417 | * structure must persist until the event occurs (assuming EV_PERSIST |
| 418 | * is not set) or is removed using event_del(). You may not reuse the same |
| 419 | * ev structure for multiple monitored descriptors; each descriptor needs |
| 420 | * its own ev. |
| 421 | */ |
| 422 | event_set(&event_, socket_, eventFlags_, TConnection::eventHandler, this); |
| 423 | |
| 424 | // Add the event |
| 425 | if (event_add(&event_, 0) == -1) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 426 | GlobalOutput("TConnection::setFlags(): coult not event_add"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 427 | } |
| 428 | } |
| 429 | |
| 430 | /** |
| 431 | * Closes a connection |
| 432 | */ |
| 433 | void TConnection::close() { |
| 434 | // Delete the registered libevent |
| 435 | if (event_del(&event_) == -1) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 436 | GlobalOutput("TConnection::close() event_del"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 437 | } |
| 438 | |
| 439 | // Close the socket |
| 440 | if (socket_ > 0) { |
| 441 | ::close(socket_); |
| 442 | } |
| 443 | socket_ = 0; |
| 444 | |
Aditya Agarwal | 1ea9052 | 2007-01-19 02:02:12 +0000 | [diff] [blame] | 445 | // close any factory produced transports |
| 446 | factoryInputTransport_->close(); |
Aditya Agarwal | 9abb0d6 | 2007-01-24 22:53:54 +0000 | [diff] [blame] | 447 | factoryOutputTransport_->close(); |
Aditya Agarwal | 1ea9052 | 2007-01-19 02:02:12 +0000 | [diff] [blame] | 448 | |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 449 | // Give this object back to the server that owns it |
| 450 | server_->returnConnection(this); |
| 451 | } |
| 452 | |
| 453 | /** |
| 454 | * Creates a new connection either by reusing an object off the stack or |
| 455 | * by allocating a new one entirely |
| 456 | */ |
| 457 | TConnection* TNonblockingServer::createConnection(int socket, short flags) { |
| 458 | // Check the stack |
| 459 | if (connectionStack_.empty()) { |
Aditya Agarwal | 9abb0d6 | 2007-01-24 22:53:54 +0000 | [diff] [blame] | 460 | return new TConnection(socket, flags, this); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 461 | } else { |
| 462 | TConnection* result = connectionStack_.top(); |
| 463 | connectionStack_.pop(); |
| 464 | result->init(socket, flags, this); |
| 465 | return result; |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | /** |
| 470 | * Returns a connection to the stack |
| 471 | */ |
| 472 | void TNonblockingServer::returnConnection(TConnection* connection) { |
| 473 | connectionStack_.push(connection); |
| 474 | } |
| 475 | |
| 476 | /** |
| 477 | * Server socket had something happen |
| 478 | */ |
| 479 | void TNonblockingServer::handleEvent(int fd, short which) { |
| 480 | // Make sure that libevent didn't fuck up the socket handles |
| 481 | assert(fd == serverSocket_); |
| 482 | |
| 483 | // Server socket accepted a new connection |
| 484 | socklen_t addrLen; |
| 485 | struct sockaddr addr; |
| 486 | addrLen = sizeof(addr); |
| 487 | |
| 488 | // Going to accept a new client socket |
| 489 | int clientSocket; |
| 490 | |
| 491 | // Accept as many new clients as possible, even though libevent signaled only |
| 492 | // one, this helps us to avoid having to go back into the libevent engine so |
| 493 | // many times |
| 494 | while ((clientSocket = accept(fd, &addr, &addrLen)) != -1) { |
| 495 | |
| 496 | // Explicitly set this socket to NONBLOCK mode |
| 497 | int flags; |
| 498 | if ((flags = fcntl(clientSocket, F_GETFL, 0)) < 0 || |
| 499 | fcntl(clientSocket, F_SETFL, flags | O_NONBLOCK) < 0) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 500 | GlobalOutput("thriftServerEventHandler: set O_NONBLOCK"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 501 | close(clientSocket); |
| 502 | return; |
| 503 | } |
| 504 | |
| 505 | // Create a new TConnection for this client socket. |
| 506 | TConnection* clientConnection = |
| 507 | createConnection(clientSocket, EV_READ | EV_PERSIST); |
| 508 | |
| 509 | // Fail fast if we could not create a TConnection object |
| 510 | if (clientConnection == NULL) { |
| 511 | fprintf(stderr, "thriftServerEventHandler: failed TConnection factory"); |
| 512 | close(clientSocket); |
| 513 | return; |
| 514 | } |
| 515 | |
| 516 | // Put this client connection into the proper state |
| 517 | clientConnection->transition(); |
| 518 | } |
| 519 | |
| 520 | // Done looping accept, now we have to make sure the error is due to |
| 521 | // blocking. Any other error is a problem |
| 522 | if (errno != EAGAIN && errno != EWOULDBLOCK) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 523 | GlobalOutput("thriftServerEventHandler: accept()"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 524 | } |
| 525 | } |
| 526 | |
| 527 | /** |
| 528 | * Main workhorse function, starts up the server listening on a port and |
| 529 | * loops over the libevent handler. |
| 530 | */ |
| 531 | void TNonblockingServer::serve() { |
| 532 | // Initialize libevent |
| 533 | event_init(); |
| 534 | |
| 535 | // Print some libevent stats |
| 536 | fprintf(stderr, |
| 537 | "libevent %s method %s\n", |
| 538 | event_get_version(), |
| 539 | event_get_method()); |
| 540 | |
| 541 | // Create the server socket |
| 542 | serverSocket_ = socket(AF_INET, SOCK_STREAM, 0); |
| 543 | if (serverSocket_ == -1) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 544 | GlobalOutput("TNonblockingServer::serve() socket() -1"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 545 | return; |
| 546 | } |
| 547 | |
| 548 | // Set socket to nonblocking mode |
| 549 | int flags; |
| 550 | if ((flags = fcntl(serverSocket_, F_GETFL, 0)) < 0 || |
| 551 | fcntl(serverSocket_, F_SETFL, flags | O_NONBLOCK) < 0) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 552 | GlobalOutput("TNonblockingServer::serve() O_NONBLOCK"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 553 | ::close(serverSocket_); |
| 554 | return; |
| 555 | } |
| 556 | |
| 557 | int one = 1; |
| 558 | struct linger ling = {0, 0}; |
| 559 | |
| 560 | // Set reuseaddr to avoid 2MSL delay on server restart |
| 561 | setsockopt(serverSocket_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); |
| 562 | |
| 563 | // Keepalive to ensure full result flushing |
| 564 | setsockopt(serverSocket_, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one)); |
| 565 | |
| 566 | // Turn linger off to avoid hung sockets |
| 567 | setsockopt(serverSocket_, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)); |
| 568 | |
| 569 | // Set TCP nodelay if available, MAC OS X Hack |
| 570 | // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html |
| 571 | #ifndef TCP_NOPUSH |
| 572 | setsockopt(serverSocket_, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); |
| 573 | #endif |
| 574 | |
| 575 | struct sockaddr_in addr; |
| 576 | addr.sin_family = AF_INET; |
| 577 | addr.sin_port = htons(port_); |
| 578 | addr.sin_addr.s_addr = INADDR_ANY; |
| 579 | |
| 580 | if (bind(serverSocket_, (struct sockaddr*)&addr, sizeof(addr)) == -1) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 581 | GlobalOutput("TNonblockingServer::serve() bind"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 582 | close(serverSocket_); |
| 583 | return; |
| 584 | } |
| 585 | |
| 586 | if (listen(serverSocket_, LISTEN_BACKLOG) == -1) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 587 | GlobalOutput("TNonblockingServer::serve() listen"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 588 | close(serverSocket_); |
| 589 | return; |
| 590 | } |
| 591 | |
| 592 | // Register the server event |
| 593 | struct event serverEvent; |
| 594 | event_set(&serverEvent, |
| 595 | serverSocket_, |
| 596 | EV_READ | EV_PERSIST, |
| 597 | TNonblockingServer::eventHandler, |
| 598 | this); |
| 599 | |
| 600 | // Add the event and start up the server |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 601 | if (-1 == event_add(&serverEvent, 0)) { |
boz | 6ded775 | 2007-06-05 22:41:18 +0000 | [diff] [blame] | 602 | GlobalOutput("TNonblockingServer::serve(): coult not event_add"); |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 603 | return; |
| 604 | } |
| 605 | |
dweatherford | 5898599 | 2007-06-19 23:10:19 +0000 | [diff] [blame] | 606 | // Run pre-serve callback function if we have one |
| 607 | if (preServeCallback_) { |
| 608 | preServeCallback_(preServeCallbackArg_); |
| 609 | } |
| 610 | |
Mark Slee | e02385b | 2007-06-09 01:21:16 +0000 | [diff] [blame] | 611 | // Run libevent engine, never returns, invokes calls to eventHandler |
Mark Slee | 2f6404d | 2006-10-10 01:37:40 +0000 | [diff] [blame] | 612 | event_loop(0); |
| 613 | } |
| 614 | |
| 615 | }}} // facebook::thrift::server |