blob: ea394c80452e1c2ad0a03beb22d7af46610d8138 [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
Konrad Grochowski9be4e682013-06-22 22:03:31 +020020#include <thrift/thrift-config.h>
Roger Meier2fa9c312011-09-05 19:15:53 +000021
Roger Meier4285ba22013-06-10 21:17:23 +020022#include <thrift/server/TNonblockingServer.h>
Roger Meier49ff8b12012-04-13 09:12:31 +000023#include <thrift/concurrency/Exception.h>
24#include <thrift/transport/TSocket.h>
cyyca8af9b2019-01-11 22:13:12 +080025#include <thrift/concurrency/ThreadFactory.h>
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -040026#include <thrift/transport/PlatformSocket.h>
Mark Slee2f6404d2006-10-10 01:37:40 +000027
James E. King, III82ae9572017-08-05 12:23:54 -040028#include <algorithm>
Mark Sleee02385b2007-06-09 01:21:16 +000029#include <iostream>
Lei Feiweib5ebcd12015-04-04 22:12:07 +080030
st0ke961fa702018-10-12 18:37:40 +070031#ifdef HAVE_POLL_H
32#include <poll.h>
33#elif HAVE_SYS_POLL_H
34#include <sys/poll.h>
35#elif HAVE_SYS_SELECT_H
Lei Feiweib5ebcd12015-04-04 22:12:07 +080036#include <sys/select.h>
37#endif
Roger Meier30aae0c2011-07-08 12:23:31 +000038
39#ifdef HAVE_SYS_SOCKET_H
Mark Slee2f6404d2006-10-10 01:37:40 +000040#include <sys/socket.h>
Roger Meier30aae0c2011-07-08 12:23:31 +000041#endif
42
43#ifdef HAVE_NETINET_IN_H
Mark Slee2f6404d2006-10-10 01:37:40 +000044#include <netinet/in.h>
45#include <netinet/tcp.h>
Roger Meier2fa9c312011-09-05 19:15:53 +000046#endif
47
48#ifdef HAVE_ARPA_INET_H
Bryan Duxbury76c43682011-08-24 21:26:48 +000049#include <arpa/inet.h>
Roger Meier30aae0c2011-07-08 12:23:31 +000050#endif
51
52#ifdef HAVE_NETDB_H
Mark Sleefb4b5142007-11-20 01:27:08 +000053#include <netdb.h>
Roger Meier30aae0c2011-07-08 12:23:31 +000054#endif
55
Roger Meier2fa9c312011-09-05 19:15:53 +000056#ifdef HAVE_FCNTL_H
Mark Slee2f6404d2006-10-10 01:37:40 +000057#include <fcntl.h>
Roger Meier2fa9c312011-09-05 19:15:53 +000058#endif
59
Mark Slee2f6404d2006-10-10 01:37:40 +000060#include <assert.h>
Roger Meier12d70532011-12-14 23:35:28 +000061
62#ifdef HAVE_SCHED_H
Jake Farrellb0d95602011-12-06 01:17:26 +000063#include <sched.h>
Roger Meier12d70532011-12-14 23:35:28 +000064#endif
Mark Slee2f6404d2006-10-10 01:37:40 +000065
David Reiss9b903442009-10-21 05:51:28 +000066#ifndef AF_LOCAL
67#define AF_LOCAL AF_UNIX
68#endif
69
James E. King, III7edc8fa2017-01-20 10:11:41 -050070#ifdef HAVE_INTTYPES_H
71#include <inttypes.h>
Roger Meier12d70532011-12-14 23:35:28 +000072#endif
73
James E. King, III7edc8fa2017-01-20 10:11:41 -050074#ifdef HAVE_STDINT_H
75#include <stdint.h>
Antonio Di Monaco796667b2016-01-04 23:05:19 +010076#endif
77
Konrad Grochowski16a23a62014-11-13 15:33:38 +010078namespace apache {
79namespace thrift {
80namespace server {
Mark Slee2f6404d2006-10-10 01:37:40 +000081
T Jake Lucianib5e62212009-01-31 22:36:20 +000082using namespace apache::thrift::protocol;
83using namespace apache::thrift::transport;
84using namespace apache::thrift::concurrency;
David Reiss1c20c872010-03-09 05:20:14 +000085using apache::thrift::transport::TSocket;
86using apache::thrift::transport::TTransportException;
cyy316723a2019-01-05 16:35:14 +080087using std::shared_ptr;
Mark Sleee02385b2007-06-09 01:21:16 +000088
Bryan Duxbury526fa8e2011-08-29 20:28:23 +000089/// Three states for sockets: recv frame size, recv data, and send mode
Konrad Grochowski16a23a62014-11-13 15:33:38 +010090enum TSocketState { SOCKET_RECV_FRAMING, SOCKET_RECV, SOCKET_SEND };
Bryan Duxbury526fa8e2011-08-29 20:28:23 +000091
92/**
93 * Five states for the nonblocking server:
94 * 1) initialize
95 * 2) read 4 byte frame size
96 * 3) read frame of data
97 * 4) send back data (if any)
98 * 5) force immediate connection close
99 */
100enum TAppState {
101 APP_INIT,
102 APP_READ_FRAME_SIZE,
103 APP_READ_REQUEST,
104 APP_WAIT_TASK,
105 APP_SEND_RESULT,
106 APP_CLOSE_CONNECTION
107};
108
109/**
110 * Represents a connection that is handled via libevent. This connection
111 * essentially encapsulates a socket that has some associated libevent state.
112 */
113class TNonblockingServer::TConnection {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100114private:
Jake Farrellb0d95602011-12-06 01:17:26 +0000115 /// Server IO Thread handling this connection
116 TNonblockingIOThread* ioThread_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000117
118 /// Server handle
119 TNonblockingServer* server_;
120
Bryan Duxbury6dd9cd02011-09-01 18:06:20 +0000121 /// TProcessor
cyy316723a2019-01-05 16:35:14 +0800122 std::shared_ptr<TProcessor> processor_;
Bryan Duxbury6dd9cd02011-09-01 18:06:20 +0000123
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000124 /// Object wrapping network socket
cyy316723a2019-01-05 16:35:14 +0800125 std::shared_ptr<TSocket> tSocket_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000126
127 /// Libevent object
128 struct event event_;
129
130 /// Libevent flags
131 short eventFlags_;
132
133 /// Socket mode
134 TSocketState socketState_;
135
136 /// Application state
137 TAppState appState_;
138
139 /// How much data needed to read
140 uint32_t readWant_;
141
142 /// Where in the read buffer are we
143 uint32_t readBufferPos_;
144
145 /// Read buffer
146 uint8_t* readBuffer_;
147
148 /// Read buffer size
149 uint32_t readBufferSize_;
150
151 /// Write buffer
152 uint8_t* writeBuffer_;
153
154 /// Write buffer size
155 uint32_t writeBufferSize_;
156
157 /// How far through writing are we?
158 uint32_t writeBufferPos_;
159
160 /// Largest size of write buffer seen since buffer was constructed
161 size_t largestWriteBufferSize_;
162
163 /// Count of the number of calls for use with getResizeBufferEveryN().
164 int32_t callsForResize_;
165
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000166 /// Transport to read from
cyy316723a2019-01-05 16:35:14 +0800167 std::shared_ptr<TMemoryBuffer> inputTransport_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000168
169 /// Transport that processor writes to
cyy316723a2019-01-05 16:35:14 +0800170 std::shared_ptr<TMemoryBuffer> outputTransport_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000171
172 /// extra transport generated by transport factory (e.g. BufferedRouterTransport)
cyy316723a2019-01-05 16:35:14 +0800173 std::shared_ptr<TTransport> factoryInputTransport_;
174 std::shared_ptr<TTransport> factoryOutputTransport_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000175
176 /// Protocol decoder
cyy316723a2019-01-05 16:35:14 +0800177 std::shared_ptr<TProtocol> inputProtocol_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000178
179 /// Protocol encoder
cyy316723a2019-01-05 16:35:14 +0800180 std::shared_ptr<TProtocol> outputProtocol_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000181
182 /// Server event handler, if any
cyy316723a2019-01-05 16:35:14 +0800183 std::shared_ptr<TServerEventHandler> serverEventHandler_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000184
185 /// Thrift call context, if any
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100186 void* connectionContext_;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000187
188 /// Go into read mode
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100189 void setRead() { setFlags(EV_READ | EV_PERSIST); }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000190
191 /// Go into write mode
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100192 void setWrite() { setFlags(EV_WRITE | EV_PERSIST); }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000193
194 /// Set socket idle
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100195 void setIdle() { setFlags(0); }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000196
197 /**
198 * Set event flags for this connection.
199 *
200 * @param eventFlags flags we pass to libevent for the connection.
201 */
202 void setFlags(short eventFlags);
203
204 /**
205 * Libevent handler called (via our static wrapper) when the connection
206 * socket had something happen. Rather than use the flags libevent passed,
207 * we use the connection state to determine whether we need to read or
208 * write the socket.
209 */
210 void workSocket();
211
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100212public:
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000213 class Task;
214
215 /// Constructor
cyy316723a2019-01-05 16:35:14 +0800216 TConnection(std::shared_ptr<TSocket> socket,
Divya Thaluru808d1432017-08-06 16:36:36 -0700217 TNonblockingIOThread* ioThread) {
Sebastian Zenker042580f2019-01-29 15:48:12 +0100218 readBuffer_ = nullptr;
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000219 readBufferSize_ = 0;
220
Jake Farrellb0d95602011-12-06 01:17:26 +0000221 ioThread_ = ioThread;
222 server_ = ioThread->getServer();
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000223
Jake Farrellb0d95602011-12-06 01:17:26 +0000224 // Allocate input and output transports these only need to be allocated
225 // once per TConnection (they don't need to be reallocated on init() call)
226 inputTransport_.reset(new TMemoryBuffer(readBuffer_, readBufferSize_));
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -0400227 outputTransport_.reset(
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100228 new TMemoryBuffer(static_cast<uint32_t>(server_->getWriteBufferDefaultSize())));
Divya Thaluru808d1432017-08-06 16:36:36 -0700229
230 tSocket_ = socket;
231
232 init(ioThread);
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000233 }
234
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100235 ~TConnection() { std::free(readBuffer_); }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000236
Roger Meier0c04fcc2013-03-22 19:52:08 +0100237 /// Close this connection and free or reset its resources.
238 void close();
239
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100240 /**
241 * Check buffers against any size limits and shrink it if exceeded.
242 *
243 * @param readLimit we reduce read buffer size to this (if nonzero).
244 * @param writeLimit if nonzero and write buffer is larger, replace it.
245 */
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000246 void checkIdleBufferMemLimit(size_t readLimit, size_t writeLimit);
247
248 /// Initialize
Divya Thaluru808d1432017-08-06 16:36:36 -0700249 void init(TNonblockingIOThread* ioThread);
250
251 /// set socket for connection
cyy316723a2019-01-05 16:35:14 +0800252 void setSocket(std::shared_ptr<TSocket> socket);
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000253
254 /**
255 * This is called when the application transitions from one state into
256 * another. This means that it has finished writing the data that it needed
257 * to, or finished receiving the data that it needed to.
258 */
259 void transition();
260
261 /**
262 * C-callable event handler for connection events. Provides a callback
263 * that libevent can understand which invokes connection_->workSocket().
264 *
265 * @param fd the descriptor the event occurred on.
266 * @param which the flags associated with the event.
267 * @param v void* callback arg where we placed TConnection's "this".
268 */
Bryan Duxbury266b1732011-09-01 16:50:28 +0000269 static void eventHandler(evutil_socket_t fd, short /* which */, void* v) {
Konrad Grochowskib7af66e2014-07-08 19:22:44 +0200270 assert(fd == static_cast<evutil_socket_t>(((TConnection*)v)->getTSocket()->getSocketFD()));
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000271 ((TConnection*)v)->workSocket();
272 }
273
274 /**
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000275 * Notification to server that processing has ended on this request.
276 * Can be called either when processing is completed or when a waiting
277 * task has been preemptively terminated (on overload).
278 *
Jake Farrellb0d95602011-12-06 01:17:26 +0000279 * Don't call this from the IO thread itself.
280 *
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -0400281 * @return true if successful, false if unable to notify (check THRIFT_GET_SOCKET_ERROR).
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000282 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100283 bool notifyIOThread() { return ioThread_->notify(this); }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000284
Jake Farrellb0d95602011-12-06 01:17:26 +0000285 /*
286 * Returns the number of this connection's currently assigned IO
287 * thread.
288 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100289 int getIOThreadNumber() const { return ioThread_->getThreadNumber(); }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000290
291 /// Force connection shutdown for this connection.
292 void forceClose() {
293 appState_ = APP_CLOSE_CONNECTION;
Jake Farrellb0d95602011-12-06 01:17:26 +0000294 if (!notifyIOThread()) {
Changli Gao257dcef2017-04-06 00:42:01 +0800295 server_->decrementActiveProcessors();
Jens Geyerfb05cf62014-12-04 21:49:07 +0100296 close();
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000297 throw TException("TConnection::forceClose: failed write on notify pipe");
298 }
299 }
300
301 /// return the server this connection was initialized for.
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100302 TNonblockingServer* getServer() const { return server_; }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000303
304 /// get state of connection.
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100305 TAppState getState() const { return appState_; }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000306
307 /// return the TSocket transport wrapping this network connection
cyy316723a2019-01-05 16:35:14 +0800308 std::shared_ptr<TSocket> getTSocket() const { return tSocket_; }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000309
310 /// return the server event handler if any
cyy316723a2019-01-05 16:35:14 +0800311 std::shared_ptr<TServerEventHandler> getServerEventHandler() { return serverEventHandler_; }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000312
313 /// return the Thrift connection context if any
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100314 void* getConnectionContext() { return connectionContext_; }
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000315};
316
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100317class TNonblockingServer::TConnection::Task : public Runnable {
318public:
cyy316723a2019-01-05 16:35:14 +0800319 Task(std::shared_ptr<TProcessor> processor,
320 std::shared_ptr<TProtocol> input,
321 std::shared_ptr<TProtocol> output,
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100322 TConnection* connection)
323 : processor_(processor),
324 input_(input),
325 output_(output),
326 connection_(connection),
327 serverEventHandler_(connection_->getServerEventHandler()),
328 connectionContext_(connection_->getConnectionContext()) {}
Mark Sleee02385b2007-06-09 01:21:16 +0000329
Sebastian Zenker042580f2019-01-29 15:48:12 +0100330 void run() override {
Mark Sleee02385b2007-06-09 01:21:16 +0000331 try {
David Reiss105961d2010-10-06 17:10:17 +0000332 for (;;) {
Roger Meier72957452013-06-29 00:28:50 +0200333 if (serverEventHandler_) {
David Reiss105961d2010-10-06 17:10:17 +0000334 serverEventHandler_->processContext(connectionContext_, connection_->getTSocket());
335 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100336 if (!processor_->process(input_, output_, connectionContext_)
337 || !input_->getTransport()->peek()) {
Mark Sleee02385b2007-06-09 01:21:16 +0000338 break;
339 }
340 }
Bryan Duxbury1e987582011-08-25 17:33:03 +0000341 } catch (const TTransportException& ttx) {
Jake Farrellb0d95602011-12-06 01:17:26 +0000342 GlobalOutput.printf("TNonblockingServer: client died: %s", ttx.what());
James E. King, III82ae9572017-08-05 12:23:54 -0400343 } catch (const std::bad_alloc&) {
Jake Farrellb0d95602011-12-06 01:17:26 +0000344 GlobalOutput("TNonblockingServer: caught bad_alloc exception.");
Henrique Mendonca962b3532012-09-20 13:19:55 +0000345 exit(1);
Bryan Duxbury1e987582011-08-25 17:33:03 +0000346 } catch (const std::exception& x) {
Jake Farrellb0d95602011-12-06 01:17:26 +0000347 GlobalOutput.printf("TNonblockingServer: process() exception: %s: %s",
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100348 typeid(x).name(),
349 x.what());
Mark Sleee02385b2007-06-09 01:21:16 +0000350 } catch (...) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100351 GlobalOutput.printf("TNonblockingServer: unknown exception while processing.");
Mark Sleee02385b2007-06-09 01:21:16 +0000352 }
Mark Slee79b16942007-11-26 19:05:29 +0000353
David Reiss01fe1532010-03-09 05:19:25 +0000354 // Signal completion back to the libevent thread via a pipe
Jake Farrellb0d95602011-12-06 01:17:26 +0000355 if (!connection_->notifyIOThread()) {
Jens Geyerfb05cf62014-12-04 21:49:07 +0100356 GlobalOutput.printf("TNonblockingServer: failed to notifyIOThread, closing.");
Changli Gao257dcef2017-04-06 00:42:01 +0800357 connection_->server_->decrementActiveProcessors();
Jens Geyerfb05cf62014-12-04 21:49:07 +0100358 connection_->close();
David Reiss01fe1532010-03-09 05:19:25 +0000359 throw TException("TNonblockingServer::Task::run: failed write on notify pipe");
Mark Sleee02385b2007-06-09 01:21:16 +0000360 }
David Reiss01fe1532010-03-09 05:19:25 +0000361 }
362
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100363 TConnection* getTConnection() { return connection_; }
Mark Sleee02385b2007-06-09 01:21:16 +0000364
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100365private:
cyy316723a2019-01-05 16:35:14 +0800366 std::shared_ptr<TProcessor> processor_;
367 std::shared_ptr<TProtocol> input_;
368 std::shared_ptr<TProtocol> output_;
David Reiss01fe1532010-03-09 05:19:25 +0000369 TConnection* connection_;
cyy316723a2019-01-05 16:35:14 +0800370 std::shared_ptr<TServerEventHandler> serverEventHandler_;
David Reiss105961d2010-10-06 17:10:17 +0000371 void* connectionContext_;
Mark Sleee02385b2007-06-09 01:21:16 +0000372};
Mark Slee5ea15f92007-03-05 22:55:59 +0000373
Divya Thaluru808d1432017-08-06 16:36:36 -0700374void TNonblockingServer::TConnection::init(TNonblockingIOThread* ioThread) {
Jake Farrellb0d95602011-12-06 01:17:26 +0000375 ioThread_ = ioThread;
376 server_ = ioThread->getServer();
Mark Slee2f6404d2006-10-10 01:37:40 +0000377 appState_ = APP_INIT;
378 eventFlags_ = 0;
379
380 readBufferPos_ = 0;
381 readWant_ = 0;
382
Sebastian Zenker042580f2019-01-29 15:48:12 +0100383 writeBuffer_ = nullptr;
Mark Slee2f6404d2006-10-10 01:37:40 +0000384 writeBufferSize_ = 0;
385 writeBufferPos_ = 0;
David Reiss54bec5d2010-10-06 17:10:45 +0000386 largestWriteBufferSize_ = 0;
Mark Slee2f6404d2006-10-10 01:37:40 +0000387
David Reiss89a12942010-10-06 17:10:52 +0000388 socketState_ = SOCKET_RECV_FRAMING;
David Reiss54bec5d2010-10-06 17:10:45 +0000389 callsForResize_ = 0;
Mark Slee79b16942007-11-26 19:05:29 +0000390
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000391 // get input/transports
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100392 factoryInputTransport_ = server_->getInputTransportFactory()->getTransport(inputTransport_);
393 factoryOutputTransport_ = server_->getOutputTransportFactory()->getTransport(outputTransport_);
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000394
395 // Create protocol
Dave Watson792db4e2015-01-16 11:22:01 -0800396 if (server_->getHeaderTransport()) {
397 inputProtocol_ = server_->getInputProtocolFactory()->getProtocol(factoryInputTransport_,
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +0100398 factoryOutputTransport_);
Dave Watson792db4e2015-01-16 11:22:01 -0800399 outputProtocol_ = inputProtocol_;
400 } else {
401 inputProtocol_ = server_->getInputProtocolFactory()->getProtocol(factoryInputTransport_);
402 outputProtocol_ = server_->getOutputProtocolFactory()->getProtocol(factoryOutputTransport_);
403 }
David Reiss105961d2010-10-06 17:10:17 +0000404
405 // Set up for any server event handler
406 serverEventHandler_ = server_->getEventHandler();
Roger Meier72957452013-06-29 00:28:50 +0200407 if (serverEventHandler_) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100408 connectionContext_ = serverEventHandler_->createContext(inputProtocol_, outputProtocol_);
David Reiss105961d2010-10-06 17:10:17 +0000409 } else {
Sebastian Zenker042580f2019-01-29 15:48:12 +0100410 connectionContext_ = nullptr;
David Reiss105961d2010-10-06 17:10:17 +0000411 }
Bryan Duxbury6dd9cd02011-09-01 18:06:20 +0000412
413 // Get the processor
Jake Farrellb0d95602011-12-06 01:17:26 +0000414 processor_ = server_->getProcessor(inputProtocol_, outputProtocol_, tSocket_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000415}
416
cyy316723a2019-01-05 16:35:14 +0800417void TNonblockingServer::TConnection::setSocket(std::shared_ptr<TSocket> socket) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700418 tSocket_ = socket;
419}
420
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000421void TNonblockingServer::TConnection::workSocket() {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100422 int got = 0, left = 0, sent = 0;
Mark Sleeaaa23ed2007-01-30 19:52:05 +0000423 uint32_t fetch = 0;
Mark Slee2f6404d2006-10-10 01:37:40 +0000424
425 switch (socketState_) {
David Reiss89a12942010-10-06 17:10:52 +0000426 case SOCKET_RECV_FRAMING:
427 union {
428 uint8_t buf[sizeof(uint32_t)];
Roger Meier3781c242011-12-11 20:07:21 +0000429 uint32_t size;
David Reiss89a12942010-10-06 17:10:52 +0000430 } framing;
Mark Slee2f6404d2006-10-10 01:37:40 +0000431
David Reiss89a12942010-10-06 17:10:52 +0000432 // if we've already received some bytes we kept them here
433 framing.size = readWant_;
434 // determine size of this frame
435 try {
436 // Read from the socket
437 fetch = tSocket_->read(&framing.buf[readBufferPos_],
438 uint32_t(sizeof(framing.size) - readBufferPos_));
439 if (fetch == 0) {
440 // Whenever we get here it means a remote disconnect
Mark Slee2f6404d2006-10-10 01:37:40 +0000441 close();
442 return;
443 }
David Reiss89a12942010-10-06 17:10:52 +0000444 readBufferPos_ += fetch;
445 } catch (TTransportException& te) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700446 //In Nonblocking SSLSocket some operations need to be retried again.
447 //Current approach is parsing exception message, but a better solution needs to be investigated.
448 if(!strstr(te.what(), "retry")) {
449 GlobalOutput.printf("TConnection::workSocket(): %s", te.what());
450 close();
David Reiss89a12942010-10-06 17:10:52 +0000451
Divya Thaluru808d1432017-08-06 16:36:36 -0700452 return;
453 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000454 }
455
David Reiss89a12942010-10-06 17:10:52 +0000456 if (readBufferPos_ < sizeof(framing.size)) {
457 // more needed before frame size is known -- save what we have so far
458 readWant_ = framing.size;
459 return;
460 }
461
462 readWant_ = ntohl(framing.size);
Roger Meier3781c242011-12-11 20:07:21 +0000463 if (readWant_ > server_->getMaxFrameSize()) {
464 // Don't allow giant frame sizes. This prevents bad clients from
465 // causing us to try and allocate a giant buffer.
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100466 GlobalOutput.printf(
467 "TNonblockingServer: frame size too large "
468 "(%" PRIu32 " > %" PRIu64
469 ") from client %s. "
470 "Remote side not using TFramedTransport?",
471 readWant_,
472 (uint64_t)server_->getMaxFrameSize(),
473 tSocket_->getSocketInfo().c_str());
David Reiss89a12942010-10-06 17:10:52 +0000474 close();
475 return;
476 }
477 // size known; now get the rest of the frame
478 transition();
Bugra Gedik8bcb7ac2018-01-21 09:43:49 -0800479
480 // If the socket has more data than the frame header, continue to work on it. This is not strictly necessary for
481 // regular sockets, because if there is more data, libevent will fire the event handler registered for read
482 // readiness, which will in turn call workSocket(). However, some socket types (such as TSSLSocket) may have the
483 // data sitting in their internal buffers and from libevent's perspective, there is no further data available. In
484 // that case, not having this workSocket() call here would result in a hang as we will never get to work the socket,
485 // despite having more data.
486 if (tSocket_->hasPendingDataToRead())
487 {
488 workSocket();
489 }
490
David Reiss89a12942010-10-06 17:10:52 +0000491 return;
492
493 case SOCKET_RECV:
494 // It is an error to be in this state if we already have all the data
Jens Geyer225646b2019-11-19 21:43:45 +0100495 if (!(readBufferPos_ < readWant_)) {
496 GlobalOutput.printf("TNonblockingServer: frame size too short");
497 close();
498 return;
499 }
David Reiss89a12942010-10-06 17:10:52 +0000500
David Reiss105961d2010-10-06 17:10:17 +0000501 try {
502 // Read from the socket
503 fetch = readWant_ - readBufferPos_;
504 got = tSocket_->read(readBuffer_ + readBufferPos_, fetch);
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100505 } catch (TTransportException& te) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700506 //In Nonblocking SSLSocket some operations need to be retried again.
507 //Current approach is parsing exception message, but a better solution needs to be investigated.
508 if(!strstr(te.what(), "retry")) {
509 GlobalOutput.printf("TConnection::workSocket(): %s", te.what());
510 close();
511 }
Mark Slee79b16942007-11-26 19:05:29 +0000512
David Reiss105961d2010-10-06 17:10:17 +0000513 return;
514 }
Jake Farrellb0d95602011-12-06 01:17:26 +0000515
Mark Slee2f6404d2006-10-10 01:37:40 +0000516 if (got > 0) {
517 // Move along in the buffer
518 readBufferPos_ += got;
519
520 // Check that we did not overdo it
521 assert(readBufferPos_ <= readWant_);
Mark Slee79b16942007-11-26 19:05:29 +0000522
Mark Slee2f6404d2006-10-10 01:37:40 +0000523 // We are done reading, move onto the next state
524 if (readBufferPos_ == readWant_) {
525 transition();
526 }
527 return;
Mark Slee2f6404d2006-10-10 01:37:40 +0000528 }
529
530 // Whenever we get down here it means a remote disconnect
531 close();
Mark Slee79b16942007-11-26 19:05:29 +0000532
Mark Slee2f6404d2006-10-10 01:37:40 +0000533 return;
534
535 case SOCKET_SEND:
536 // Should never have position past size
537 assert(writeBufferPos_ <= writeBufferSize_);
538
539 // If there is no data to send, then let us move on
540 if (writeBufferPos_ == writeBufferSize_) {
Buğra Gedik36d1b0d2016-09-04 17:18:15 +0900541 GlobalOutput("WARNING: Send state with no data to send");
Mark Slee2f6404d2006-10-10 01:37:40 +0000542 transition();
543 return;
544 }
545
David Reiss105961d2010-10-06 17:10:17 +0000546 try {
547 left = writeBufferSize_ - writeBufferPos_;
548 sent = tSocket_->write_partial(writeBuffer_ + writeBufferPos_, left);
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100549 } catch (TTransportException& te) {
David Reiss105961d2010-10-06 17:10:17 +0000550 GlobalOutput.printf("TConnection::workSocket(): %s ", te.what());
Mark Slee2f6404d2006-10-10 01:37:40 +0000551 close();
552 return;
553 }
554
555 writeBufferPos_ += sent;
556
557 // Did we overdo it?
558 assert(writeBufferPos_ <= writeBufferSize_);
559
Mark Slee79b16942007-11-26 19:05:29 +0000560 // We are done!
Mark Slee2f6404d2006-10-10 01:37:40 +0000561 if (writeBufferPos_ == writeBufferSize_) {
562 transition();
563 }
564
565 return;
566
567 default:
David Reiss3bb5e052010-01-25 19:31:31 +0000568 GlobalOutput.printf("Unexpected Socket State %d", socketState_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000569 assert(0);
570 }
571}
572
Dave Watson792db4e2015-01-16 11:22:01 -0800573bool TNonblockingServer::getHeaderTransport() {
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +0100574 // Currently if there is no output protocol factory,
Dave Watson792db4e2015-01-16 11:22:01 -0800575 // we assume header transport (without having to create
576 // a new transport and check)
Sebastian Zenker042580f2019-01-29 15:48:12 +0100577 return getOutputProtocolFactory() == nullptr;
Dave Watson792db4e2015-01-16 11:22:01 -0800578}
579
Mark Slee2f6404d2006-10-10 01:37:40 +0000580/**
581 * This is called when the application transitions from one state into
582 * another. This means that it has finished writing the data that it needed
583 * to, or finished receiving the data that it needed to.
584 */
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000585void TNonblockingServer::TConnection::transition() {
Jake Farrellb0d95602011-12-06 01:17:26 +0000586 // ensure this connection is active right now
587 assert(ioThread_);
588 assert(server_);
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000589
Mark Slee2f6404d2006-10-10 01:37:40 +0000590 // Switch upon the state that we are currently in and move to a new state
591 switch (appState_) {
592
593 case APP_READ_REQUEST:
594 // We are done reading the request, package the read buffer into transport
595 // and get back some data from the dispatch function
Dave Watson792db4e2015-01-16 11:22:01 -0800596 if (server_->getHeaderTransport()) {
597 inputTransport_->resetBuffer(readBuffer_, readBufferPos_);
598 outputTransport_->resetBuffer();
599 } else {
600 // We saved room for the framing size in case header transport needed it,
601 // but just skip it for the non-header case
602 inputTransport_->resetBuffer(readBuffer_ + 4, readBufferPos_ - 4);
603 outputTransport_->resetBuffer();
604
605 // Prepend four bytes of blank space to the buffer so we can
606 // write the frame size there later.
607 outputTransport_->getWritePtr(4);
608 outputTransport_->wroteBytes(4);
609 }
Mark Slee79b16942007-11-26 19:05:29 +0000610
David Reiss01fe1532010-03-09 05:19:25 +0000611 server_->incrementActiveProcessors();
612
Mark Sleee02385b2007-06-09 01:21:16 +0000613 if (server_->isThreadPoolProcessing()) {
614 // We are setting up a Task to do this work and we will wait on it
Mark Slee79b16942007-11-26 19:05:29 +0000615
David Reiss01fe1532010-03-09 05:19:25 +0000616 // Create task and dispatch to the thread manager
cyy316723a2019-01-05 16:35:14 +0800617 std::shared_ptr<Runnable> task = std::shared_ptr<Runnable>(
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100618 new Task(processor_, inputProtocol_, outputProtocol_, this));
David Reiss01fe1532010-03-09 05:19:25 +0000619 // The application is now waiting on the task to finish
620 appState_ = APP_WAIT_TASK;
Mark Slee2f6404d2006-10-10 01:37:40 +0000621
Changli Gaod4fa7062017-03-10 13:25:43 +0800622 // Set this connection idle so that libevent doesn't process more
623 // data on it while we're still waiting for the threadmanager to
624 // finish this task
625 setIdle();
626
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100627 try {
628 server_->addTask(task);
629 } catch (IllegalStateException& ise) {
630 // The ThreadManager is not ready to handle any more tasks (it's probably shutting down).
631 GlobalOutput.printf("IllegalStateException: Server::process() %s", ise.what());
Changli Gaod4fa7062017-03-10 13:25:43 +0800632 server_->decrementActiveProcessors();
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100633 close();
Jens Geyerfb05cf62014-12-04 21:49:07 +0100634 } catch (TimedOutException& to) {
635 GlobalOutput.printf("[ERROR] TimedOutException: Server::process() %s", to.what());
Changli Gaod4fa7062017-03-10 13:25:43 +0800636 server_->decrementActiveProcessors();
Jens Geyerfb05cf62014-12-04 21:49:07 +0100637 close();
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100638 }
Mark Slee402ee282007-08-23 01:43:20 +0000639
David Reiss01fe1532010-03-09 05:19:25 +0000640 return;
Mark Sleee02385b2007-06-09 01:21:16 +0000641 } else {
642 try {
Roger Meier72957452013-06-29 00:28:50 +0200643 if (serverEventHandler_) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100644 serverEventHandler_->processContext(connectionContext_, getTSocket());
Roger Meier72957452013-06-29 00:28:50 +0200645 }
Mark Sleee02385b2007-06-09 01:21:16 +0000646 // Invoke the processor
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100647 processor_->process(inputProtocol_, outputProtocol_, connectionContext_);
648 } catch (const TTransportException& ttx) {
649 GlobalOutput.printf(
650 "TNonblockingServer transport error in "
651 "process(): %s",
652 ttx.what());
David Reiss01fe1532010-03-09 05:19:25 +0000653 server_->decrementActiveProcessors();
Mark Sleee02385b2007-06-09 01:21:16 +0000654 close();
655 return;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100656 } catch (const std::exception& x) {
Bryan Duxbury1e987582011-08-25 17:33:03 +0000657 GlobalOutput.printf("Server::process() uncaught exception: %s: %s",
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100658 typeid(x).name(),
659 x.what());
David Reiss01fe1532010-03-09 05:19:25 +0000660 server_->decrementActiveProcessors();
Mark Slee79b16942007-11-26 19:05:29 +0000661 close();
Mark Sleee02385b2007-06-09 01:21:16 +0000662 return;
663 } catch (...) {
David Reiss01e55c12008-07-13 22:18:51 +0000664 GlobalOutput.printf("Server::process() unknown exception");
David Reiss01fe1532010-03-09 05:19:25 +0000665 server_->decrementActiveProcessors();
Mark Sleee02385b2007-06-09 01:21:16 +0000666 close();
667 return;
668 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000669 }
James E. King III9bea32f2018-03-16 16:07:42 -0400670 // fallthrough
Mark Slee2f6404d2006-10-10 01:37:40 +0000671
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100672 // Intentionally fall through here, the call to process has written into
673 // the writeBuffer_
Mark Slee402ee282007-08-23 01:43:20 +0000674
Mark Sleee02385b2007-06-09 01:21:16 +0000675 case APP_WAIT_TASK:
676 // We have now finished processing a task and the result has been written
677 // into the outputTransport_, so we grab its contents and place them into
678 // the writeBuffer_ for actual writing by the libevent thread
679
David Reiss01fe1532010-03-09 05:19:25 +0000680 server_->decrementActiveProcessors();
Mark Slee2f6404d2006-10-10 01:37:40 +0000681 // Get the result of the operation
682 outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_);
683
684 // If the function call generated return data, then move into the send
685 // state and get going
David Reissaf787782008-07-03 20:29:34 +0000686 // 4 bytes were reserved for frame size
David Reiss52cb7a72008-06-30 21:40:35 +0000687 if (writeBufferSize_ > 4) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000688
689 // Move into write state
690 writeBufferPos_ = 0;
691 socketState_ = SOCKET_SEND;
Mark Slee92f00fb2006-10-25 01:28:17 +0000692
David Reissaf787782008-07-03 20:29:34 +0000693 // Put the frame size into the write buffer
Sebastian Zenker042580f2019-01-29 15:48:12 +0100694 auto frameSize = (int32_t)htonl(writeBufferSize_ - 4);
David Reissaf787782008-07-03 20:29:34 +0000695 memcpy(writeBuffer_, &frameSize, 4);
Mark Slee2f6404d2006-10-10 01:37:40 +0000696
697 // Socket into write mode
David Reiss52cb7a72008-06-30 21:40:35 +0000698 appState_ = APP_SEND_RESULT;
Mark Slee2f6404d2006-10-10 01:37:40 +0000699 setWrite();
700
Mark Slee2f6404d2006-10-10 01:37:40 +0000701 return;
702 }
703
David Reissc51986f2009-03-24 20:01:25 +0000704 // In this case, the request was oneway and we should fall through
Mark Slee2f6404d2006-10-10 01:37:40 +0000705 // right back into the read frame header state
Mark Slee92f00fb2006-10-25 01:28:17 +0000706 goto LABEL_APP_INIT;
707
Mark Slee2f6404d2006-10-10 01:37:40 +0000708 case APP_SEND_RESULT:
David Reiss54bec5d2010-10-06 17:10:45 +0000709 // it's now safe to perform buffer size housekeeping.
710 if (writeBufferSize_ > largestWriteBufferSize_) {
711 largestWriteBufferSize_ = writeBufferSize_;
712 }
713 if (server_->getResizeBufferEveryN() > 0
714 && ++callsForResize_ >= server_->getResizeBufferEveryN()) {
715 checkIdleBufferMemLimit(server_->getIdleReadBufferLimit(),
716 server_->getIdleWriteBufferLimit());
717 callsForResize_ = 0;
718 }
James E. King III9bea32f2018-03-16 16:07:42 -0400719 // fallthrough
Mark Slee2f6404d2006-10-10 01:37:40 +0000720
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100721 // N.B.: We also intentionally fall through here into the INIT state!
Mark Slee2f6404d2006-10-10 01:37:40 +0000722
Mark Slee92f00fb2006-10-25 01:28:17 +0000723 LABEL_APP_INIT:
Mark Slee2f6404d2006-10-10 01:37:40 +0000724 case APP_INIT:
725
726 // Clear write buffer variables
Sebastian Zenker042580f2019-01-29 15:48:12 +0100727 writeBuffer_ = nullptr;
Mark Slee2f6404d2006-10-10 01:37:40 +0000728 writeBufferPos_ = 0;
729 writeBufferSize_ = 0;
730
Mark Slee2f6404d2006-10-10 01:37:40 +0000731 // Into read4 state we go
David Reiss89a12942010-10-06 17:10:52 +0000732 socketState_ = SOCKET_RECV_FRAMING;
Mark Slee2f6404d2006-10-10 01:37:40 +0000733 appState_ = APP_READ_FRAME_SIZE;
734
David Reiss89a12942010-10-06 17:10:52 +0000735 readBufferPos_ = 0;
736
Mark Slee2f6404d2006-10-10 01:37:40 +0000737 // Register read event
738 setRead();
David Reiss84e63ab2008-03-07 20:12:28 +0000739
Mark Slee2f6404d2006-10-10 01:37:40 +0000740 return;
741
742 case APP_READ_FRAME_SIZE:
Dave Watson792db4e2015-01-16 11:22:01 -0800743 readWant_ += 4;
744
David Reiss89a12942010-10-06 17:10:52 +0000745 // We just read the request length
746 // Double the buffer size until it is big enough
747 if (readWant_ > readBufferSize_) {
748 if (readBufferSize_ == 0) {
749 readBufferSize_ = 1;
750 }
751 uint32_t newSize = readBufferSize_;
752 while (readWant_ > newSize) {
753 newSize *= 2;
754 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000755
Sebastian Zenker042580f2019-01-29 15:48:12 +0100756 auto* newBuffer = (uint8_t*)std::realloc(readBuffer_, newSize);
757 if (newBuffer == nullptr) {
David Reiss89a12942010-10-06 17:10:52 +0000758 // nothing else to be done...
759 throw std::bad_alloc();
760 }
761 readBuffer_ = newBuffer;
762 readBufferSize_ = newSize;
Mark Slee2f6404d2006-10-10 01:37:40 +0000763 }
764
Dave Watson792db4e2015-01-16 11:22:01 -0800765 readBufferPos_ = 4;
766 *((uint32_t*)readBuffer_) = htonl(readWant_ - 4);
Mark Slee2f6404d2006-10-10 01:37:40 +0000767
768 // Move into read request state
David Reiss89a12942010-10-06 17:10:52 +0000769 socketState_ = SOCKET_RECV;
Mark Slee2f6404d2006-10-10 01:37:40 +0000770 appState_ = APP_READ_REQUEST;
771
Mark Slee2f6404d2006-10-10 01:37:40 +0000772 return;
773
David Reiss01fe1532010-03-09 05:19:25 +0000774 case APP_CLOSE_CONNECTION:
775 server_->decrementActiveProcessors();
776 close();
777 return;
778
Mark Slee2f6404d2006-10-10 01:37:40 +0000779 default:
David Reiss3bb5e052010-01-25 19:31:31 +0000780 GlobalOutput.printf("Unexpected Application State %d", appState_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000781 assert(0);
782 }
783}
784
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000785void TNonblockingServer::TConnection::setFlags(short eventFlags) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000786 // Catch the do nothing case
787 if (eventFlags_ == eventFlags) {
788 return;
789 }
790
791 // Delete a previously existing event
Buğra Gedik36d1b0d2016-09-04 17:18:15 +0900792 if (eventFlags_ && event_del(&event_) == -1) {
793 GlobalOutput.perror("TConnection::setFlags() event_del", THRIFT_GET_SOCKET_ERROR);
794 return;
Mark Slee2f6404d2006-10-10 01:37:40 +0000795 }
796
797 // Update in memory structure
798 eventFlags_ = eventFlags;
799
Mark Slee402ee282007-08-23 01:43:20 +0000800 // Do not call event_set if there are no flags
801 if (!eventFlags_) {
802 return;
803 }
804
David Reiss01fe1532010-03-09 05:19:25 +0000805 /*
Mark Slee2f6404d2006-10-10 01:37:40 +0000806 * event_set:
807 *
808 * Prepares the event structure &event to be used in future calls to
809 * event_add() and event_del(). The event will be prepared to call the
Mark Sleee02385b2007-06-09 01:21:16 +0000810 * eventHandler using the 'sock' file descriptor to monitor events.
Mark Slee2f6404d2006-10-10 01:37:40 +0000811 *
812 * The events can be either EV_READ, EV_WRITE, or both, indicating
813 * that an application can read or write from the file respectively without
814 * blocking.
815 *
Mark Sleee02385b2007-06-09 01:21:16 +0000816 * The eventHandler will be called with the file descriptor that triggered
Mark Slee2f6404d2006-10-10 01:37:40 +0000817 * the event and the type of event which will be one of: EV_TIMEOUT,
818 * EV_SIGNAL, EV_READ, EV_WRITE.
819 *
820 * The additional flag EV_PERSIST makes an event_add() persistent until
821 * event_del() has been called.
822 *
823 * Once initialized, the &event struct can be used repeatedly with
824 * event_add() and event_del() and does not need to be reinitialized unless
Mark Sleee02385b2007-06-09 01:21:16 +0000825 * the eventHandler and/or the argument to it are to be changed. However,
Mark Slee2f6404d2006-10-10 01:37:40 +0000826 * when an ev structure has been added to libevent using event_add() the
827 * structure must persist until the event occurs (assuming EV_PERSIST
828 * is not set) or is removed using event_del(). You may not reuse the same
829 * ev structure for multiple monitored descriptors; each descriptor needs
830 * its own ev.
831 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100832 event_set(&event_, tSocket_->getSocketFD(), eventFlags_, TConnection::eventHandler, this);
Jake Farrellb0d95602011-12-06 01:17:26 +0000833 event_base_set(ioThread_->getEventBase(), &event_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000834
835 // Add the event
Sebastian Zenker042580f2019-01-29 15:48:12 +0100836 if (event_add(&event_, nullptr) == -1) {
Buğra Gedik36d1b0d2016-09-04 17:18:15 +0900837 GlobalOutput.perror("TConnection::setFlags(): could not event_add", THRIFT_GET_SOCKET_ERROR);
Mark Slee2f6404d2006-10-10 01:37:40 +0000838 }
839}
840
841/**
842 * Closes a connection
843 */
Bryan Duxbury526fa8e2011-08-29 20:28:23 +0000844void TNonblockingServer::TConnection::close() {
Changli Gaobf42d552017-03-20 14:29:07 +0800845 setIdle();
David Reiss105961d2010-10-06 17:10:17 +0000846
Roger Meier72957452013-06-29 00:28:50 +0200847 if (serverEventHandler_) {
David Reiss105961d2010-10-06 17:10:17 +0000848 serverEventHandler_->deleteContext(connectionContext_, inputProtocol_, outputProtocol_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000849 }
Sebastian Zenker042580f2019-01-29 15:48:12 +0100850 ioThread_ = nullptr;
Mark Slee2f6404d2006-10-10 01:37:40 +0000851
852 // Close the socket
David Reiss105961d2010-10-06 17:10:17 +0000853 tSocket_->close();
Mark Slee2f6404d2006-10-10 01:37:40 +0000854
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000855 // close any factory produced transports
856 factoryInputTransport_->close();
Aditya Agarwal9abb0d62007-01-24 22:53:54 +0000857 factoryOutputTransport_->close();
Aditya Agarwal1ea90522007-01-19 02:02:12 +0000858
Roger Meier464a3a42014-07-07 21:48:28 +0200859 // release processor and handler
860 processor_.reset();
861
Mark Slee2f6404d2006-10-10 01:37:40 +0000862 // Give this object back to the server that owns it
863 server_->returnConnection(this);
864}
865
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100866void TNonblockingServer::TConnection::checkIdleBufferMemLimit(size_t readLimit, size_t writeLimit) {
David Reiss54bec5d2010-10-06 17:10:45 +0000867 if (readLimit > 0 && readBufferSize_ > readLimit) {
David Reiss89a12942010-10-06 17:10:52 +0000868 free(readBuffer_);
Sebastian Zenker042580f2019-01-29 15:48:12 +0100869 readBuffer_ = nullptr;
David Reiss89a12942010-10-06 17:10:52 +0000870 readBufferSize_ = 0;
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000871 }
David Reiss54bec5d2010-10-06 17:10:45 +0000872
873 if (writeLimit > 0 && largestWriteBufferSize_ > writeLimit) {
874 // just start over
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -0400875 outputTransport_->resetBuffer(static_cast<uint32_t>(server_->getWriteBufferDefaultSize()));
David Reiss54bec5d2010-10-06 17:10:45 +0000876 largestWriteBufferSize_ = 0;
877 }
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000878}
879
David Reiss8ede8182010-09-02 15:26:28 +0000880TNonblockingServer::~TNonblockingServer() {
Roger Meier0c04fcc2013-03-22 19:52:08 +0100881 // Close any active connections (moves them to the idle connection stack)
882 while (activeConnections_.size()) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100883 activeConnections_.front()->close();
Roger Meier0c04fcc2013-03-22 19:52:08 +0100884 }
David Reiss8ede8182010-09-02 15:26:28 +0000885 // Clean up unused TConnection objects in connectionStack_
886 while (!connectionStack_.empty()) {
887 TConnection* connection = connectionStack_.top();
888 connectionStack_.pop();
889 delete connection;
890 }
Roger Meier0c04fcc2013-03-22 19:52:08 +0100891 // The TNonblockingIOThread objects have shared_ptrs to the Thread
892 // objects and the Thread objects have shared_ptrs to the TNonblockingIOThread
893 // objects (as runnable) so these objects will never deallocate without help.
894 while (!ioThreads_.empty()) {
cyy316723a2019-01-05 16:35:14 +0800895 std::shared_ptr<TNonblockingIOThread> iot = ioThreads_.back();
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100896 ioThreads_.pop_back();
cyy316723a2019-01-05 16:35:14 +0800897 iot->setThread(std::shared_ptr<Thread>());
Roger Meier0c04fcc2013-03-22 19:52:08 +0100898 }
David Reiss8ede8182010-09-02 15:26:28 +0000899}
900
Mark Slee2f6404d2006-10-10 01:37:40 +0000901/**
902 * Creates a new connection either by reusing an object off the stack or
903 * by allocating a new one entirely
904 */
cyy316723a2019-01-05 16:35:14 +0800905TNonblockingServer::TConnection* TNonblockingServer::createConnection(std::shared_ptr<TSocket> socket) {
Mark Slee2f6404d2006-10-10 01:37:40 +0000906 // Check the stack
Jake Farrellb0d95602011-12-06 01:17:26 +0000907 Guard g(connMutex_);
908
909 // pick an IO thread to handle this connection -- currently round robin
Jake Farrellb0d95602011-12-06 01:17:26 +0000910 assert(nextIOThread_ < ioThreads_.size());
911 int selectedThreadIdx = nextIOThread_;
Ben Craig64935232013-10-09 15:21:38 -0500912 nextIOThread_ = static_cast<uint32_t>((nextIOThread_ + 1) % ioThreads_.size());
Jake Farrellb0d95602011-12-06 01:17:26 +0000913
914 TNonblockingIOThread* ioThread = ioThreads_[selectedThreadIdx].get();
915
916 // Check the connection stack to see if we can re-use
Sebastian Zenker042580f2019-01-29 15:48:12 +0100917 TConnection* result = nullptr;
Mark Slee2f6404d2006-10-10 01:37:40 +0000918 if (connectionStack_.empty()) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700919 result = new TConnection(socket, ioThread);
Jake Farrellb0d95602011-12-06 01:17:26 +0000920 ++numTConnections_;
Mark Slee2f6404d2006-10-10 01:37:40 +0000921 } else {
Jake Farrellb0d95602011-12-06 01:17:26 +0000922 result = connectionStack_.top();
Mark Slee2f6404d2006-10-10 01:37:40 +0000923 connectionStack_.pop();
Divya Thaluru808d1432017-08-06 16:36:36 -0700924 result->setSocket(socket);
925 result->init(ioThread);
Mark Slee2f6404d2006-10-10 01:37:40 +0000926 }
Roger Meier0c04fcc2013-03-22 19:52:08 +0100927 activeConnections_.push_back(result);
Jake Farrellb0d95602011-12-06 01:17:26 +0000928 return result;
Mark Slee2f6404d2006-10-10 01:37:40 +0000929}
930
931/**
932 * Returns a connection to the stack
933 */
934void TNonblockingServer::returnConnection(TConnection* connection) {
Jake Farrellb0d95602011-12-06 01:17:26 +0000935 Guard g(connMutex_);
936
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100937 activeConnections_.erase(std::remove(activeConnections_.begin(),
938 activeConnections_.end(),
939 connection),
940 activeConnections_.end());
Roger Meier0c04fcc2013-03-22 19:52:08 +0100941
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100942 if (connectionStackLimit_ && (connectionStack_.size() >= connectionStackLimit_)) {
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000943 delete connection;
Jake Farrellb0d95602011-12-06 01:17:26 +0000944 --numTConnections_;
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000945 } else {
David Reiss54bec5d2010-10-06 17:10:45 +0000946 connection->checkIdleBufferMemLimit(idleReadBufferLimit_, idleWriteBufferLimit_);
Kevin Clarkcbcd63a2009-03-19 03:50:05 +0000947 connectionStack_.push(connection);
948 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000949}
950
951/**
David Reissa79e4882008-03-05 07:51:47 +0000952 * Server socket had something happen. We accept all waiting client
953 * connections on fd and assign TConnection objects to handle those requests.
Mark Slee2f6404d2006-10-10 01:37:40 +0000954 */
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -0400955void TNonblockingServer::handleEvent(THRIFT_SOCKET fd, short which) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100956 (void)which;
David Reiss3bb5e052010-01-25 19:31:31 +0000957 // Make sure that libevent didn't mess up the socket handles
Mark Slee2f6404d2006-10-10 01:37:40 +0000958 assert(fd == serverSocket_);
Mark Slee79b16942007-11-26 19:05:29 +0000959
Mark Slee2f6404d2006-10-10 01:37:40 +0000960 // Going to accept a new client socket
cyy316723a2019-01-05 16:35:14 +0800961 std::shared_ptr<TSocket> clientSocket;
Mark Slee79b16942007-11-26 19:05:29 +0000962
Divya Thaluru808d1432017-08-06 16:36:36 -0700963 clientSocket = serverTransport_->accept();
964 if (clientSocket) {
David Reiss01fe1532010-03-09 05:19:25 +0000965 // If we're overloaded, take action here
966 if (overloadAction_ != T_OVERLOAD_NO_ACTION && serverOverloaded()) {
Jake Farrellb0d95602011-12-06 01:17:26 +0000967 Guard g(connMutex_);
David Reiss01fe1532010-03-09 05:19:25 +0000968 nConnectionsDropped_++;
969 nTotalConnectionsDropped_++;
970 if (overloadAction_ == T_OVERLOAD_CLOSE_ON_ACCEPT) {
Divya Thaluru808d1432017-08-06 16:36:36 -0700971 clientSocket->close();
David Reiss83b8fda2010-03-09 05:19:34 +0000972 return;
David Reiss01fe1532010-03-09 05:19:25 +0000973 } else if (overloadAction_ == T_OVERLOAD_DRAIN_TASK_QUEUE) {
974 if (!drainPendingTask()) {
975 // Nothing left to discard, so we drop connection instead.
Divya Thaluru808d1432017-08-06 16:36:36 -0700976 clientSocket->close();
David Reiss83b8fda2010-03-09 05:19:34 +0000977 return;
David Reiss01fe1532010-03-09 05:19:25 +0000978 }
979 }
980 }
Jake Farrellb0d95602011-12-06 01:17:26 +0000981
Mark Slee2f6404d2006-10-10 01:37:40 +0000982 // Create a new TConnection for this client socket.
Divya Thaluru808d1432017-08-06 16:36:36 -0700983 TConnection* clientConnection = createConnection(clientSocket);
Mark Slee2f6404d2006-10-10 01:37:40 +0000984
985 // Fail fast if we could not create a TConnection object
Sebastian Zenker042580f2019-01-29 15:48:12 +0100986 if (clientConnection == nullptr) {
David Reiss01e55c12008-07-13 22:18:51 +0000987 GlobalOutput.printf("thriftServerEventHandler: failed TConnection factory");
Divya Thaluru808d1432017-08-06 16:36:36 -0700988 clientSocket->close();
Mark Slee2f6404d2006-10-10 01:37:40 +0000989 return;
990 }
991
Jake Farrellb0d95602011-12-06 01:17:26 +0000992 /*
993 * Either notify the ioThread that is assigned this connection to
994 * start processing, or if it is us, we'll just ask this
995 * connection to do its initial state change here.
996 *
997 * (We need to avoid writing to our own notification pipe, to
998 * avoid possible deadlocks if the pipe is full.)
999 *
1000 * The IO thread #0 is the only one that handles these listen
1001 * events, so unless the connection has been assigned to thread #0
1002 * we know it's not on our thread.
1003 */
1004 if (clientConnection->getIOThreadNumber() == 0) {
1005 clientConnection->transition();
1006 } else {
Jens Geyerfb05cf62014-12-04 21:49:07 +01001007 if (!clientConnection->notifyIOThread()) {
1008 GlobalOutput.perror("[ERROR] notifyIOThread failed on fresh connection, closing", errno);
Changli Gao75386db2017-03-10 13:15:37 +08001009 clientConnection->close();
Jens Geyerfb05cf62014-12-04 21:49:07 +01001010 }
Jake Farrellb0d95602011-12-06 01:17:26 +00001011 }
Mark Slee2f6404d2006-10-10 01:37:40 +00001012 }
1013}
1014
1015/**
Mark Slee79b16942007-11-26 19:05:29 +00001016 * Creates a socket to listen on and binds it to the local port.
Mark Slee2f6404d2006-10-10 01:37:40 +00001017 */
Jake Farrellb0d95602011-12-06 01:17:26 +00001018void TNonblockingServer::createAndListenOnSocket() {
Divya Thaluru808d1432017-08-06 16:36:36 -07001019 serverTransport_->listen();
1020 serverSocket_ = serverTransport_->getSocketFD();
Mark Slee79b16942007-11-26 19:05:29 +00001021}
1022
Mark Slee79b16942007-11-26 19:05:29 +00001023
cyy316723a2019-01-05 16:35:14 +08001024void TNonblockingServer::setThreadManager(std::shared_ptr<ThreadManager> threadManager) {
David Reiss068f4162010-03-09 05:19:45 +00001025 threadManager_ = threadManager;
Roger Meier72957452013-06-29 00:28:50 +02001026 if (threadManager) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001027 threadManager->setExpireCallback(
cyy316723a2019-01-05 16:35:14 +08001028 std::bind(&TNonblockingServer::expireClose,
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001029 this,
cyy316723a2019-01-05 16:35:14 +08001030 std::placeholders::_1));
David Reiss068f4162010-03-09 05:19:45 +00001031 threadPoolProcessing_ = true;
1032 } else {
1033 threadPoolProcessing_ = false;
1034 }
1035}
1036
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001037bool TNonblockingServer::serverOverloaded() {
David Reiss01fe1532010-03-09 05:19:25 +00001038 size_t activeConnections = numTConnections_ - connectionStack_.size();
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001039 if (numActiveProcessors_ > maxActiveProcessors_ || activeConnections > maxConnections_) {
David Reiss01fe1532010-03-09 05:19:25 +00001040 if (!overloaded_) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001041 GlobalOutput.printf("TNonblockingServer: overload condition begun.");
David Reiss01fe1532010-03-09 05:19:25 +00001042 overloaded_ = true;
1043 }
1044 } else {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001045 if (overloaded_ && (numActiveProcessors_ <= overloadHysteresis_ * maxActiveProcessors_)
1046 && (activeConnections <= overloadHysteresis_ * maxConnections_)) {
1047 GlobalOutput.printf(
1048 "TNonblockingServer: overload ended; "
1049 "%u dropped (%llu total)",
1050 nConnectionsDropped_,
1051 nTotalConnectionsDropped_);
David Reiss01fe1532010-03-09 05:19:25 +00001052 nConnectionsDropped_ = 0;
1053 overloaded_ = false;
1054 }
1055 }
1056
1057 return overloaded_;
1058}
1059
1060bool TNonblockingServer::drainPendingTask() {
1061 if (threadManager_) {
cyy316723a2019-01-05 16:35:14 +08001062 std::shared_ptr<Runnable> task = threadManager_->removeNextPending();
David Reiss01fe1532010-03-09 05:19:25 +00001063 if (task) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001064 TConnection* connection = static_cast<TConnection::Task*>(task.get())->getTConnection();
1065 assert(connection && connection->getServer() && connection->getState() == APP_WAIT_TASK);
David Reiss01fe1532010-03-09 05:19:25 +00001066 connection->forceClose();
1067 return true;
1068 }
1069 }
1070 return false;
Mark Slee79b16942007-11-26 19:05:29 +00001071}
1072
cyy316723a2019-01-05 16:35:14 +08001073void TNonblockingServer::expireClose(std::shared_ptr<Runnable> task) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001074 TConnection* connection = static_cast<TConnection::Task*>(task.get())->getTConnection();
1075 assert(connection && connection->getServer() && connection->getState() == APP_WAIT_TASK);
David Reiss068f4162010-03-09 05:19:45 +00001076 connection->forceClose();
1077}
1078
Bugra Gedik8bcb7ac2018-01-21 09:43:49 -08001079void TNonblockingServer::stop() {
Jake Farrellb0d95602011-12-06 01:17:26 +00001080 // Breaks the event loop in all threads so that they end ASAP.
cyy64750162019-02-08 13:40:59 +08001081 for (auto & ioThread : ioThreads_) {
1082 ioThread->stop();
Jake Farrellb0d95602011-12-06 01:17:26 +00001083 }
1084}
1085
Roger Meier6f2a5032013-07-08 23:35:25 +02001086void TNonblockingServer::registerEvents(event_base* user_event_base) {
1087 userEventBase_ = user_event_base;
1088
Jake Farrellb0d95602011-12-06 01:17:26 +00001089 // init listen socket
Roger Meiere802aa42013-07-19 21:10:54 +02001090 if (serverSocket_ == THRIFT_INVALID_SOCKET)
Roger Meier6f2a5032013-07-08 23:35:25 +02001091 createAndListenOnSocket();
Mark Slee79b16942007-11-26 19:05:29 +00001092
Jake Farrellb0d95602011-12-06 01:17:26 +00001093 // set up the IO threads
1094 assert(ioThreads_.empty());
1095 if (!numIOThreads_) {
1096 numIOThreads_ = DEFAULT_IO_THREADS;
David Reiss01fe1532010-03-09 05:19:25 +00001097 }
Nobuaki Sukegawa8016af82015-01-02 23:14:22 +09001098 // User-provided event-base doesn't works for multi-threaded servers
1099 assert(numIOThreads_ == 1 || !userEventBase_);
David Reiss01fe1532010-03-09 05:19:25 +00001100
Roger Meierd0cdecf2011-12-08 19:34:01 +00001101 for (uint32_t id = 0; id < numIOThreads_; ++id) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001102 // the first IO thread also does the listening on server socket
Roger Meier0be9ffa2013-07-19 21:10:01 +02001103 THRIFT_SOCKET listenFd = (id == 0 ? serverSocket_ : THRIFT_INVALID_SOCKET);
Mark Slee2f6404d2006-10-10 01:37:40 +00001104
Jake Farrellb0d95602011-12-06 01:17:26 +00001105 shared_ptr<TNonblockingIOThread> thread(
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001106 new TNonblockingIOThread(this, id, listenFd, useHighPriorityIOThreads_));
Jake Farrellb0d95602011-12-06 01:17:26 +00001107 ioThreads_.push_back(thread);
1108 }
1109
1110 // Notify handler of the preServe event
Roger Meier72957452013-06-29 00:28:50 +02001111 if (eventHandler_) {
Mark Sleeb4d3e7b2007-11-28 01:51:43 +00001112 eventHandler_->preServe();
dweatherford58985992007-06-19 23:10:19 +00001113 }
1114
Jake Farrellb0d95602011-12-06 01:17:26 +00001115 // Start all of our helper IO threads. Note that the threads run forever,
1116 // only terminating if stop() is called.
1117 assert(ioThreads_.size() == numIOThreads_);
1118 assert(ioThreads_.size() > 0);
1119
Divya Thaluru808d1432017-08-06 16:36:36 -07001120 GlobalOutput.printf("TNonblockingServer: Serving with %d io threads.",
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001121 ioThreads_.size());
Jake Farrellb0d95602011-12-06 01:17:26 +00001122
1123 // Launch all the secondary IO threads in separate threads
1124 if (ioThreads_.size() > 1) {
cyyca8af9b2019-01-11 22:13:12 +08001125 ioThreadFactory_.reset(new ThreadFactory(
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001126 false // detached
1127 ));
Jake Farrellb0d95602011-12-06 01:17:26 +00001128
1129 assert(ioThreadFactory_.get());
1130
1131 // intentionally starting at thread 1, not 0
Roger Meierd0cdecf2011-12-08 19:34:01 +00001132 for (uint32_t i = 1; i < ioThreads_.size(); ++i) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001133 shared_ptr<Thread> thread = ioThreadFactory_->newThread(ioThreads_[i]);
1134 ioThreads_[i]->setThread(thread);
1135 thread->start();
1136 }
1137 }
1138
Roger Meier6f2a5032013-07-08 23:35:25 +02001139 // Register the events for the primary (listener) IO thread
1140 ioThreads_[0]->registerEvents();
1141}
1142
1143/**
1144 * Main workhorse function, starts up the server listening on a port and
1145 * loops over the libevent handler.
1146 */
1147void TNonblockingServer::serve() {
1148
Konrad Grochowski1f6e3802015-05-18 18:10:06 +02001149 if (ioThreads_.empty())
Sebastian Zenker042580f2019-01-29 15:48:12 +01001150 registerEvents(nullptr);
Roger Meier6f2a5032013-07-08 23:35:25 +02001151
Jake Farrellb0d95602011-12-06 01:17:26 +00001152 // Run the primary (listener) IO thread loop in our main thread; this will
1153 // only return when the server is shutting down.
1154 ioThreads_[0]->run();
1155
1156 // Ensure all threads are finished before exiting serve()
Roger Meierd0cdecf2011-12-08 19:34:01 +00001157 for (uint32_t i = 0; i < ioThreads_.size(); ++i) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001158 ioThreads_[i]->join();
1159 GlobalOutput.printf("TNonblocking: join done for IO thread #%d", i);
1160 }
Mark Slee2f6404d2006-10-10 01:37:40 +00001161}
1162
Jake Farrellb0d95602011-12-06 01:17:26 +00001163TNonblockingIOThread::TNonblockingIOThread(TNonblockingServer* server,
1164 int number,
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -04001165 THRIFT_SOCKET listenSocket,
Jake Farrellb0d95602011-12-06 01:17:26 +00001166 bool useHighPriority)
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001167 : server_(server),
1168 number_(number),
cyy64750162019-02-08 13:40:59 +08001169 threadId_{},
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001170 listenSocket_(listenSocket),
1171 useHighPriority_(useHighPriority),
Sebastian Zenker042580f2019-01-29 15:48:12 +01001172 eventBase_(nullptr),
cyy64750162019-02-08 13:40:59 +08001173 ownEventBase_(false),
1174 serverEvent_{},
1175 notificationEvent_{} {
Jake Farrellb0d95602011-12-06 01:17:26 +00001176 notificationPipeFDs_[0] = -1;
1177 notificationPipeFDs_[1] = -1;
1178}
1179
1180TNonblockingIOThread::~TNonblockingIOThread() {
1181 // make sure our associated thread is fully finished
1182 join();
1183
Roger Meier6f2a5032013-07-08 23:35:25 +02001184 if (eventBase_ && ownEventBase_) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001185 event_base_free(eventBase_);
Roger Meier6f2a5032013-07-08 23:35:25 +02001186 ownEventBase_ = false;
Bryan Duxbury76c43682011-08-24 21:26:48 +00001187 }
1188
gzshi41945622017-01-06 10:47:03 +08001189 if (listenSocket_ != THRIFT_INVALID_SOCKET) {
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -04001190 if (0 != ::THRIFT_CLOSESOCKET(listenSocket_)) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001191 GlobalOutput.perror("TNonblockingIOThread listenSocket_ close(): ", THRIFT_GET_SOCKET_ERROR);
Jake Farrellb0d95602011-12-06 01:17:26 +00001192 }
Roger Meier0be9ffa2013-07-19 21:10:01 +02001193 listenSocket_ = THRIFT_INVALID_SOCKET;
Jake Farrellb0d95602011-12-06 01:17:26 +00001194 }
1195
cyy64750162019-02-08 13:40:59 +08001196 for (auto notificationPipeFD : notificationPipeFDs_) {
1197 if (notificationPipeFD >= 0) {
1198 if (0 != ::THRIFT_CLOSESOCKET(notificationPipeFD)) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001199 GlobalOutput.perror("TNonblockingIOThread notificationPipe close(): ",
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -04001200 THRIFT_GET_SOCKET_ERROR);
Jake Farrellb0d95602011-12-06 01:17:26 +00001201 }
cyy64750162019-02-08 13:40:59 +08001202 notificationPipeFD = THRIFT_INVALID_SOCKET;
Jake Farrellb0d95602011-12-06 01:17:26 +00001203 }
1204 }
1205}
1206
1207void TNonblockingIOThread::createNotificationPipe() {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001208 if (evutil_socketpair(AF_LOCAL, SOCK_STREAM, 0, notificationPipeFDs_) == -1) {
Roger Meier12d70532011-12-14 23:35:28 +00001209 GlobalOutput.perror("TNonblockingServer::createNotificationPipe ", EVUTIL_SOCKET_ERROR());
Jake Farrellb0d95602011-12-06 01:17:26 +00001210 throw TException("can't create notification pipe");
1211 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001212 if (evutil_make_socket_nonblocking(notificationPipeFDs_[0]) < 0
1213 || evutil_make_socket_nonblocking(notificationPipeFDs_[1]) < 0) {
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -04001214 ::THRIFT_CLOSESOCKET(notificationPipeFDs_[0]);
1215 ::THRIFT_CLOSESOCKET(notificationPipeFDs_[1]);
1216 throw TException("TNonblockingServer::createNotificationPipe() THRIFT_O_NONBLOCK");
Jake Farrellb0d95602011-12-06 01:17:26 +00001217 }
cyy64750162019-02-08 13:40:59 +08001218 for (auto notificationPipeFD : notificationPipeFDs_) {
Roger Meier12d70532011-12-14 23:35:28 +00001219#if LIBEVENT_VERSION_NUMBER < 0x02000000
1220 int flags;
cyy64750162019-02-08 13:40:59 +08001221 if ((flags = THRIFT_FCNTL(notificationPipeFD, F_GETFD, 0)) < 0
1222 || THRIFT_FCNTL(notificationPipeFD, F_SETFD, flags | FD_CLOEXEC) < 0) {
Roger Meier12d70532011-12-14 23:35:28 +00001223#else
cyy64750162019-02-08 13:40:59 +08001224 if (evutil_make_socket_closeonexec(notificationPipeFD) < 0) {
Roger Meier12d70532011-12-14 23:35:28 +00001225#endif
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -04001226 ::THRIFT_CLOSESOCKET(notificationPipeFDs_[0]);
1227 ::THRIFT_CLOSESOCKET(notificationPipeFDs_[1]);
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001228 throw TException(
1229 "TNonblockingServer::createNotificationPipe() "
1230 "FD_CLOEXEC");
Jake Farrellb0d95602011-12-06 01:17:26 +00001231 }
1232 }
1233}
1234
1235/**
1236 * Register the core libevent events onto the proper base.
1237 */
1238void TNonblockingIOThread::registerEvents() {
Roger Meier6f2a5032013-07-08 23:35:25 +02001239 threadId_ = Thread::get_current();
1240
Sebastian Zenker042580f2019-01-29 15:48:12 +01001241 assert(eventBase_ == nullptr);
Roger Meier6f2a5032013-07-08 23:35:25 +02001242 eventBase_ = getServer()->getUserEventBase();
Sebastian Zenker042580f2019-01-29 15:48:12 +01001243 if (eventBase_ == nullptr) {
Roger Meier6f2a5032013-07-08 23:35:25 +02001244 eventBase_ = event_base_new();
1245 ownEventBase_ = true;
1246 }
1247
1248 // Print some libevent stats
1249 if (number_ == 0) {
1250 GlobalOutput.printf("TNonblockingServer: using libevent %s method %s",
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001251 event_get_version(),
1252 event_base_get_method(eventBase_));
Roger Meier6f2a5032013-07-08 23:35:25 +02001253 }
1254
gzshi41945622017-01-06 10:47:03 +08001255 if (listenSocket_ != THRIFT_INVALID_SOCKET) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001256 // Register the server event
1257 event_set(&serverEvent_,
1258 listenSocket_,
1259 EV_READ | EV_PERSIST,
1260 TNonblockingIOThread::listenHandler,
1261 server_);
1262 event_base_set(eventBase_, &serverEvent_);
1263
1264 // Add the event and start up the server
Sebastian Zenker042580f2019-01-29 15:48:12 +01001265 if (-1 == event_add(&serverEvent_, nullptr)) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001266 throw TException(
1267 "TNonblockingServer::serve(): "
1268 "event_add() failed on server listen event");
Jake Farrellb0d95602011-12-06 01:17:26 +00001269 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001270 GlobalOutput.printf("TNonblocking: IO thread #%d registered for listen.", number_);
Jake Farrellb0d95602011-12-06 01:17:26 +00001271 }
1272
1273 createNotificationPipe();
1274
1275 // Create an event to be notified when a task finishes
1276 event_set(&notificationEvent_,
1277 getNotificationRecvFD(),
1278 EV_READ | EV_PERSIST,
1279 TNonblockingIOThread::notifyHandler,
1280 this);
1281
1282 // Attach to the base
1283 event_base_set(eventBase_, &notificationEvent_);
1284
1285 // Add the event and start up the server
Sebastian Zenker042580f2019-01-29 15:48:12 +01001286 if (-1 == event_add(&notificationEvent_, nullptr)) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001287 throw TException(
1288 "TNonblockingServer::serve(): "
1289 "event_add() failed on task-done notification event");
Jake Farrellb0d95602011-12-06 01:17:26 +00001290 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001291 GlobalOutput.printf("TNonblocking: IO thread #%d registered for notify.", number_);
Jake Farrellb0d95602011-12-06 01:17:26 +00001292}
1293
1294bool TNonblockingIOThread::notify(TNonblockingServer::TConnection* conn) {
cyy9fed9012019-01-16 14:43:51 +08001295 auto fd = getNotificationSendFD();
Jake Farrellb0d95602011-12-06 01:17:26 +00001296 if (fd < 0) {
1297 return false;
1298 }
1299
st0ke961fa702018-10-12 18:37:40 +07001300 int ret = -1;
tpcwangf98d59f2016-03-23 16:18:52 -07001301 long kSize = sizeof(conn);
st0ke961fa702018-10-12 18:37:40 +07001302 const char * pos = (const char *)const_cast_sockopt(&conn);
1303
1304#if defined(HAVE_POLL_H) || defined(HAVE_SYS_POLL_H)
1305 struct pollfd pfd = {fd, POLLOUT, 0};
1306
1307 while (kSize > 0) {
1308 pfd.revents = 0;
1309 ret = poll(&pfd, 1, -1);
1310 if (ret < 0) {
1311 return false;
1312 } else if (ret == 0) {
1313 continue;
1314 }
1315
1316 if (pfd.revents & POLLHUP || pfd.revents & POLLERR) {
1317 ::THRIFT_CLOSESOCKET(fd);
1318 return false;
1319 }
1320
1321 if (pfd.revents & POLLOUT) {
1322 ret = send(fd, pos, kSize, 0);
1323 if (ret < 0) {
1324 if (errno == EAGAIN) {
1325 continue;
1326 }
1327
1328 ::THRIFT_CLOSESOCKET(fd);
1329 return false;
1330 }
1331
1332 kSize -= ret;
1333 pos += ret;
1334 }
1335 }
1336#else
1337 fd_set wfds, efds;
abadcafe38772c92015-04-03 22:23:04 +08001338
1339 while (kSize > 0) {
Lei Feiweib5ebcd12015-04-04 22:12:07 +08001340 FD_ZERO(&wfds);
1341 FD_ZERO(&efds);
1342 FD_SET(fd, &wfds);
1343 FD_SET(fd, &efds);
zeshuai00726681fb2020-06-03 17:24:38 +08001344 ret = select(static_cast<int>(fd + 1), nullptr, &wfds, &efds, nullptr);
abadcafe38772c92015-04-03 22:23:04 +08001345 if (ret < 0) {
1346 return false;
1347 } else if (ret == 0) {
1348 continue;
1349 }
1350
Lei Feiweib5ebcd12015-04-04 22:12:07 +08001351 if (FD_ISSET(fd, &efds)) {
1352 ::THRIFT_CLOSESOCKET(fd);
abadcafe38772c92015-04-03 22:23:04 +08001353 return false;
1354 }
1355
Lei Feiweib5ebcd12015-04-04 22:12:07 +08001356 if (FD_ISSET(fd, &wfds)) {
abadcafe38772c92015-04-03 22:23:04 +08001357 ret = send(fd, pos, kSize, 0);
1358 if (ret < 0) {
1359 if (errno == EAGAIN) {
1360 continue;
1361 }
1362
Lei Feiweib5ebcd12015-04-04 22:12:07 +08001363 ::THRIFT_CLOSESOCKET(fd);
abadcafe38772c92015-04-03 22:23:04 +08001364 return false;
1365 }
1366
1367 kSize -= ret;
1368 pos += ret;
1369 }
Jake Farrellb0d95602011-12-06 01:17:26 +00001370 }
st0ke961fa702018-10-12 18:37:40 +07001371#endif
Jake Farrellb0d95602011-12-06 01:17:26 +00001372
1373 return true;
1374}
1375
1376/* static */
Roger Meier12d70532011-12-14 23:35:28 +00001377void TNonblockingIOThread::notifyHandler(evutil_socket_t fd, short which, void* v) {
Sebastian Zenker042580f2019-01-29 15:48:12 +01001378 auto* ioThread = (TNonblockingIOThread*)v;
Jake Farrellb0d95602011-12-06 01:17:26 +00001379 assert(ioThread);
Roger Meierd0cdecf2011-12-08 19:34:01 +00001380 (void)which;
Jake Farrellb0d95602011-12-06 01:17:26 +00001381
1382 while (true) {
Sebastian Zenker042580f2019-01-29 15:48:12 +01001383 TNonblockingServer::TConnection* connection = nullptr;
Jake Farrellb0d95602011-12-06 01:17:26 +00001384 const int kSize = sizeof(connection);
Ben Craig64935232013-10-09 15:21:38 -05001385 long nBytes = recv(fd, cast_sockopt(&connection), kSize, 0);
Jake Farrellb0d95602011-12-06 01:17:26 +00001386 if (nBytes == kSize) {
Sebastian Zenker042580f2019-01-29 15:48:12 +01001387 if (connection == nullptr) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001388 // this is the command to stop our thread, exit the handler!
Buğra Gedik36d1b0d2016-09-04 17:18:15 +09001389 ioThread->breakLoop(false);
Jake Farrellb0d95602011-12-06 01:17:26 +00001390 return;
1391 }
1392 connection->transition();
1393 } else if (nBytes > 0) {
1394 // throw away these bytes and hope that next time we get a solid read
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001395 GlobalOutput.printf("notifyHandler: Bad read of %d bytes, wanted %d", nBytes, kSize);
Jake Farrellb0d95602011-12-06 01:17:26 +00001396 ioThread->breakLoop(true);
1397 return;
1398 } else if (nBytes == 0) {
1399 GlobalOutput.printf("notifyHandler: Notify socket closed!");
Buğra Gedik36d1b0d2016-09-04 17:18:15 +09001400 ioThread->breakLoop(false);
Jake Farrellb0d95602011-12-06 01:17:26 +00001401 // exit the loop
1402 break;
1403 } else { // nBytes < 0
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001404 if (THRIFT_GET_SOCKET_ERROR != THRIFT_EWOULDBLOCK
1405 && THRIFT_GET_SOCKET_ERROR != THRIFT_EAGAIN) {
1406 GlobalOutput.perror("TNonblocking: notifyHandler read() failed: ", THRIFT_GET_SOCKET_ERROR);
1407 ioThread->breakLoop(true);
1408 return;
Jake Farrellb0d95602011-12-06 01:17:26 +00001409 }
1410 // exit the loop
1411 break;
1412 }
1413 }
1414}
1415
1416void TNonblockingIOThread::breakLoop(bool error) {
1417 if (error) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001418 GlobalOutput.printf("TNonblockingServer: IO thread #%d exiting with error.", number_);
Jake Farrellb0d95602011-12-06 01:17:26 +00001419 // TODO: figure out something better to do here, but for now kill the
1420 // whole process.
1421 GlobalOutput.printf("TNonblockingServer: aborting process.");
1422 ::abort();
1423 }
1424
Jake Farrellb0d95602011-12-06 01:17:26 +00001425 // If we're running in the same thread, we can't use the notify(0)
1426 // mechanism to stop the thread, but happily if we're running in the
1427 // same thread, this means the thread can't be blocking in the event
1428 // loop either.
Roger Meier12d70532011-12-14 23:35:28 +00001429 if (!Thread::is_current(threadId_)) {
Sebastian Zenker042580f2019-01-29 15:48:12 +01001430 notify(nullptr);
Buğra Gedik36d1b0d2016-09-04 17:18:15 +09001431 } else {
1432 // cause the loop to stop ASAP - even if it has things to do in it
1433 event_base_loopbreak(eventBase_);
Jake Farrellb0d95602011-12-06 01:17:26 +00001434 }
1435}
1436
1437void TNonblockingIOThread::setCurrentThreadHighPriority(bool value) {
Roger Meier12d70532011-12-14 23:35:28 +00001438#ifdef HAVE_SCHED_H
Jake Farrellb0d95602011-12-06 01:17:26 +00001439 // Start out with a standard, low-priority setup for the sched params.
1440 struct sched_param sp;
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001441 bzero((void*)&sp, sizeof(sp));
Jake Farrellb0d95602011-12-06 01:17:26 +00001442 int policy = SCHED_OTHER;
1443
1444 // If desired, set up high-priority sched params structure.
1445 if (value) {
1446 // FIFO scheduler, ranked above default SCHED_OTHER queue
1447 policy = SCHED_FIFO;
1448 // The priority only compares us to other SCHED_FIFO threads, so we
1449 // just pick a random priority halfway between min & max.
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001450 const int priority = (sched_get_priority_max(policy) + sched_get_priority_min(policy)) / 2;
Jake Farrellb0d95602011-12-06 01:17:26 +00001451
1452 sp.sched_priority = priority;
Bryan Duxbury76c43682011-08-24 21:26:48 +00001453 }
1454
Jake Farrellb0d95602011-12-06 01:17:26 +00001455 // Actually set the sched params for the current thread.
1456 if (0 == pthread_setschedparam(pthread_self(), policy, &sp)) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001457 GlobalOutput.printf("TNonblocking: IO Thread #%d using high-priority scheduler!", number_);
Jake Farrellb0d95602011-12-06 01:17:26 +00001458 } else {
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -04001459 GlobalOutput.perror("TNonblocking: pthread_setschedparam(): ", THRIFT_GET_SOCKET_ERROR);
Jake Farrellb0d95602011-12-06 01:17:26 +00001460 }
Roger Meierd051ca02013-08-15 01:35:11 +02001461#else
1462 THRIFT_UNUSED_VARIABLE(value);
Roger Meier12d70532011-12-14 23:35:28 +00001463#endif
Jake Farrellb0d95602011-12-06 01:17:26 +00001464}
Bryan Duxbury76c43682011-08-24 21:26:48 +00001465
Jake Farrellb0d95602011-12-06 01:17:26 +00001466void TNonblockingIOThread::run() {
Sebastian Zenker042580f2019-01-29 15:48:12 +01001467 if (eventBase_ == nullptr) {
Roger Meier6f2a5032013-07-08 23:35:25 +02001468 registerEvents();
Buğra Gedik36d1b0d2016-09-04 17:18:15 +09001469 }
Jake Farrellb0d95602011-12-06 01:17:26 +00001470 if (useHighPriority_) {
1471 setCurrentThreadHighPriority(true);
1472 }
1473
Sebastian Zenker042580f2019-01-29 15:48:12 +01001474 if (eventBase_ != nullptr)
Buğra Gedik36d1b0d2016-09-04 17:18:15 +09001475 {
1476 GlobalOutput.printf("TNonblockingServer: IO thread #%d entering loop...", number_);
1477 // Run libevent engine, never returns, invokes calls to eventHandler
1478 event_base_loop(eventBase_, 0);
Jake Farrellb0d95602011-12-06 01:17:26 +00001479
Buğra Gedik36d1b0d2016-09-04 17:18:15 +09001480 if (useHighPriority_) {
1481 setCurrentThreadHighPriority(false);
1482 }
1483
1484 // cleans up our registered events
1485 cleanupEvents();
Jake Farrellb0d95602011-12-06 01:17:26 +00001486 }
1487
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001488 GlobalOutput.printf("TNonblockingServer: IO thread #%d run() done!", number_);
Jake Farrellb0d95602011-12-06 01:17:26 +00001489}
1490
1491void TNonblockingIOThread::cleanupEvents() {
1492 // stop the listen socket, if any
gzshi41945622017-01-06 10:47:03 +08001493 if (listenSocket_ != THRIFT_INVALID_SOCKET) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001494 if (event_del(&serverEvent_) == -1) {
Carl Yeksigian7cb7fc82013-06-07 07:33:01 -04001495 GlobalOutput.perror("TNonblockingIOThread::stop() event_del: ", THRIFT_GET_SOCKET_ERROR);
Jake Farrellb0d95602011-12-06 01:17:26 +00001496 }
1497 }
1498
1499 event_del(&notificationEvent_);
1500}
1501
Jake Farrellb0d95602011-12-06 01:17:26 +00001502void TNonblockingIOThread::stop() {
1503 // This should cause the thread to fall out of its event loop ASAP.
1504 breakLoop(false);
1505}
1506
1507void TNonblockingIOThread::join() {
1508 // If this was a thread created by a factory (not the thread that called
1509 // serve()), we join() it to make sure we shut down fully.
1510 if (thread_) {
1511 try {
1512 // Note that it is safe to both join() ourselves twice, as well as join
1513 // the current thread as the pthread implementation checks for deadlock.
1514 thread_->join();
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001515 } catch (...) {
Jake Farrellb0d95602011-12-06 01:17:26 +00001516 // swallow everything
1517 }
1518 }
Bryan Duxbury76c43682011-08-24 21:26:48 +00001519}
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001520}
1521}
1522} // apache::thrift::server