blob: 75a209ea80067af825050b72da451ec087dc5f46 [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
Mark Slee4af6ed72006-10-25 19:02:49 +0000156 server_->getProcessor()->process(inputProtocol_, outputProtocol_);
Mark Slee2f6404d2006-10-10 01:37:40 +0000157 } 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
Mark Slee2f6404d2006-10-10 01:37:40 +0000167 // Get the result of the operation
168 outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_);
169
170 // If the function call generated return data, then move into the send
171 // state and get going
172 if (writeBufferSize_ > 0) {
173
174 // Move into write state
175 writeBufferPos_ = 0;
176 socketState_ = SOCKET_SEND;
Mark Slee92f00fb2006-10-25 01:28:17 +0000177
178 if (server_->getFrameResponses()) {
179 // Put the frame size into the write buffer
180 appState_ = APP_SEND_FRAME_SIZE;
181 frameSize_ = (int32_t)htonl(writeBufferSize_);
182 writeBuffer_ = (uint8_t*)&frameSize_;
183 writeBufferSize_ = 4;
184 } else {
185 // Go straight into sending the result, do not frame it
186 appState_ = APP_SEND_RESULT;
187 }
Mark Slee2f6404d2006-10-10 01:37:40 +0000188
189 // Socket into write mode
190 setWrite();
191
192 // Try to work the socket immediately
193 workSocket();
194
195 return;
196 }
197
198 // In this case, the request was asynchronous and we should fall through
199 // right back into the read frame header state
Mark Slee92f00fb2006-10-25 01:28:17 +0000200 goto LABEL_APP_INIT;
201
202 case APP_SEND_FRAME_SIZE:
203
204 // Refetch the result of the operation since we put the frame size into
205 // writeBuffer_
206 outputTransport_->getBuffer(&writeBuffer_, &writeBufferSize_);
207 writeBufferPos_ = 0;
208
209 // Now in send result state
210 appState_ = APP_SEND_RESULT;
211
212 // Go to work on the socket right away, probably still writeable
213 workSocket();
214
215 return;
Mark Slee2f6404d2006-10-10 01:37:40 +0000216
217 case APP_SEND_RESULT:
218
219 // N.B.: We also intentionally fall through here into the INIT state!
220
Mark Slee92f00fb2006-10-25 01:28:17 +0000221 LABEL_APP_INIT:
Mark Slee2f6404d2006-10-10 01:37:40 +0000222 case APP_INIT:
223
224 // Clear write buffer variables
225 writeBuffer_ = NULL;
226 writeBufferPos_ = 0;
227 writeBufferSize_ = 0;
228
229 // Set up read buffer for getting 4 bytes
230 readBufferPos_ = 0;
231 readWant_ = 4;
232
233 // Into read4 state we go
234 socketState_ = SOCKET_RECV;
235 appState_ = APP_READ_FRAME_SIZE;
236
237 // Register read event
238 setRead();
239
240 // Try to work the socket right away
241 workSocket();
242
243 return;
244
245 case APP_READ_FRAME_SIZE:
246 // We just read the request length, deserialize it
247 int sz = *(int32_t*)readBuffer_;
248 sz = (int32_t)ntohl(sz);
249
250 if (sz <= 0) {
251 fprintf(stderr, "TConnection:transition() Negative frame size %d, remote side not using TFramedTransport?", sz);
252 close();
253 return;
254 }
255
256 // Reset the read buffer
257 readWant_ = (uint32_t)sz;
258 readBufferPos_= 0;
259
260 // Move into read request state
261 appState_ = APP_READ_REQUEST;
262
263 // Work the socket right away
264 workSocket();
265
266 return;
267
268 default:
269 fprintf(stderr, "Totally Fucked. Application State %d\n", appState_);
270 assert(0);
271 }
272}
273
274void TConnection::setFlags(short eventFlags) {
275 // Catch the do nothing case
276 if (eventFlags_ == eventFlags) {
277 return;
278 }
279
280 // Delete a previously existing event
281 if (eventFlags_ != 0) {
282 if (event_del(&event_) == -1) {
283 perror("TConnection::setFlags event_del");
284 return;
285 }
286 }
287
288 // Update in memory structure
289 eventFlags_ = eventFlags;
290
291 /**
292 * event_set:
293 *
294 * Prepares the event structure &event to be used in future calls to
295 * event_add() and event_del(). The event will be prepared to call the
296 * event_handler using the 'sock' file descriptor to monitor events.
297 *
298 * The events can be either EV_READ, EV_WRITE, or both, indicating
299 * that an application can read or write from the file respectively without
300 * blocking.
301 *
302 * The event_handler will be called with the file descriptor that triggered
303 * the event and the type of event which will be one of: EV_TIMEOUT,
304 * EV_SIGNAL, EV_READ, EV_WRITE.
305 *
306 * The additional flag EV_PERSIST makes an event_add() persistent until
307 * event_del() has been called.
308 *
309 * Once initialized, the &event struct can be used repeatedly with
310 * event_add() and event_del() and does not need to be reinitialized unless
311 * the event_handler and/or the argument to it are to be changed. However,
312 * when an ev structure has been added to libevent using event_add() the
313 * structure must persist until the event occurs (assuming EV_PERSIST
314 * is not set) or is removed using event_del(). You may not reuse the same
315 * ev structure for multiple monitored descriptors; each descriptor needs
316 * its own ev.
317 */
318 event_set(&event_, socket_, eventFlags_, TConnection::eventHandler, this);
319
320 // Add the event
321 if (event_add(&event_, 0) == -1) {
322 perror("TConnection::setFlags(): coult not event_add");
323 }
324}
325
326/**
327 * Closes a connection
328 */
329void TConnection::close() {
330 // Delete the registered libevent
331 if (event_del(&event_) == -1) {
332 perror("TConnection::close() event_del");
333 }
334
335 // Close the socket
336 if (socket_ > 0) {
337 ::close(socket_);
338 }
339 socket_ = 0;
340
341 // Give this object back to the server that owns it
342 server_->returnConnection(this);
343}
344
345/**
346 * Creates a new connection either by reusing an object off the stack or
347 * by allocating a new one entirely
348 */
349TConnection* TNonblockingServer::createConnection(int socket, short flags) {
350 // Check the stack
351 if (connectionStack_.empty()) {
352 return new TConnection(socket, flags, this);
353 } else {
354 TConnection* result = connectionStack_.top();
355 connectionStack_.pop();
356 result->init(socket, flags, this);
357 return result;
358 }
359}
360
361/**
362 * Returns a connection to the stack
363 */
364void TNonblockingServer::returnConnection(TConnection* connection) {
365 connectionStack_.push(connection);
366}
367
368/**
369 * Server socket had something happen
370 */
371void TNonblockingServer::handleEvent(int fd, short which) {
372 // Make sure that libevent didn't fuck up the socket handles
373 assert(fd == serverSocket_);
374
375 // Server socket accepted a new connection
376 socklen_t addrLen;
377 struct sockaddr addr;
378 addrLen = sizeof(addr);
379
380 // Going to accept a new client socket
381 int clientSocket;
382
383 // Accept as many new clients as possible, even though libevent signaled only
384 // one, this helps us to avoid having to go back into the libevent engine so
385 // many times
386 while ((clientSocket = accept(fd, &addr, &addrLen)) != -1) {
387
388 // Explicitly set this socket to NONBLOCK mode
389 int flags;
390 if ((flags = fcntl(clientSocket, F_GETFL, 0)) < 0 ||
391 fcntl(clientSocket, F_SETFL, flags | O_NONBLOCK) < 0) {
392 perror("thriftServerEventHandler: set O_NONBLOCK");
393 close(clientSocket);
394 return;
395 }
396
397 // Create a new TConnection for this client socket.
398 TConnection* clientConnection =
399 createConnection(clientSocket, EV_READ | EV_PERSIST);
400
401 // Fail fast if we could not create a TConnection object
402 if (clientConnection == NULL) {
403 fprintf(stderr, "thriftServerEventHandler: failed TConnection factory");
404 close(clientSocket);
405 return;
406 }
407
408 // Put this client connection into the proper state
409 clientConnection->transition();
410 }
411
412 // Done looping accept, now we have to make sure the error is due to
413 // blocking. Any other error is a problem
414 if (errno != EAGAIN && errno != EWOULDBLOCK) {
415 perror("thriftServerEventHandler: accept()");
416 }
417}
418
419/**
420 * Main workhorse function, starts up the server listening on a port and
421 * loops over the libevent handler.
422 */
423void TNonblockingServer::serve() {
424 // Initialize libevent
425 event_init();
426
427 // Print some libevent stats
428 fprintf(stderr,
429 "libevent %s method %s\n",
430 event_get_version(),
431 event_get_method());
432
433 // Create the server socket
434 serverSocket_ = socket(AF_INET, SOCK_STREAM, 0);
435 if (serverSocket_ == -1) {
436 perror("TNonblockingServer::serve() socket() -1");
437 return;
438 }
439
440 // Set socket to nonblocking mode
441 int flags;
442 if ((flags = fcntl(serverSocket_, F_GETFL, 0)) < 0 ||
443 fcntl(serverSocket_, F_SETFL, flags | O_NONBLOCK) < 0) {
444 perror("TNonblockingServer::serve() O_NONBLOCK");
445 ::close(serverSocket_);
446 return;
447 }
448
449 int one = 1;
450 struct linger ling = {0, 0};
451
452 // Set reuseaddr to avoid 2MSL delay on server restart
453 setsockopt(serverSocket_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
454
455 // Keepalive to ensure full result flushing
456 setsockopt(serverSocket_, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
457
458 // Turn linger off to avoid hung sockets
459 setsockopt(serverSocket_, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
460
461 // Set TCP nodelay if available, MAC OS X Hack
462 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
463 #ifndef TCP_NOPUSH
464 setsockopt(serverSocket_, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
465 #endif
466
467 struct sockaddr_in addr;
468 addr.sin_family = AF_INET;
469 addr.sin_port = htons(port_);
470 addr.sin_addr.s_addr = INADDR_ANY;
471
472 if (bind(serverSocket_, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
473 perror("TNonblockingServer::serve() bind");
474 close(serverSocket_);
475 return;
476 }
477
478 if (listen(serverSocket_, LISTEN_BACKLOG) == -1) {
479 perror("TNonblockingServer::serve() listen");
480 close(serverSocket_);
481 return;
482 }
483
484 // Register the server event
485 struct event serverEvent;
486 event_set(&serverEvent,
487 serverSocket_,
488 EV_READ | EV_PERSIST,
489 TNonblockingServer::eventHandler,
490 this);
491
492 // Add the event and start up the server
493 if (event_add(&serverEvent, 0) == -1) {
494 perror("TNonblockingServer::serve(): coult not event_add");
495 return;
496 }
497
498 // Run libevent engine, never returns, invokes calls to event_handler
499 event_loop(0);
500}
501
502}}} // facebook::thrift::server