blob: 14fb5bc15f20cd2ce9103b9eff21a3d2a4c56296 [file] [log] [blame]
Mark Slee2f6404d2006-10-10 01:37:40 +00001#include "TNonblockingServer.h"
2
3#include <sys/socket.h>
4#include <netinet/in.h>
5#include <netinet/tcp.h>
6#include <fcntl.h>
7#include <errno.h>
8#include <assert.h>
9
10namespace facebook { namespace thrift { namespace server {
11
12void TConnection::init(int socket, short eventFlags, TNonblockingServer* s) {
13 socket_ = socket;
14 server_ = s;
15 appState_ = APP_INIT;
16 eventFlags_ = 0;
17
18 readBufferPos_ = 0;
19 readWant_ = 0;
20
21 writeBuffer_ = NULL;
22 writeBufferSize_ = 0;
23 writeBufferPos_ = 0;
24
25 socketState_ = SOCKET_RECV;
26 appState_ = APP_INIT;
27
28 // Set flags, which also registers the event
29 setFlags(eventFlags);
30}
31
32void TConnection::workSocket() {
33 int flags;
34
35 switch (socketState_) {
36 case SOCKET_RECV:
37 // It is an error to be in this state if we already have all the data
38 assert(readBufferPos_ < readWant_);
39
40 // How much space is availble, and how much will we fetch
41 uint32_t avail = readBufferSize_ - readBufferPos_;
42 uint32_t fetch = readWant_ - readBufferPos_;
43
44 // Double the buffer size until it is big enough
45 if (fetch > avail) {
46 while (fetch > avail) {
47 readBufferSize_ *= 2;
48 }
49 readBuffer_ = (uint8_t*)realloc(readBuffer_, readBufferSize_);
50 if (readBuffer_ == NULL) {
51 perror("TConnection::workSocket() realloc");
52 close();
53 return;
54 }
55 }
56
57 // Read from the socket
58 int got = recv(socket_, readBuffer_ + readBufferPos_, fetch, 0);
59
60 if (got > 0) {
61 // Move along in the buffer
62 readBufferPos_ += got;
63
64 // Check that we did not overdo it
65 assert(readBufferPos_ <= readWant_);
66
67 // We are done reading, move onto the next state
68 if (readBufferPos_ == readWant_) {
69 transition();
70 }
71 return;
72 } else if (got == -1) {
73 // Blocking errors are okay, just move on
74 if (errno == EAGAIN || errno == EWOULDBLOCK) {
75 return;
76 }
77
78 if (errno != ECONNRESET) {
79 perror("TConnection::workSocket() recv -1");
80 }
81 }
82
83 // Whenever we get down here it means a remote disconnect
84 close();
85
86 return;
87
88 case SOCKET_SEND:
89 // Should never have position past size
90 assert(writeBufferPos_ <= writeBufferSize_);
91
92 // If there is no data to send, then let us move on
93 if (writeBufferPos_ == writeBufferSize_) {
94 fprintf(stderr, "WARNING: Send state with no data to send\n");
95 transition();
96 return;
97 }
98
99 flags = 0;
100 #ifdef MSG_NOSIGNAL
101 // Note the use of MSG_NOSIGNAL to suppress SIGPIPE errors, instead we
102 // check for the EPIPE return condition and close the socket in that case
103 flags |= MSG_NOSIGNAL;
104 #endif // ifdef MSG_NOSIGNAL
105
106 int left = writeBufferSize_ - writeBufferPos_;
107 int sent = send(socket_, writeBuffer_ + writeBufferPos_, left, flags);
108
109 if (sent <= 0) {
110 // Blocking errors are okay, just move on
111 if (errno == EAGAIN || errno == EWOULDBLOCK) {
112 return;
113 }
114 if (errno != EPIPE) {
115 perror("TConnection::workSocket() send -1");
116 }
117 close();
118 return;
119 }
120
121 writeBufferPos_ += sent;
122
123 // Did we overdo it?
124 assert(writeBufferPos_ <= writeBufferSize_);
125
126 // We are done!
127 if (writeBufferPos_ == writeBufferSize_) {
128 transition();
129 }
130
131 return;
132
133 default:
134 fprintf(stderr, "Shit Got Ill. Socket State %d\n", socketState_);
135 assert(0);
136 }
137}
138
139/**
140 * This is called when the application transitions from one state into
141 * another. This means that it has finished writing the data that it needed
142 * to, or finished receiving the data that it needed to.
143 */
144void TConnection::transition() {
145 // Switch upon the state that we are currently in and move to a new state
146 switch (appState_) {
147
148 case APP_READ_REQUEST:
149 // We are done reading the request, package the read buffer into transport
150 // and get back some data from the dispatch function
151 inputTransport_->resetBuffer(readBuffer_, readBufferPos_);
152 outputTransport_->resetBuffer();
153
154 try {
155 // Invoke the processor
156 server_->getProcessor()->process(inputTransport_, outputTransport_);
157 } catch (TTransportException &x) {
158 fprintf(stderr, "Server::process %s\n", x.getMessage().c_str());
159 close();
160 return;
161 } catch (...) {
162 fprintf(stderr, "Server::process() unknown exception\n");
163 close();
164 return;
165 }
166
167
168 // Get the result of the operation
169 outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_);
170
171 // If the function call generated return data, then move into the send
172 // state and get going
173 if (writeBufferSize_ > 0) {
174
175 // Move into write state
176 writeBufferPos_ = 0;
177 socketState_ = SOCKET_SEND;
178 appState_ = APP_SEND_RESULT;
179
180 // Socket into write mode
181 setWrite();
182
183 // Try to work the socket immediately
184 workSocket();
185
186 return;
187 }
188
189 // In this case, the request was asynchronous and we should fall through
190 // right back into the read frame header state
191
192 case APP_SEND_RESULT:
193
194 // N.B.: We also intentionally fall through here into the INIT state!
195
196 case APP_INIT:
197
198 // Clear write buffer variables
199 writeBuffer_ = NULL;
200 writeBufferPos_ = 0;
201 writeBufferSize_ = 0;
202
203 // Set up read buffer for getting 4 bytes
204 readBufferPos_ = 0;
205 readWant_ = 4;
206
207 // Into read4 state we go
208 socketState_ = SOCKET_RECV;
209 appState_ = APP_READ_FRAME_SIZE;
210
211 // Register read event
212 setRead();
213
214 // Try to work the socket right away
215 workSocket();
216
217 return;
218
219 case APP_READ_FRAME_SIZE:
220 // We just read the request length, deserialize it
221 int sz = *(int32_t*)readBuffer_;
222 sz = (int32_t)ntohl(sz);
223
224 if (sz <= 0) {
225 fprintf(stderr, "TConnection:transition() Negative frame size %d, remote side not using TFramedTransport?", sz);
226 close();
227 return;
228 }
229
230 // Reset the read buffer
231 readWant_ = (uint32_t)sz;
232 readBufferPos_= 0;
233
234 // Move into read request state
235 appState_ = APP_READ_REQUEST;
236
237 // Work the socket right away
238 workSocket();
239
240 return;
241
242 default:
243 fprintf(stderr, "Totally Fucked. Application State %d\n", appState_);
244 assert(0);
245 }
246}
247
248void TConnection::setFlags(short eventFlags) {
249 // Catch the do nothing case
250 if (eventFlags_ == eventFlags) {
251 return;
252 }
253
254 // Delete a previously existing event
255 if (eventFlags_ != 0) {
256 if (event_del(&event_) == -1) {
257 perror("TConnection::setFlags event_del");
258 return;
259 }
260 }
261
262 // Update in memory structure
263 eventFlags_ = eventFlags;
264
265 /**
266 * event_set:
267 *
268 * Prepares the event structure &event to be used in future calls to
269 * event_add() and event_del(). The event will be prepared to call the
270 * event_handler using the 'sock' file descriptor to monitor events.
271 *
272 * The events can be either EV_READ, EV_WRITE, or both, indicating
273 * that an application can read or write from the file respectively without
274 * blocking.
275 *
276 * The event_handler will be called with the file descriptor that triggered
277 * the event and the type of event which will be one of: EV_TIMEOUT,
278 * EV_SIGNAL, EV_READ, EV_WRITE.
279 *
280 * The additional flag EV_PERSIST makes an event_add() persistent until
281 * event_del() has been called.
282 *
283 * Once initialized, the &event struct can be used repeatedly with
284 * event_add() and event_del() and does not need to be reinitialized unless
285 * the event_handler and/or the argument to it are to be changed. However,
286 * when an ev structure has been added to libevent using event_add() the
287 * structure must persist until the event occurs (assuming EV_PERSIST
288 * is not set) or is removed using event_del(). You may not reuse the same
289 * ev structure for multiple monitored descriptors; each descriptor needs
290 * its own ev.
291 */
292 event_set(&event_, socket_, eventFlags_, TConnection::eventHandler, this);
293
294 // Add the event
295 if (event_add(&event_, 0) == -1) {
296 perror("TConnection::setFlags(): coult not event_add");
297 }
298}
299
300/**
301 * Closes a connection
302 */
303void TConnection::close() {
304 // Delete the registered libevent
305 if (event_del(&event_) == -1) {
306 perror("TConnection::close() event_del");
307 }
308
309 // Close the socket
310 if (socket_ > 0) {
311 ::close(socket_);
312 }
313 socket_ = 0;
314
315 // Give this object back to the server that owns it
316 server_->returnConnection(this);
317}
318
319/**
320 * Creates a new connection either by reusing an object off the stack or
321 * by allocating a new one entirely
322 */
323TConnection* TNonblockingServer::createConnection(int socket, short flags) {
324 // Check the stack
325 if (connectionStack_.empty()) {
326 return new TConnection(socket, flags, this);
327 } else {
328 TConnection* result = connectionStack_.top();
329 connectionStack_.pop();
330 result->init(socket, flags, this);
331 return result;
332 }
333}
334
335/**
336 * Returns a connection to the stack
337 */
338void TNonblockingServer::returnConnection(TConnection* connection) {
339 connectionStack_.push(connection);
340}
341
342/**
343 * Server socket had something happen
344 */
345void TNonblockingServer::handleEvent(int fd, short which) {
346 // Make sure that libevent didn't fuck up the socket handles
347 assert(fd == serverSocket_);
348
349 // Server socket accepted a new connection
350 socklen_t addrLen;
351 struct sockaddr addr;
352 addrLen = sizeof(addr);
353
354 // Going to accept a new client socket
355 int clientSocket;
356
357 // Accept as many new clients as possible, even though libevent signaled only
358 // one, this helps us to avoid having to go back into the libevent engine so
359 // many times
360 while ((clientSocket = accept(fd, &addr, &addrLen)) != -1) {
361
362 // Explicitly set this socket to NONBLOCK mode
363 int flags;
364 if ((flags = fcntl(clientSocket, F_GETFL, 0)) < 0 ||
365 fcntl(clientSocket, F_SETFL, flags | O_NONBLOCK) < 0) {
366 perror("thriftServerEventHandler: set O_NONBLOCK");
367 close(clientSocket);
368 return;
369 }
370
371 // Create a new TConnection for this client socket.
372 TConnection* clientConnection =
373 createConnection(clientSocket, EV_READ | EV_PERSIST);
374
375 // Fail fast if we could not create a TConnection object
376 if (clientConnection == NULL) {
377 fprintf(stderr, "thriftServerEventHandler: failed TConnection factory");
378 close(clientSocket);
379 return;
380 }
381
382 // Put this client connection into the proper state
383 clientConnection->transition();
384 }
385
386 // Done looping accept, now we have to make sure the error is due to
387 // blocking. Any other error is a problem
388 if (errno != EAGAIN && errno != EWOULDBLOCK) {
389 perror("thriftServerEventHandler: accept()");
390 }
391}
392
393/**
394 * Main workhorse function, starts up the server listening on a port and
395 * loops over the libevent handler.
396 */
397void TNonblockingServer::serve() {
398 // Initialize libevent
399 event_init();
400
401 // Print some libevent stats
402 fprintf(stderr,
403 "libevent %s method %s\n",
404 event_get_version(),
405 event_get_method());
406
407 // Create the server socket
408 serverSocket_ = socket(AF_INET, SOCK_STREAM, 0);
409 if (serverSocket_ == -1) {
410 perror("TNonblockingServer::serve() socket() -1");
411 return;
412 }
413
414 // Set socket to nonblocking mode
415 int flags;
416 if ((flags = fcntl(serverSocket_, F_GETFL, 0)) < 0 ||
417 fcntl(serverSocket_, F_SETFL, flags | O_NONBLOCK) < 0) {
418 perror("TNonblockingServer::serve() O_NONBLOCK");
419 ::close(serverSocket_);
420 return;
421 }
422
423 int one = 1;
424 struct linger ling = {0, 0};
425
426 // Set reuseaddr to avoid 2MSL delay on server restart
427 setsockopt(serverSocket_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
428
429 // Keepalive to ensure full result flushing
430 setsockopt(serverSocket_, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
431
432 // Turn linger off to avoid hung sockets
433 setsockopt(serverSocket_, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
434
435 // Set TCP nodelay if available, MAC OS X Hack
436 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
437 #ifndef TCP_NOPUSH
438 setsockopt(serverSocket_, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
439 #endif
440
441 struct sockaddr_in addr;
442 addr.sin_family = AF_INET;
443 addr.sin_port = htons(port_);
444 addr.sin_addr.s_addr = INADDR_ANY;
445
446 if (bind(serverSocket_, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
447 perror("TNonblockingServer::serve() bind");
448 close(serverSocket_);
449 return;
450 }
451
452 if (listen(serverSocket_, LISTEN_BACKLOG) == -1) {
453 perror("TNonblockingServer::serve() listen");
454 close(serverSocket_);
455 return;
456 }
457
458 // Register the server event
459 struct event serverEvent;
460 event_set(&serverEvent,
461 serverSocket_,
462 EV_READ | EV_PERSIST,
463 TNonblockingServer::eventHandler,
464 this);
465
466 // Add the event and start up the server
467 if (event_add(&serverEvent, 0) == -1) {
468 perror("TNonblockingServer::serve(): coult not event_add");
469 return;
470 }
471
472 // Run libevent engine, never returns, invokes calls to event_handler
473 event_loop(0);
474}
475
476}}} // facebook::thrift::server