blob: 681cbdb5d19c08dddc6906d7cd61ea6b99600aa8 [file] [log] [blame]
David Reissea2cba82009-03-30 21:35:00 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
Mark Slee9f0c6512007-02-28 23:58:26 +000019
Mark Slee2f6404d2006-10-10 01:37:40 +000020#include "TNonblockingServer.h"
David Reisse11f3072008-10-07 21:39:19 +000021#include <concurrency/Exception.h>
David Reiss1c20c872010-03-09 05:20:14 +000022#include <transport/TSocket.h>
Mark Slee2f6404d2006-10-10 01:37:40 +000023
Mark Sleee02385b2007-06-09 01:21:16 +000024#include <iostream>
Roger Meier30aae0c2011-07-08 12:23:31 +000025
26#ifdef HAVE_SYS_SOCKET_H
Mark Slee2f6404d2006-10-10 01:37:40 +000027#include <sys/socket.h>
Roger Meier30aae0c2011-07-08 12:23:31 +000028#endif
29
30#ifdef HAVE_NETINET_IN_H
Mark Slee2f6404d2006-10-10 01:37:40 +000031#include <netinet/in.h>
32#include <netinet/tcp.h>
Bryan Duxbury76c43682011-08-24 21:26:48 +000033#include <arpa/inet.h>
Roger Meier30aae0c2011-07-08 12:23:31 +000034#endif
35
36#ifdef HAVE_NETDB_H
Mark Sleefb4b5142007-11-20 01:27:08 +000037#include <netdb.h>
Roger Meier30aae0c2011-07-08 12:23:31 +000038#endif
39
Mark Slee2f6404d2006-10-10 01:37:40 +000040#include <fcntl.h>
41#include <errno.h>
42#include <assert.h>
43
David Reiss9b903442009-10-21 05:51:28 +000044#ifndef AF_LOCAL
45#define AF_LOCAL AF_UNIX
46#endif
47
T Jake Lucianib5e62212009-01-31 22:36:20 +000048namespace apache { namespace thrift { namespace server {
Mark Slee2f6404d2006-10-10 01:37:40 +000049
T Jake Lucianib5e62212009-01-31 22:36:20 +000050using namespace apache::thrift::protocol;
51using namespace apache::thrift::transport;
52using namespace apache::thrift::concurrency;
Mark Sleee02385b2007-06-09 01:21:16 +000053using namespace std;
David Reiss1c20c872010-03-09 05:20:14 +000054using apache::thrift::transport::TSocket;
55using apache::thrift::transport::TTransportException;
Mark Sleee02385b2007-06-09 01:21:16 +000056
57class TConnection::Task: public Runnable {
58 public:
59 Task(boost::shared_ptr<TProcessor> processor,
60 boost::shared_ptr<TProtocol> input,
61 boost::shared_ptr<TProtocol> output,
David Reiss01fe1532010-03-09 05:19:25 +000062 TConnection* connection) :
Mark Sleee02385b2007-06-09 01:21:16 +000063 processor_(processor),
64 input_(input),
65 output_(output),
David Reiss105961d2010-10-06 17:10:17 +000066 connection_(connection),
67 serverEventHandler_(connection_->getServerEventHandler()),
68 connectionContext_(connection_->getConnectionContext()) {}
Mark Sleee02385b2007-06-09 01:21:16 +000069
70 void run() {
71 try {
David Reiss105961d2010-10-06 17:10:17 +000072 for (;;) {
73 if (serverEventHandler_ != NULL) {
74 serverEventHandler_->processContext(connectionContext_, connection_->getTSocket());
75 }
76 if (!processor_->process(input_, output_, connectionContext_) ||
77 !input_->getTransport()->peek()) {
Mark Sleee02385b2007-06-09 01:21:16 +000078 break;
79 }
80 }
81 } catch (TTransportException& ttx) {
David Reissa79e4882008-03-05 07:51:47 +000082 cerr << "TNonblockingServer client died: " << ttx.what() << endl;
Mark Sleee02385b2007-06-09 01:21:16 +000083 } catch (TException& x) {
David Reissa79e4882008-03-05 07:51:47 +000084 cerr << "TNonblockingServer exception: " << x.what() << endl;
David Reiss28e88ec2010-03-09 05:19:27 +000085 } catch (bad_alloc&) {
86 cerr << "TNonblockingServer caught bad_alloc exception.";
87 exit(-1);
Mark Sleee02385b2007-06-09 01:21:16 +000088 } catch (...) {
David Reissa79e4882008-03-05 07:51:47 +000089 cerr << "TNonblockingServer uncaught exception." << endl;
Mark Sleee02385b2007-06-09 01:21:16 +000090 }
Mark Slee79b16942007-11-26 19:05:29 +000091
David Reiss01fe1532010-03-09 05:19:25 +000092 // Signal completion back to the libevent thread via a pipe
93 if (!connection_->notifyServer()) {
94 throw TException("TNonblockingServer::Task::run: failed write on notify pipe");
Mark Sleee02385b2007-06-09 01:21:16 +000095 }
David Reiss01fe1532010-03-09 05:19:25 +000096 }
97
98 TConnection* getTConnection() {
99 return connection_;
Mark Sleee02385b2007-06-09 01:21:16 +0000100 }
101
102 private:
103 boost::shared_ptr<TProcessor> processor_;
104 boost::shared_ptr<TProtocol> input_;
105 boost::shared_ptr<TProtocol> output_;
David Reiss01fe1532010-03-09 05:19:25 +0000106 TConnection* connection_;
David Reiss105961d2010-10-06 17:10:17 +0000107 boost::shared_ptr<TServerEventHandler> serverEventHandler_;
108 void* connectionContext_;
Mark Sleee02385b2007-06-09 01:21:16 +0000109};
Mark Slee5ea15f92007-03-05 22:55:59 +0000110
David Reiss105961d2010-10-06 17:10:17 +0000111void TConnection::init(int socket, short eventFlags, TNonblockingServer* s,
112 const sockaddr* addr, socklen_t addrLen) {
113 tSocket_->setSocketFD(socket);
114 tSocket_->setCachedAddress(addr, addrLen);
115
Mark Slee2f6404d2006-10-10 01:37:40 +0000116 server_ = s;
117 appState_ = APP_INIT;
118 eventFlags_ = 0;
119
120 readBufferPos_ = 0;
121 readWant_ = 0;
122
123 writeBuffer_ = NULL;
124 writeBufferSize_ = 0;
125 writeBufferPos_ = 0;
David Reiss54bec5d2010-10-06 17:10:45 +0000126 largestWriteBufferSize_ = 0;
Mark Slee2f6404d2006-10-10 01:37:40 +0000127
David Reiss89a12942010-10-06 17:10:52 +0000128 socketState_ = SOCKET_RECV_FRAMING;
Mark Slee2f6404d2006-10-10 01:37:40 +0000129 appState_ = APP_INIT;
David Reiss54bec5d2010-10-06 17:10:45 +0000130 callsForResize_ = 0;
Mark Slee79b16942007-11-26 19:05:29 +0000131
Mark Slee2f6404d2006-10-10 01:37:40 +0000132 // Set flags, which also registers the event
133 setFlags(eventFlags);
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000134
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000135 // get input/transports
136 factoryInputTransport_ = s->getInputTransportFactory()->getTransport(inputTransport_);
137 factoryOutputTransport_ = s->getOutputTransportFactory()->getTransport(outputTransport_);
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000138
139 // Create protocol
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000140 inputProtocol_ = s->getInputProtocolFactory()->getProtocol(factoryInputTransport_);
141 outputProtocol_ = s->getOutputProtocolFactory()->getProtocol(factoryOutputTransport_);
David Reiss105961d2010-10-06 17:10:17 +0000142
143 // Set up for any server event handler
144 serverEventHandler_ = server_->getEventHandler();
145 if (serverEventHandler_ != NULL) {
146 connectionContext_ = serverEventHandler_->createContext(inputProtocol_, outputProtocol_);
147 } else {
148 connectionContext_ = NULL;
149 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000150}
151
152void TConnection::workSocket() {
David Reiss105961d2010-10-06 17:10:17 +0000153 int got=0, left=0, sent=0;
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000154 uint32_t fetch = 0;
Mark Slee2f6404d2006-10-10 01:37:40 +0000155
156 switch (socketState_) {
David Reiss89a12942010-10-06 17:10:52 +0000157 case SOCKET_RECV_FRAMING:
158 union {
159 uint8_t buf[sizeof(uint32_t)];
160 int32_t size;
161 } framing;
Mark Slee2f6404d2006-10-10 01:37:40 +0000162
David Reiss89a12942010-10-06 17:10:52 +0000163 // if we've already received some bytes we kept them here
164 framing.size = readWant_;
165 // determine size of this frame
166 try {
167 // Read from the socket
168 fetch = tSocket_->read(&framing.buf[readBufferPos_],
169 uint32_t(sizeof(framing.size) - readBufferPos_));
170 if (fetch == 0) {
171 // Whenever we get here it means a remote disconnect
Mark Slee2f6404d2006-10-10 01:37:40 +0000172 close();
173 return;
174 }
David Reiss89a12942010-10-06 17:10:52 +0000175 readBufferPos_ += fetch;
176 } catch (TTransportException& te) {
177 GlobalOutput.printf("TConnection::workSocket(): %s", te.what());
178 close();
179
180 return;
Mark Slee2f6404d2006-10-10 01:37:40 +0000181 }
182
David Reiss89a12942010-10-06 17:10:52 +0000183 if (readBufferPos_ < sizeof(framing.size)) {
184 // more needed before frame size is known -- save what we have so far
185 readWant_ = framing.size;
186 return;
187 }
188
189 readWant_ = ntohl(framing.size);
190 if (static_cast<int>(readWant_) <= 0) {
191 GlobalOutput.printf("TConnection:workSocket() Negative frame size %d, remote side not using TFramedTransport?", static_cast<int>(readWant_));
192 close();
193 return;
194 }
195 // size known; now get the rest of the frame
196 transition();
197 return;
198
199 case SOCKET_RECV:
200 // It is an error to be in this state if we already have all the data
201 assert(readBufferPos_ < readWant_);
202
David Reiss105961d2010-10-06 17:10:17 +0000203 try {
204 // Read from the socket
205 fetch = readWant_ - readBufferPos_;
206 got = tSocket_->read(readBuffer_ + readBufferPos_, fetch);
207 }
208 catch (TTransportException& te) {
209 GlobalOutput.printf("TConnection::workSocket(): %s", te.what());
210 close();
Mark Slee79b16942007-11-26 19:05:29 +0000211
David Reiss105961d2010-10-06 17:10:17 +0000212 return;
213 }
214
Mark Slee2f6404d2006-10-10 01:37:40 +0000215 if (got > 0) {
216 // Move along in the buffer
217 readBufferPos_ += got;
218
219 // Check that we did not overdo it
220 assert(readBufferPos_ <= readWant_);
Mark Slee79b16942007-11-26 19:05:29 +0000221
Mark Slee2f6404d2006-10-10 01:37:40 +0000222 // We are done reading, move onto the next state
223 if (readBufferPos_ == readWant_) {
224 transition();
225 }
226 return;
Mark Slee2f6404d2006-10-10 01:37:40 +0000227 }
228
229 // Whenever we get down here it means a remote disconnect
230 close();
Mark Slee79b16942007-11-26 19:05:29 +0000231
Mark Slee2f6404d2006-10-10 01:37:40 +0000232 return;
233
234 case SOCKET_SEND:
235 // Should never have position past size
236 assert(writeBufferPos_ <= writeBufferSize_);
237
238 // If there is no data to send, then let us move on
239 if (writeBufferPos_ == writeBufferSize_) {
Mark Slee79b16942007-11-26 19:05:29 +0000240 GlobalOutput("WARNING: Send state with no data to send\n");
Mark Slee2f6404d2006-10-10 01:37:40 +0000241 transition();
242 return;
243 }
244
David Reiss105961d2010-10-06 17:10:17 +0000245 try {
246 left = writeBufferSize_ - writeBufferPos_;
247 sent = tSocket_->write_partial(writeBuffer_ + writeBufferPos_, left);
248 }
249 catch (TTransportException& te) {
250 GlobalOutput.printf("TConnection::workSocket(): %s ", te.what());
Mark Slee2f6404d2006-10-10 01:37:40 +0000251 close();
252 return;
253 }
254
255 writeBufferPos_ += sent;
256
257 // Did we overdo it?
258 assert(writeBufferPos_ <= writeBufferSize_);
259
Mark Slee79b16942007-11-26 19:05:29 +0000260 // We are done!
Mark Slee2f6404d2006-10-10 01:37:40 +0000261 if (writeBufferPos_ == writeBufferSize_) {
262 transition();
263 }
264
265 return;
266
267 default:
David Reiss3bb5e052010-01-25 19:31:31 +0000268 GlobalOutput.printf("Unexpected Socket State %d", socketState_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000269 assert(0);
270 }
271}
272
273/**
274 * This is called when the application transitions from one state into
275 * another. This means that it has finished writing the data that it needed
276 * to, or finished receiving the data that it needed to.
277 */
278void TConnection::transition() {
279 // Switch upon the state that we are currently in and move to a new state
280 switch (appState_) {
281
282 case APP_READ_REQUEST:
283 // We are done reading the request, package the read buffer into transport
284 // and get back some data from the dispatch function
285 inputTransport_->resetBuffer(readBuffer_, readBufferPos_);
David Reiss7197efb2010-10-06 17:10:43 +0000286 outputTransport_->resetBuffer();
David Reiss52cb7a72008-06-30 21:40:35 +0000287 // Prepend four bytes of blank space to the buffer so we can
288 // write the frame size there later.
289 outputTransport_->getWritePtr(4);
290 outputTransport_->wroteBytes(4);
Mark Slee79b16942007-11-26 19:05:29 +0000291
David Reiss01fe1532010-03-09 05:19:25 +0000292 server_->incrementActiveProcessors();
293
Mark Sleee02385b2007-06-09 01:21:16 +0000294 if (server_->isThreadPoolProcessing()) {
295 // We are setting up a Task to do this work and we will wait on it
Mark Slee79b16942007-11-26 19:05:29 +0000296
David Reiss01fe1532010-03-09 05:19:25 +0000297 // Create task and dispatch to the thread manager
298 boost::shared_ptr<Runnable> task =
299 boost::shared_ptr<Runnable>(new Task(server_->getProcessor(),
300 inputProtocol_,
301 outputProtocol_,
302 this));
303 // The application is now waiting on the task to finish
304 appState_ = APP_WAIT_TASK;
Mark Slee2f6404d2006-10-10 01:37:40 +0000305
David Reisse11f3072008-10-07 21:39:19 +0000306 try {
307 server_->addTask(task);
308 } catch (IllegalStateException & ise) {
309 // The ThreadManager is not ready to handle any more tasks (it's probably shutting down).
David Reissc53a5942008-10-07 23:55:24 +0000310 GlobalOutput.printf("IllegalStateException: Server::process() %s", ise.what());
David Reisse11f3072008-10-07 21:39:19 +0000311 close();
312 }
Mark Slee402ee282007-08-23 01:43:20 +0000313
David Reiss01fe1532010-03-09 05:19:25 +0000314 // Set this connection idle so that libevent doesn't process more
315 // data on it while we're still waiting for the threadmanager to
316 // finish this task
317 setIdle();
318 return;
Mark Sleee02385b2007-06-09 01:21:16 +0000319 } else {
320 try {
321 // Invoke the processor
David Reiss23248712010-10-06 17:10:08 +0000322 server_->getProcessor()->process(inputProtocol_, outputProtocol_, NULL);
Mark Sleee02385b2007-06-09 01:21:16 +0000323 } catch (TTransportException &ttx) {
David Reiss01e55c12008-07-13 22:18:51 +0000324 GlobalOutput.printf("TTransportException: Server::process() %s", ttx.what());
David Reiss01fe1532010-03-09 05:19:25 +0000325 server_->decrementActiveProcessors();
Mark Sleee02385b2007-06-09 01:21:16 +0000326 close();
327 return;
328 } catch (TException &x) {
David Reiss01e55c12008-07-13 22:18:51 +0000329 GlobalOutput.printf("TException: Server::process() %s", x.what());
David Reiss01fe1532010-03-09 05:19:25 +0000330 server_->decrementActiveProcessors();
Mark Slee79b16942007-11-26 19:05:29 +0000331 close();
Mark Sleee02385b2007-06-09 01:21:16 +0000332 return;
333 } catch (...) {
David Reiss01e55c12008-07-13 22:18:51 +0000334 GlobalOutput.printf("Server::process() unknown exception");
David Reiss01fe1532010-03-09 05:19:25 +0000335 server_->decrementActiveProcessors();
Mark Sleee02385b2007-06-09 01:21:16 +0000336 close();
337 return;
338 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000339 }
340
Mark Slee402ee282007-08-23 01:43:20 +0000341 // Intentionally fall through here, the call to process has written into
342 // the writeBuffer_
343
Mark Sleee02385b2007-06-09 01:21:16 +0000344 case APP_WAIT_TASK:
345 // We have now finished processing a task and the result has been written
346 // into the outputTransport_, so we grab its contents and place them into
347 // the writeBuffer_ for actual writing by the libevent thread
348
David Reiss01fe1532010-03-09 05:19:25 +0000349 server_->decrementActiveProcessors();
Mark Slee2f6404d2006-10-10 01:37:40 +0000350 // Get the result of the operation
351 outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_);
352
353 // If the function call generated return data, then move into the send
354 // state and get going
David Reissaf787782008-07-03 20:29:34 +0000355 // 4 bytes were reserved for frame size
David Reiss52cb7a72008-06-30 21:40:35 +0000356 if (writeBufferSize_ > 4) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000357
358 // Move into write state
359 writeBufferPos_ = 0;
360 socketState_ = SOCKET_SEND;
Mark Slee92f00fb2006-10-25 01:28:17 +0000361
David Reissaf787782008-07-03 20:29:34 +0000362 // Put the frame size into the write buffer
363 int32_t frameSize = (int32_t)htonl(writeBufferSize_ - 4);
364 memcpy(writeBuffer_, &frameSize, 4);
Mark Slee2f6404d2006-10-10 01:37:40 +0000365
366 // Socket into write mode
David Reiss52cb7a72008-06-30 21:40:35 +0000367 appState_ = APP_SEND_RESULT;
Mark Slee2f6404d2006-10-10 01:37:40 +0000368 setWrite();
369
370 // Try to work the socket immediately
Mark Sleee02385b2007-06-09 01:21:16 +0000371 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000372
373 return;
374 }
375
David Reissc51986f2009-03-24 20:01:25 +0000376 // In this case, the request was oneway and we should fall through
Mark Slee2f6404d2006-10-10 01:37:40 +0000377 // right back into the read frame header state
Mark Slee92f00fb2006-10-25 01:28:17 +0000378 goto LABEL_APP_INIT;
379
Mark Slee2f6404d2006-10-10 01:37:40 +0000380 case APP_SEND_RESULT:
David Reiss54bec5d2010-10-06 17:10:45 +0000381 // it's now safe to perform buffer size housekeeping.
382 if (writeBufferSize_ > largestWriteBufferSize_) {
383 largestWriteBufferSize_ = writeBufferSize_;
384 }
385 if (server_->getResizeBufferEveryN() > 0
386 && ++callsForResize_ >= server_->getResizeBufferEveryN()) {
387 checkIdleBufferMemLimit(server_->getIdleReadBufferLimit(),
388 server_->getIdleWriteBufferLimit());
389 callsForResize_ = 0;
390 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000391
392 // N.B.: We also intentionally fall through here into the INIT state!
393
Mark Slee92f00fb2006-10-25 01:28:17 +0000394 LABEL_APP_INIT:
Mark Slee2f6404d2006-10-10 01:37:40 +0000395 case APP_INIT:
396
397 // Clear write buffer variables
398 writeBuffer_ = NULL;
399 writeBufferPos_ = 0;
400 writeBufferSize_ = 0;
401
Mark Slee2f6404d2006-10-10 01:37:40 +0000402 // Into read4 state we go
David Reiss89a12942010-10-06 17:10:52 +0000403 socketState_ = SOCKET_RECV_FRAMING;
Mark Slee2f6404d2006-10-10 01:37:40 +0000404 appState_ = APP_READ_FRAME_SIZE;
405
David Reiss89a12942010-10-06 17:10:52 +0000406 readBufferPos_ = 0;
407
Mark Slee2f6404d2006-10-10 01:37:40 +0000408 // Register read event
409 setRead();
David Reiss84e63ab2008-03-07 20:12:28 +0000410
Mark Slee2f6404d2006-10-10 01:37:40 +0000411 // Try to work the socket right away
Mark Sleee02385b2007-06-09 01:21:16 +0000412 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000413
414 return;
415
416 case APP_READ_FRAME_SIZE:
David Reiss89a12942010-10-06 17:10:52 +0000417 // We just read the request length
418 // Double the buffer size until it is big enough
419 if (readWant_ > readBufferSize_) {
420 if (readBufferSize_ == 0) {
421 readBufferSize_ = 1;
422 }
423 uint32_t newSize = readBufferSize_;
424 while (readWant_ > newSize) {
425 newSize *= 2;
426 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000427
David Reiss89a12942010-10-06 17:10:52 +0000428 uint8_t* newBuffer = (uint8_t*)std::realloc(readBuffer_, newSize);
429 if (newBuffer == NULL) {
430 // nothing else to be done...
431 throw std::bad_alloc();
432 }
433 readBuffer_ = newBuffer;
434 readBufferSize_ = newSize;
Mark Slee2f6404d2006-10-10 01:37:40 +0000435 }
436
Mark Slee2f6404d2006-10-10 01:37:40 +0000437 readBufferPos_= 0;
438
439 // Move into read request state
David Reiss89a12942010-10-06 17:10:52 +0000440 socketState_ = SOCKET_RECV;
Mark Slee2f6404d2006-10-10 01:37:40 +0000441 appState_ = APP_READ_REQUEST;
442
443 // Work the socket right away
Mark Sleee02385b2007-06-09 01:21:16 +0000444 // workSocket();
Mark Slee2f6404d2006-10-10 01:37:40 +0000445
446 return;
447
David Reiss01fe1532010-03-09 05:19:25 +0000448 case APP_CLOSE_CONNECTION:
449 server_->decrementActiveProcessors();
450 close();
451 return;
452
Mark Slee2f6404d2006-10-10 01:37:40 +0000453 default:
David Reiss3bb5e052010-01-25 19:31:31 +0000454 GlobalOutput.printf("Unexpected Application State %d", appState_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000455 assert(0);
456 }
457}
458
459void TConnection::setFlags(short eventFlags) {
460 // Catch the do nothing case
461 if (eventFlags_ == eventFlags) {
462 return;
463 }
464
465 // Delete a previously existing event
466 if (eventFlags_ != 0) {
467 if (event_del(&event_) == -1) {
boz6ded7752007-06-05 22:41:18 +0000468 GlobalOutput("TConnection::setFlags event_del");
Mark Slee2f6404d2006-10-10 01:37:40 +0000469 return;
470 }
471 }
472
473 // Update in memory structure
474 eventFlags_ = eventFlags;
475
Mark Slee402ee282007-08-23 01:43:20 +0000476 // Do not call event_set if there are no flags
477 if (!eventFlags_) {
478 return;
479 }
480
David Reiss01fe1532010-03-09 05:19:25 +0000481 /*
Mark Slee2f6404d2006-10-10 01:37:40 +0000482 * event_set:
483 *
484 * Prepares the event structure &event to be used in future calls to
485 * event_add() and event_del(). The event will be prepared to call the
Mark Sleee02385b2007-06-09 01:21:16 +0000486 * eventHandler using the 'sock' file descriptor to monitor events.
Mark Slee2f6404d2006-10-10 01:37:40 +0000487 *
488 * The events can be either EV_READ, EV_WRITE, or both, indicating
489 * that an application can read or write from the file respectively without
490 * blocking.
491 *
Mark Sleee02385b2007-06-09 01:21:16 +0000492 * The eventHandler will be called with the file descriptor that triggered
Mark Slee2f6404d2006-10-10 01:37:40 +0000493 * the event and the type of event which will be one of: EV_TIMEOUT,
494 * EV_SIGNAL, EV_READ, EV_WRITE.
495 *
496 * The additional flag EV_PERSIST makes an event_add() persistent until
497 * event_del() has been called.
498 *
499 * Once initialized, the &event struct can be used repeatedly with
500 * event_add() and event_del() and does not need to be reinitialized unless
Mark Sleee02385b2007-06-09 01:21:16 +0000501 * the eventHandler and/or the argument to it are to be changed. However,
Mark Slee2f6404d2006-10-10 01:37:40 +0000502 * when an ev structure has been added to libevent using event_add() the
503 * structure must persist until the event occurs (assuming EV_PERSIST
504 * is not set) or is removed using event_del(). You may not reuse the same
505 * ev structure for multiple monitored descriptors; each descriptor needs
506 * its own ev.
507 */
David Reiss105961d2010-10-06 17:10:17 +0000508 event_set(&event_, tSocket_->getSocketFD(), eventFlags_,
509 TConnection::eventHandler, this);
Mark Slee79b16942007-11-26 19:05:29 +0000510 event_base_set(server_->getEventBase(), &event_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000511
512 // Add the event
513 if (event_add(&event_, 0) == -1) {
Mark Slee17496a02007-08-02 06:37:40 +0000514 GlobalOutput("TConnection::setFlags(): could not event_add");
Mark Slee2f6404d2006-10-10 01:37:40 +0000515 }
516}
517
518/**
519 * Closes a connection
520 */
521void TConnection::close() {
522 // Delete the registered libevent
523 if (event_del(&event_) == -1) {
David Reiss105961d2010-10-06 17:10:17 +0000524 GlobalOutput.perror("TConnection::close() event_del", errno);
525 }
526
527 if (serverEventHandler_ != NULL) {
528 serverEventHandler_->deleteContext(connectionContext_, inputProtocol_, outputProtocol_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000529 }
530
531 // Close the socket
David Reiss105961d2010-10-06 17:10:17 +0000532 tSocket_->close();
Mark Slee2f6404d2006-10-10 01:37:40 +0000533
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000534 // close any factory produced transports
535 factoryInputTransport_->close();
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000536 factoryOutputTransport_->close();
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000537
Mark Slee2f6404d2006-10-10 01:37:40 +0000538 // Give this object back to the server that owns it
539 server_->returnConnection(this);
540}
541
David Reiss54bec5d2010-10-06 17:10:45 +0000542void TConnection::checkIdleBufferMemLimit(size_t readLimit,
543 size_t writeLimit) {
544 if (readLimit > 0 && readBufferSize_ > readLimit) {
David Reiss89a12942010-10-06 17:10:52 +0000545 free(readBuffer_);
546 readBuffer_ = NULL;
547 readBufferSize_ = 0;
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000548 }
David Reiss54bec5d2010-10-06 17:10:45 +0000549
550 if (writeLimit > 0 && largestWriteBufferSize_ > writeLimit) {
551 // just start over
David Reiss89a12942010-10-06 17:10:52 +0000552 outputTransport_->resetBuffer(server_->getWriteBufferDefaultSize());
David Reiss54bec5d2010-10-06 17:10:45 +0000553 largestWriteBufferSize_ = 0;
554 }
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000555}
556
David Reiss8ede8182010-09-02 15:26:28 +0000557TNonblockingServer::~TNonblockingServer() {
558 // TODO: We currently leak any active TConnection objects.
559 // Since we're shutting down and destroying the event_base, the TConnection
560 // objects will never receive any additional callbacks. (And even if they
561 // did, it would be bad, since they keep a pointer around to the server,
562 // which is being destroyed.)
563
564 // Clean up unused TConnection objects in connectionStack_
565 while (!connectionStack_.empty()) {
566 TConnection* connection = connectionStack_.top();
567 connectionStack_.pop();
568 delete connection;
569 }
570
Roger Meierc1905582011-08-02 23:37:36 +0000571 if (eventBase_ && ownEventBase_) {
David Reiss8ede8182010-09-02 15:26:28 +0000572 event_base_free(eventBase_);
573 }
574
575 if (serverSocket_ >= 0) {
576 close(serverSocket_);
577 }
578}
579
Mark Slee2f6404d2006-10-10 01:37:40 +0000580/**
581 * Creates a new connection either by reusing an object off the stack or
582 * by allocating a new one entirely
583 */
David Reiss105961d2010-10-06 17:10:17 +0000584TConnection* TNonblockingServer::createConnection(int socket, short flags,
585 const sockaddr* addr,
586 socklen_t addrLen) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000587 // Check the stack
588 if (connectionStack_.empty()) {
David Reiss105961d2010-10-06 17:10:17 +0000589 return new TConnection(socket, flags, this, addr, addrLen);
Mark Slee2f6404d2006-10-10 01:37:40 +0000590 } else {
591 TConnection* result = connectionStack_.top();
592 connectionStack_.pop();
David Reiss105961d2010-10-06 17:10:17 +0000593 result->init(socket, flags, this, addr, addrLen);
Mark Slee2f6404d2006-10-10 01:37:40 +0000594 return result;
595 }
596}
597
598/**
599 * Returns a connection to the stack
600 */
601void TNonblockingServer::returnConnection(TConnection* connection) {
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000602 if (connectionStackLimit_ &&
603 (connectionStack_.size() >= connectionStackLimit_)) {
604 delete connection;
605 } else {
David Reiss54bec5d2010-10-06 17:10:45 +0000606 connection->checkIdleBufferMemLimit(idleReadBufferLimit_, idleWriteBufferLimit_);
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000607 connectionStack_.push(connection);
608 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000609}
610
611/**
David Reissa79e4882008-03-05 07:51:47 +0000612 * Server socket had something happen. We accept all waiting client
613 * connections on fd and assign TConnection objects to handle those requests.
Mark Slee2f6404d2006-10-10 01:37:40 +0000614 */
615void TNonblockingServer::handleEvent(int fd, short which) {
Roger Meier3b771a12010-11-17 22:11:26 +0000616 (void) which;
David Reiss3bb5e052010-01-25 19:31:31 +0000617 // Make sure that libevent didn't mess up the socket handles
Mark Slee2f6404d2006-10-10 01:37:40 +0000618 assert(fd == serverSocket_);
Mark Slee79b16942007-11-26 19:05:29 +0000619
Mark Slee2f6404d2006-10-10 01:37:40 +0000620 // Server socket accepted a new connection
621 socklen_t addrLen;
David Reiss105961d2010-10-06 17:10:17 +0000622 sockaddr_storage addrStorage;
623 sockaddr* addrp = (sockaddr*)&addrStorage;
624 addrLen = sizeof(addrStorage);
Mark Slee79b16942007-11-26 19:05:29 +0000625
Mark Slee2f6404d2006-10-10 01:37:40 +0000626 // Going to accept a new client socket
627 int clientSocket;
Mark Slee79b16942007-11-26 19:05:29 +0000628
Mark Slee2f6404d2006-10-10 01:37:40 +0000629 // Accept as many new clients as possible, even though libevent signaled only
630 // one, this helps us to avoid having to go back into the libevent engine so
631 // many times
David Reiss105961d2010-10-06 17:10:17 +0000632 while ((clientSocket = ::accept(fd, addrp, &addrLen)) != -1) {
David Reiss01fe1532010-03-09 05:19:25 +0000633 // If we're overloaded, take action here
634 if (overloadAction_ != T_OVERLOAD_NO_ACTION && serverOverloaded()) {
635 nConnectionsDropped_++;
636 nTotalConnectionsDropped_++;
637 if (overloadAction_ == T_OVERLOAD_CLOSE_ON_ACCEPT) {
638 close(clientSocket);
David Reiss83b8fda2010-03-09 05:19:34 +0000639 return;
David Reiss01fe1532010-03-09 05:19:25 +0000640 } else if (overloadAction_ == T_OVERLOAD_DRAIN_TASK_QUEUE) {
641 if (!drainPendingTask()) {
642 // Nothing left to discard, so we drop connection instead.
643 close(clientSocket);
David Reiss83b8fda2010-03-09 05:19:34 +0000644 return;
David Reiss01fe1532010-03-09 05:19:25 +0000645 }
646 }
647 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000648 // Explicitly set this socket to NONBLOCK mode
649 int flags;
650 if ((flags = fcntl(clientSocket, F_GETFL, 0)) < 0 ||
651 fcntl(clientSocket, F_SETFL, flags | O_NONBLOCK) < 0) {
David Reiss01e55c12008-07-13 22:18:51 +0000652 GlobalOutput.perror("thriftServerEventHandler: set O_NONBLOCK (fcntl) ", errno);
Mark Slee2f6404d2006-10-10 01:37:40 +0000653 close(clientSocket);
654 return;
655 }
656
657 // Create a new TConnection for this client socket.
658 TConnection* clientConnection =
David Reiss105961d2010-10-06 17:10:17 +0000659 createConnection(clientSocket, EV_READ | EV_PERSIST, addrp, addrLen);
Mark Slee2f6404d2006-10-10 01:37:40 +0000660
661 // Fail fast if we could not create a TConnection object
662 if (clientConnection == NULL) {
David Reiss01e55c12008-07-13 22:18:51 +0000663 GlobalOutput.printf("thriftServerEventHandler: failed TConnection factory");
Mark Slee2f6404d2006-10-10 01:37:40 +0000664 close(clientSocket);
665 return;
666 }
667
668 // Put this client connection into the proper state
669 clientConnection->transition();
David Reiss3e7fca42009-09-19 01:59:13 +0000670
671 // addrLen is written by the accept() call, so needs to be set before the next call.
David Reiss105961d2010-10-06 17:10:17 +0000672 addrLen = sizeof(addrStorage);
Mark Slee2f6404d2006-10-10 01:37:40 +0000673 }
Mark Slee79b16942007-11-26 19:05:29 +0000674
Mark Slee2f6404d2006-10-10 01:37:40 +0000675 // Done looping accept, now we have to make sure the error is due to
676 // blocking. Any other error is a problem
677 if (errno != EAGAIN && errno != EWOULDBLOCK) {
David Reiss01e55c12008-07-13 22:18:51 +0000678 GlobalOutput.perror("thriftServerEventHandler: accept() ", errno);
Mark Slee2f6404d2006-10-10 01:37:40 +0000679 }
680}
681
682/**
Mark Slee79b16942007-11-26 19:05:29 +0000683 * Creates a socket to listen on and binds it to the local port.
Mark Slee2f6404d2006-10-10 01:37:40 +0000684 */
Mark Slee79b16942007-11-26 19:05:29 +0000685void TNonblockingServer::listenSocket() {
686 int s;
Mark Sleefb4b5142007-11-20 01:27:08 +0000687 struct addrinfo hints, *res, *res0;
688 int error;
Mark Slee79b16942007-11-26 19:05:29 +0000689
Mark Sleefb4b5142007-11-20 01:27:08 +0000690 char port[sizeof("65536") + 1];
691 memset(&hints, 0, sizeof(hints));
692 hints.ai_family = PF_UNSPEC;
693 hints.ai_socktype = SOCK_STREAM;
Mark Slee256bdc42007-11-27 08:42:19 +0000694 hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
Mark Sleefb4b5142007-11-20 01:27:08 +0000695 sprintf(port, "%d", port_);
696
697 // Wildcard address
698 error = getaddrinfo(NULL, port, &hints, &res0);
699 if (error) {
David Reiss9b209552008-04-08 06:26:05 +0000700 string errStr = "TNonblockingServer::serve() getaddrinfo " + string(gai_strerror(error));
701 GlobalOutput(errStr.c_str());
Mark Sleefb4b5142007-11-20 01:27:08 +0000702 return;
703 }
704
705 // Pick the ipv6 address first since ipv4 addresses can be mapped
706 // into ipv6 space.
707 for (res = res0; res; res = res->ai_next) {
708 if (res->ai_family == AF_INET6 || res->ai_next == NULL)
709 break;
710 }
711
Mark Slee2f6404d2006-10-10 01:37:40 +0000712 // Create the server socket
Mark Slee79b16942007-11-26 19:05:29 +0000713 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
714 if (s == -1) {
715 freeaddrinfo(res0);
716 throw TException("TNonblockingServer::serve() socket() -1");
Mark Slee2f6404d2006-10-10 01:37:40 +0000717 }
718
David Reiss13aea462008-06-10 22:56:04 +0000719 #ifdef IPV6_V6ONLY
David Reisseee98be2010-03-09 05:20:10 +0000720 if (res->ai_family == AF_INET6) {
721 int zero = 0;
Roger Meier30aae0c2011-07-08 12:23:31 +0000722 if (-1 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, const_cast_sockopt(&zero), sizeof(zero))) {
David Reisseee98be2010-03-09 05:20:10 +0000723 GlobalOutput("TServerSocket::listen() IPV6_V6ONLY");
724 }
David Reiss13aea462008-06-10 22:56:04 +0000725 }
726 #endif // #ifdef IPV6_V6ONLY
727
728
Mark Slee79b16942007-11-26 19:05:29 +0000729 int one = 1;
730
731 // Set reuseaddr to avoid 2MSL delay on server restart
Roger Meier30aae0c2011-07-08 12:23:31 +0000732 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, const_cast_sockopt(&one), sizeof(one));
Mark Slee79b16942007-11-26 19:05:29 +0000733
Roger Meier30aae0c2011-07-08 12:23:31 +0000734 if (::bind(s, res->ai_addr, res->ai_addrlen) == -1) {
Mark Slee79b16942007-11-26 19:05:29 +0000735 close(s);
736 freeaddrinfo(res0);
737 throw TException("TNonblockingServer::serve() bind");
738 }
739
740 // Done with the addr info
741 freeaddrinfo(res0);
742
743 // Set up this file descriptor for listening
744 listenSocket(s);
745}
746
747/**
748 * Takes a socket created by listenSocket() and sets various options on it
749 * to prepare for use in the server.
750 */
751void TNonblockingServer::listenSocket(int s) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000752 // Set socket to nonblocking mode
753 int flags;
Mark Slee79b16942007-11-26 19:05:29 +0000754 if ((flags = fcntl(s, F_GETFL, 0)) < 0 ||
755 fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
756 close(s);
757 throw TException("TNonblockingServer::serve() O_NONBLOCK");
Mark Slee2f6404d2006-10-10 01:37:40 +0000758 }
759
760 int one = 1;
761 struct linger ling = {0, 0};
Mark Slee2f6404d2006-10-10 01:37:40 +0000762
763 // Keepalive to ensure full result flushing
Roger Meier30aae0c2011-07-08 12:23:31 +0000764 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, const_cast_sockopt(&one), sizeof(one));
Mark Slee2f6404d2006-10-10 01:37:40 +0000765
766 // Turn linger off to avoid hung sockets
Roger Meier30aae0c2011-07-08 12:23:31 +0000767 setsockopt(s, SOL_SOCKET, SO_LINGER, const_cast_sockopt(&ling), sizeof(ling));
Mark Slee2f6404d2006-10-10 01:37:40 +0000768
769 // Set TCP nodelay if available, MAC OS X Hack
770 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
771 #ifndef TCP_NOPUSH
Roger Meier30aae0c2011-07-08 12:23:31 +0000772 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, const_cast_sockopt(&one), sizeof(one));
Mark Slee2f6404d2006-10-10 01:37:40 +0000773 #endif
774
David Reiss1c20c872010-03-09 05:20:14 +0000775 #ifdef TCP_LOW_MIN_RTO
776 if (TSocket::getUseLowMinRto()) {
Roger Meier30aae0c2011-07-08 12:23:31 +0000777 setsockopt(s, IPPROTO_TCP, TCP_LOW_MIN_RTO, const_cast_sockopt(&one), sizeof(one));
David Reiss1c20c872010-03-09 05:20:14 +0000778 }
779 #endif
780
Mark Slee79b16942007-11-26 19:05:29 +0000781 if (listen(s, LISTEN_BACKLOG) == -1) {
782 close(s);
783 throw TException("TNonblockingServer::serve() listen");
Mark Slee2f6404d2006-10-10 01:37:40 +0000784 }
785
Mark Slee79b16942007-11-26 19:05:29 +0000786 // Cool, this socket is good to go, set it as the serverSocket_
787 serverSocket_ = s;
788}
789
David Reiss01fe1532010-03-09 05:19:25 +0000790void TNonblockingServer::createNotificationPipe() {
Roger Meier30aae0c2011-07-08 12:23:31 +0000791 if(evutil_socketpair(AF_LOCAL, SOCK_STREAM, 0, notificationPipeFDs_) == -1) {
792 GlobalOutput.perror("TNonblockingServer::createNotificationPipe ", EVUTIL_SOCKET_ERROR());
793 throw TException("can't create notification pipe");
David Reiss01fe1532010-03-09 05:19:25 +0000794 }
Roger Meier30aae0c2011-07-08 12:23:31 +0000795 if(evutil_make_socket_nonblocking(notificationPipeFDs_[0])<0 ||
796 evutil_make_socket_nonblocking(notificationPipeFDs_[1])<0) {
David Reiss83b8fda2010-03-09 05:19:34 +0000797 close(notificationPipeFDs_[0]);
798 close(notificationPipeFDs_[1]);
799 throw TException("TNonblockingServer::createNotificationPipe() O_NONBLOCK");
800 }
David Reiss01fe1532010-03-09 05:19:25 +0000801}
802
Mark Slee79b16942007-11-26 19:05:29 +0000803/**
804 * Register the core libevent events onto the proper base.
805 */
Roger Meierc1905582011-08-02 23:37:36 +0000806void TNonblockingServer::registerEvents(event_base* base, bool ownEventBase) {
Mark Slee79b16942007-11-26 19:05:29 +0000807 assert(serverSocket_ != -1);
808 assert(!eventBase_);
809 eventBase_ = base;
Roger Meierc1905582011-08-02 23:37:36 +0000810 ownEventBase_ = ownEventBase;
Mark Slee79b16942007-11-26 19:05:29 +0000811
812 // Print some libevent stats
David Reiss01e55c12008-07-13 22:18:51 +0000813 GlobalOutput.printf("libevent %s method %s",
Mark Slee79b16942007-11-26 19:05:29 +0000814 event_get_version(),
Bryan Duxbury37874ca2011-08-25 17:28:23 +0000815 event_base_get_method(eventBase_));
Mark Slee2f6404d2006-10-10 01:37:40 +0000816
817 // Register the server event
Mark Slee79b16942007-11-26 19:05:29 +0000818 event_set(&serverEvent_,
Mark Slee2f6404d2006-10-10 01:37:40 +0000819 serverSocket_,
820 EV_READ | EV_PERSIST,
821 TNonblockingServer::eventHandler,
822 this);
Mark Slee79b16942007-11-26 19:05:29 +0000823 event_base_set(eventBase_, &serverEvent_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000824
825 // Add the event and start up the server
Mark Slee79b16942007-11-26 19:05:29 +0000826 if (-1 == event_add(&serverEvent_, 0)) {
827 throw TException("TNonblockingServer::serve(): coult not event_add");
Mark Slee2f6404d2006-10-10 01:37:40 +0000828 }
David Reiss01fe1532010-03-09 05:19:25 +0000829 if (threadPoolProcessing_) {
830 // Create an event to be notified when a task finishes
831 event_set(&notificationEvent_,
832 getNotificationRecvFD(),
833 EV_READ | EV_PERSIST,
834 TConnection::taskHandler,
835 this);
David Reiss1c20c872010-03-09 05:20:14 +0000836
David Reiss01fe1532010-03-09 05:19:25 +0000837 // Attach to the base
838 event_base_set(eventBase_, &notificationEvent_);
839
840 // Add the event and start up the server
841 if (-1 == event_add(&notificationEvent_, 0)) {
842 throw TException("TNonblockingServer::serve(): notification event_add fail");
843 }
844 }
845}
846
David Reiss068f4162010-03-09 05:19:45 +0000847void TNonblockingServer::setThreadManager(boost::shared_ptr<ThreadManager> threadManager) {
848 threadManager_ = threadManager;
849 if (threadManager != NULL) {
850 threadManager->setExpireCallback(std::tr1::bind(&TNonblockingServer::expireClose, this, std::tr1::placeholders::_1));
851 threadPoolProcessing_ = true;
852 } else {
853 threadPoolProcessing_ = false;
854 }
855}
856
David Reiss01fe1532010-03-09 05:19:25 +0000857bool TNonblockingServer::serverOverloaded() {
858 size_t activeConnections = numTConnections_ - connectionStack_.size();
859 if (numActiveProcessors_ > maxActiveProcessors_ ||
860 activeConnections > maxConnections_) {
861 if (!overloaded_) {
862 GlobalOutput.printf("thrift non-blocking server overload condition");
863 overloaded_ = true;
864 }
865 } else {
866 if (overloaded_ &&
867 (numActiveProcessors_ <= overloadHysteresis_ * maxActiveProcessors_) &&
868 (activeConnections <= overloadHysteresis_ * maxConnections_)) {
869 GlobalOutput.printf("thrift non-blocking server overload ended; %u dropped (%llu total)",
870 nConnectionsDropped_, nTotalConnectionsDropped_);
871 nConnectionsDropped_ = 0;
872 overloaded_ = false;
873 }
874 }
875
876 return overloaded_;
877}
878
879bool TNonblockingServer::drainPendingTask() {
880 if (threadManager_) {
881 boost::shared_ptr<Runnable> task = threadManager_->removeNextPending();
882 if (task) {
883 TConnection* connection =
884 static_cast<TConnection::Task*>(task.get())->getTConnection();
885 assert(connection && connection->getServer()
886 && connection->getState() == APP_WAIT_TASK);
887 connection->forceClose();
888 return true;
889 }
890 }
891 return false;
Mark Slee79b16942007-11-26 19:05:29 +0000892}
893
David Reiss068f4162010-03-09 05:19:45 +0000894void TNonblockingServer::expireClose(boost::shared_ptr<Runnable> task) {
895 TConnection* connection =
896 static_cast<TConnection::Task*>(task.get())->getTConnection();
897 assert(connection && connection->getServer()
898 && connection->getState() == APP_WAIT_TASK);
899 connection->forceClose();
900}
901
Mark Slee79b16942007-11-26 19:05:29 +0000902/**
903 * Main workhorse function, starts up the server listening on a port and
904 * loops over the libevent handler.
905 */
906void TNonblockingServer::serve() {
907 // Init socket
908 listenSocket();
909
David Reiss01fe1532010-03-09 05:19:25 +0000910 if (threadPoolProcessing_) {
911 // Init task completion notification pipe
912 createNotificationPipe();
913 }
914
Mark Slee79b16942007-11-26 19:05:29 +0000915 // Initialize libevent core
Bryan Duxbury37874ca2011-08-25 17:28:23 +0000916 registerEvents(static_cast<event_base*>(event_base_new()), true);
Mark Slee2f6404d2006-10-10 01:37:40 +0000917
Mark Sleeb4d3e7b2007-11-28 01:51:43 +0000918 // Run the preServe event
919 if (eventHandler_ != NULL) {
920 eventHandler_->preServe();
dweatherford58985992007-06-19 23:10:19 +0000921 }
922
Bryan Duxbury76c43682011-08-24 21:26:48 +0000923 // Run libevent engine, invokes calls to eventHandler
924 // Only returns if stop() is called.
Mark Slee79b16942007-11-26 19:05:29 +0000925 event_base_loop(eventBase_, 0);
Mark Slee2f6404d2006-10-10 01:37:40 +0000926}
927
Bryan Duxbury76c43682011-08-24 21:26:48 +0000928void TNonblockingServer::stop() {
929 if (!eventBase_) {
930 return;
931 }
932
933 // Call event_base_loopbreak() to tell libevent to exit the loop
934 //
935 // (The libevent documentation doesn't explicitly state that this function is
936 // safe to call from another thread. However, all it does is set a variable,
937 // in the event_base, so it should be fine.)
938 event_base_loopbreak(eventBase_);
939
940 // event_base_loopbreak() only causes the loop to exit the next time it wakes
941 // up. We need to force it to wake up, in case there are no real events
942 // it needs to process.
943 //
944 // Attempt to connect to the server socket. If anything fails,
945 // we'll just have to wait until libevent wakes up on its own.
946 //
947 // First create a socket
948 int fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
949 if (fd < 0) {
950 return;
951 }
952
953 // Set up the address
954 struct sockaddr_in addr;
955 addr.sin_family = AF_INET;
956 addr.sin_addr.s_addr = htonl(0x7f000001); // 127.0.0.1
957 addr.sin_port = htons(port_);
958
959 // Finally do the connect().
960 // We don't care about the return value;
961 // we're just going to close the socket either way.
962 connect(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr));
963 close(fd);
964}
965
T Jake Lucianib5e62212009-01-31 22:36:20 +0000966}}} // apache::thrift::server