Add REUSEPORT option to AsyncServerSocket
[folly.git] / folly / io / async / AsyncServerSocket.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef __STDC_FORMAT_MACROS
18   #define __STDC_FORMAT_MACROS
19 #endif
20
21 #include <folly/io/async/AsyncServerSocket.h>
22
23 #include <folly/io/async/EventBase.h>
24 #include <folly/io/async/NotificationQueue.h>
25 #include <folly/SocketAddress.h>
26
27 #include <errno.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <netinet/tcp.h>
34
35 namespace folly {
36
37 const uint32_t AsyncServerSocket::kDefaultMaxAcceptAtOnce;
38 const uint32_t AsyncServerSocket::kDefaultCallbackAcceptAtOnce;
39 const uint32_t AsyncServerSocket::kDefaultMaxMessagesInQueue;
40
41 int setCloseOnExec(int fd, int value) {
42   // Read the current flags
43   int old_flags = fcntl(fd, F_GETFD, 0);
44
45   // If reading the flags failed, return error indication now
46   if (old_flags < 0)
47     return -1;
48
49   // Set just the flag we want to set
50   int new_flags;
51   if (value != 0)
52     new_flags = old_flags | FD_CLOEXEC;
53   else
54     new_flags = old_flags & ~FD_CLOEXEC;
55
56   // Store modified flag word in the descriptor
57   return fcntl(fd, F_SETFD, new_flags);
58 }
59
60 void AsyncServerSocket::RemoteAcceptor::start(
61   EventBase* eventBase, uint32_t maxAtOnce, uint32_t maxInQueue) {
62   setMaxReadAtOnce(maxAtOnce);
63   queue_.setMaxQueueSize(maxInQueue);
64
65   if (!eventBase->runInEventBaseThread([=](){
66         callback_->acceptStarted();
67         this->startConsuming(eventBase, &queue_);
68       })) {
69     throw std::invalid_argument("unable to start waiting on accept "
70                             "notification queue in the specified "
71                             "EventBase thread");
72   }
73 }
74
75 void AsyncServerSocket::RemoteAcceptor::stop(
76   EventBase* eventBase, AcceptCallback* callback) {
77   if (!eventBase->runInEventBaseThread([=](){
78         callback->acceptStopped();
79         delete this;
80       })) {
81     throw std::invalid_argument("unable to start waiting on accept "
82                             "notification queue in the specified "
83                             "EventBase thread");
84   }
85 }
86
87 void AsyncServerSocket::RemoteAcceptor::messageAvailable(
88   QueueMessage&& msg) {
89
90   switch (msg.type) {
91     case MessageType::MSG_NEW_CONN:
92     {
93       callback_->connectionAccepted(msg.fd, msg.address);
94       break;
95     }
96     case MessageType::MSG_ERROR:
97     {
98       std::runtime_error ex(msg.msg);
99       callback_->acceptError(ex);
100       break;
101     }
102     default:
103     {
104       LOG(ERROR) << "invalid accept notification message type "
105                  << int(msg.type);
106       std::runtime_error ex(
107         "received invalid accept notification message type");
108       callback_->acceptError(ex);
109     }
110   }
111 }
112
113 /*
114  * AsyncServerSocket::BackoffTimeout
115  */
116 class AsyncServerSocket::BackoffTimeout : public AsyncTimeout {
117  public:
118   BackoffTimeout(AsyncServerSocket* socket)
119     : AsyncTimeout(socket->getEventBase()),
120       socket_(socket) {}
121
122   virtual void timeoutExpired() noexcept {
123     socket_->backoffTimeoutExpired();
124   }
125
126  private:
127   AsyncServerSocket* socket_;
128 };
129
130 /*
131  * AsyncServerSocket methods
132  */
133
134 AsyncServerSocket::AsyncServerSocket(EventBase* eventBase)
135 :   eventBase_(eventBase),
136     accepting_(false),
137     maxAcceptAtOnce_(kDefaultMaxAcceptAtOnce),
138     maxNumMsgsInQueue_(kDefaultMaxMessagesInQueue),
139     acceptRateAdjustSpeed_(0),
140     acceptRate_(1),
141     lastAccepTimestamp_(std::chrono::steady_clock::now()),
142     numDroppedConnections_(0),
143     callbackIndex_(0),
144     backoffTimeout_(nullptr),
145     callbacks_(),
146     keepAliveEnabled_(true),
147     closeOnExec_(true),
148     shutdownSocketSet_(nullptr) {
149 }
150
151 void AsyncServerSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
152   if (shutdownSocketSet_ == newSS) {
153     return;
154   }
155   if (shutdownSocketSet_) {
156     for (auto& h : sockets_) {
157       shutdownSocketSet_->remove(h.socket_);
158     }
159   }
160   shutdownSocketSet_ = newSS;
161   if (shutdownSocketSet_) {
162     for (auto& h : sockets_) {
163       shutdownSocketSet_->add(h.socket_);
164     }
165   }
166 }
167
168 AsyncServerSocket::~AsyncServerSocket() {
169   assert(callbacks_.empty());
170 }
171
172 int AsyncServerSocket::stopAccepting(int shutdownFlags) {
173   int result = 0;
174   for (auto& handler : sockets_) {
175     VLOG(10) << "AsyncServerSocket::stopAccepting " << this <<
176               handler.socket_;
177   }
178   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
179
180   // When destroy is called, unregister and close the socket immediately
181   accepting_ = false;
182
183   for (auto& handler : sockets_) {
184     handler.unregisterHandler();
185     if (shutdownSocketSet_) {
186       shutdownSocketSet_->close(handler.socket_);
187     } else if (shutdownFlags >= 0) {
188       result = ::shutdown(handler.socket_, shutdownFlags);
189       pendingCloseSockets_.push_back(handler.socket_);
190     } else {
191       ::close(handler.socket_);
192     }
193   }
194   sockets_.clear();
195
196   // Destroy the backoff timout.  This will cancel it if it is running.
197   delete backoffTimeout_;
198   backoffTimeout_ = nullptr;
199
200   // Close all of the callback queues to notify them that they are being
201   // destroyed.  No one should access the AsyncServerSocket any more once
202   // destroy() is called.  However, clear out callbacks_ before invoking the
203   // accept callbacks just in case.  This will potentially help us detect the
204   // bug if one of the callbacks calls addAcceptCallback() or
205   // removeAcceptCallback().
206   std::vector<CallbackInfo> callbacksCopy;
207   callbacks_.swap(callbacksCopy);
208   for (std::vector<CallbackInfo>::iterator it = callbacksCopy.begin();
209        it != callbacksCopy.end();
210        ++it) {
211     it->consumer->stop(it->eventBase, it->callback);
212   }
213
214   return result;
215 }
216
217 void AsyncServerSocket::destroy() {
218   stopAccepting();
219   for (auto s: pendingCloseSockets_) {
220     ::close(s);
221   }
222   // Then call DelayedDestruction::destroy() to take care of
223   // whether or not we need immediate or delayed destruction
224   DelayedDestruction::destroy();
225 }
226
227 void AsyncServerSocket::attachEventBase(EventBase *eventBase) {
228   assert(eventBase_ == nullptr);
229   assert(eventBase->isInEventBaseThread());
230
231   eventBase_ = eventBase;
232   for (auto& handler : sockets_) {
233     handler.attachEventBase(eventBase);
234   }
235 }
236
237 void AsyncServerSocket::detachEventBase() {
238   assert(eventBase_ != nullptr);
239   assert(eventBase_->isInEventBaseThread());
240   assert(!accepting_);
241
242   eventBase_ = nullptr;
243   for (auto& handler : sockets_) {
244     handler.detachEventBase();
245   }
246 }
247
248 void AsyncServerSocket::useExistingSockets(const std::vector<int>& fds) {
249   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
250
251   if (sockets_.size() > 0) {
252     throw std::invalid_argument(
253                               "cannot call useExistingSocket() on a "
254                               "AsyncServerSocket that already has a socket");
255   }
256
257   for (auto fd: fds) {
258     // Set addressFamily_ from this socket.
259     // Note that the socket may not have been bound yet, but
260     // setFromLocalAddress() will still work and get the correct address family.
261     // We will update addressFamily_ again anyway if bind() is called later.
262     SocketAddress address;
263     address.setFromLocalAddress(fd);
264
265     setupSocket(fd);
266     sockets_.push_back(
267       ServerEventHandler(eventBase_, fd, this, address.getFamily()));
268     sockets_.back().changeHandlerFD(fd);
269   }
270 }
271
272 void AsyncServerSocket::useExistingSocket(int fd) {
273   useExistingSockets({fd});
274 }
275
276 void AsyncServerSocket::bind(const SocketAddress& address) {
277   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
278
279   // useExistingSocket() may have been called to initialize socket_ already.
280   // However, in the normal case we need to create a new socket now.
281   // Don't set socket_ yet, so that socket_ will remain uninitialized if an
282   // error occurs.
283   int fd;
284   if (sockets_.size() == 0) {
285     fd = createSocket(address.getFamily());
286   } else if (sockets_.size() == 1) {
287     if (address.getFamily() != sockets_[0].addressFamily_) {
288       throw std::invalid_argument(
289                                 "Attempted to bind address to socket with "
290                                 "different address family");
291     }
292     fd = sockets_[0].socket_;
293   } else {
294     throw std::invalid_argument(
295                               "Attempted to bind to multiple fds");
296   }
297
298   // Bind to the socket
299   sockaddr_storage addrStorage;
300   address.getAddress(&addrStorage);
301   sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
302   if (::bind(fd, saddr, address.getActualSize()) != 0) {
303     if (sockets_.size() == 0) {
304       ::close(fd);
305     }
306     folly::throwSystemError(errno,
307                               "failed to bind to async server socket: " +
308                                 address.describe());
309   }
310
311   // Record the address family that we are using,
312   // so we know how much address space we need to record accepted addresses.
313
314   // If we just created this socket, update the EventHandler and set socket_
315   if (sockets_.size() == 0) {
316     sockets_.push_back(
317       ServerEventHandler(eventBase_, fd, this, address.getFamily()));
318     sockets_[0].changeHandlerFD(fd);
319   }
320 }
321
322 void AsyncServerSocket::bind(uint16_t port) {
323   struct addrinfo hints, *res, *res0;
324   char sport[sizeof("65536")];
325
326   memset(&hints, 0, sizeof(hints));
327   hints.ai_family = AF_UNSPEC;
328   hints.ai_socktype = SOCK_STREAM;
329   hints.ai_flags = AI_PASSIVE;
330   snprintf(sport, sizeof(sport), "%u", port);
331
332   if (getaddrinfo(nullptr, sport, &hints, &res0)) {
333     throw std::invalid_argument(
334                               "Attempted to bind address to socket with "
335                               "bad getaddrinfo");
336   }
337
338   folly::ScopeGuard guard = folly::makeGuard([&]{
339       freeaddrinfo(res0);
340     });
341   DCHECK(&guard);
342
343   for (res = res0; res; res = res->ai_next) {
344     int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
345     // IPv6/IPv4 may not be supported by the kernel
346     if (s < 0 && errno == EAFNOSUPPORT) {
347       continue;
348     }
349     CHECK(s);
350
351     try {
352       setupSocket(s);
353     } catch (...) {
354       ::close(s);
355       throw;
356     }
357
358     if (res->ai_family == AF_INET6) {
359       int v6only = 1;
360       CHECK(0 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
361                             &v6only, sizeof(v6only)));
362     }
363
364     SocketAddress address;
365     address.setFromLocalAddress(s);
366
367     sockets_.push_back(
368       ServerEventHandler(eventBase_, s, this, address.getFamily()));
369
370     // Bind to the socket
371     if (::bind(s, res->ai_addr, res->ai_addrlen) != 0) {
372       folly::throwSystemError(
373         errno,
374         "failed to bind to async server socket for port");
375     }
376   }
377   if (sockets_.size() == 0) {
378     throw std::runtime_error(
379         "did not bind any async server socket for port");
380   }
381 }
382
383 void AsyncServerSocket::listen(int backlog) {
384   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
385
386   // Start listening
387   for (auto& handler : sockets_) {
388     if (::listen(handler.socket_, backlog) == -1) {
389       folly::throwSystemError(errno,
390                                     "failed to listen on async server socket");
391     }
392   }
393 }
394
395 void AsyncServerSocket::getAddress(SocketAddress* addressReturn) const {
396   CHECK(sockets_.size() >= 1);
397   if (sockets_.size() > 1) {
398     VLOG(2) << "Warning: getAddress can return multiple addresses, " <<
399       "but getAddress was called, so only returning the first";
400   }
401   addressReturn->setFromLocalAddress(sockets_[0].socket_);
402 }
403
404 std::vector<SocketAddress> AsyncServerSocket::getAddresses()
405     const {
406   CHECK(sockets_.size() >= 1);
407   auto tsaVec = std::vector<SocketAddress>(sockets_.size());
408   auto tsaIter = tsaVec.begin();
409   for (const auto& socket : sockets_) {
410     (tsaIter++)->setFromLocalAddress(socket.socket_);
411   };
412   return tsaVec;
413 }
414
415 void AsyncServerSocket::addAcceptCallback(AcceptCallback *callback,
416                                            EventBase *eventBase,
417                                            uint32_t maxAtOnce) {
418   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
419
420   // If this is the first accept callback and we are supposed to be accepting,
421   // start accepting once the callback is installed.
422   bool runStartAccepting = accepting_ && callbacks_.empty();
423
424   if (!eventBase) {
425     eventBase = eventBase_; // Run in AsyncServerSocket's eventbase
426   }
427
428   callbacks_.push_back(CallbackInfo(callback, eventBase));
429
430   // Start the remote acceptor.
431   //
432   // It would be nice if we could avoid starting the remote acceptor if
433   // eventBase == eventBase_.  However, that would cause issues if
434   // detachEventBase() and attachEventBase() were ever used to change the
435   // primary EventBase for the server socket.  Therefore we require the caller
436   // to specify a nullptr EventBase if they want to ensure that the callback is
437   // always invoked in the primary EventBase, and to be able to invoke that
438   // callback more efficiently without having to use a notification queue.
439   RemoteAcceptor* acceptor = nullptr;
440   try {
441     acceptor = new RemoteAcceptor(callback);
442     acceptor->start(eventBase, maxAtOnce, maxNumMsgsInQueue_);
443   } catch (...) {
444     callbacks_.pop_back();
445     delete acceptor;
446     throw;
447   }
448   callbacks_.back().consumer = acceptor;
449
450   // If this is the first accept callback and we are supposed to be accepting,
451   // start accepting.
452   if (runStartAccepting) {
453     startAccepting();
454   }
455 }
456
457 void AsyncServerSocket::removeAcceptCallback(AcceptCallback *callback,
458                                               EventBase *eventBase) {
459   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
460
461   // Find the matching AcceptCallback.
462   // We just do a simple linear search; we don't expect removeAcceptCallback()
463   // to be called frequently, and we expect there to only be a small number of
464   // callbacks anyway.
465   std::vector<CallbackInfo>::iterator it = callbacks_.begin();
466   uint32_t n = 0;
467   while (true) {
468     if (it == callbacks_.end()) {
469       throw std::runtime_error("AsyncServerSocket::removeAcceptCallback(): "
470                               "accept callback not found");
471     }
472     if (it->callback == callback &&
473         (it->eventBase == eventBase || eventBase == nullptr)) {
474       break;
475     }
476     ++it;
477     ++n;
478   }
479
480   // Remove this callback from callbacks_.
481   //
482   // Do this before invoking the acceptStopped() callback, in case
483   // acceptStopped() invokes one of our methods that examines callbacks_.
484   //
485   // Save a copy of the CallbackInfo first.
486   CallbackInfo info(*it);
487   callbacks_.erase(it);
488   if (n < callbackIndex_) {
489     // We removed an element before callbackIndex_.  Move callbackIndex_ back
490     // one step, since things after n have been shifted back by 1.
491     --callbackIndex_;
492   } else {
493     // We removed something at or after callbackIndex_.
494     // If we removed the last element and callbackIndex_ was pointing at it,
495     // we need to reset callbackIndex_ to 0.
496     if (callbackIndex_ >= callbacks_.size()) {
497       callbackIndex_ = 0;
498     }
499   }
500
501   info.consumer->stop(info.eventBase, info.callback);
502
503   // If we are supposed to be accepting but the last accept callback
504   // was removed, unregister for events until a callback is added.
505   if (accepting_ && callbacks_.empty()) {
506     for (auto& handler : sockets_) {
507       handler.unregisterHandler();
508     }
509   }
510 }
511
512 void AsyncServerSocket::startAccepting() {
513   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
514
515   accepting_ = true;
516   if (callbacks_.empty()) {
517     // We can't actually begin accepting if no callbacks are defined.
518     // Wait until a callback is added to start accepting.
519     return;
520   }
521
522   for (auto& handler : sockets_) {
523     if (!handler.registerHandler(
524           EventHandler::READ | EventHandler::PERSIST)) {
525       throw std::runtime_error("failed to register for accept events");
526     }
527   }
528 }
529
530 void AsyncServerSocket::pauseAccepting() {
531   assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
532   accepting_ = false;
533   for (auto& handler : sockets_) {
534    handler. unregisterHandler();
535   }
536
537   // If we were in the accept backoff state, disable the backoff timeout
538   if (backoffTimeout_) {
539     backoffTimeout_->cancelTimeout();
540   }
541 }
542
543 int AsyncServerSocket::createSocket(int family) {
544   int fd = socket(family, SOCK_STREAM, 0);
545   if (fd == -1) {
546     folly::throwSystemError(errno, "error creating async server socket");
547   }
548
549   try {
550     setupSocket(fd);
551   } catch (...) {
552     ::close(fd);
553     throw;
554   }
555   return fd;
556 }
557
558 void AsyncServerSocket::setupSocket(int fd) {
559   // Get the address family
560   SocketAddress address;
561   address.setFromLocalAddress(fd);
562   auto family = address.getFamily();
563
564   // Put the socket in non-blocking mode
565   if (fcntl(fd, F_SETFL, O_NONBLOCK) != 0) {
566     folly::throwSystemError(errno,
567                             "failed to put socket in non-blocking mode");
568   }
569
570   // Set reuseaddr to avoid 2MSL delay on server restart
571   int one = 1;
572   if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) {
573     // This isn't a fatal error; just log an error message and continue
574     LOG(ERROR) << "failed to set SO_REUSEADDR on async server socket " << errno;
575   }
576
577   // Set reuseport to support multiple accept threads
578   int zero = 0;
579   if (reusePortEnabled_ &&
580       setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(int)) != 0) {
581     LOG(ERROR) << "failed to set SO_REUSEPORT on async server socket "
582                << strerror(errno);
583     folly::throwSystemError(errno,
584                             "failed to bind to async server socket: " +
585                             address.describe());
586   }
587
588   // Set keepalive as desired
589   if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
590                  (keepAliveEnabled_) ? &one : &zero, sizeof(int)) != 0) {
591     LOG(ERROR) << "failed to set SO_KEEPALIVE on async server socket: " <<
592             strerror(errno);
593   }
594
595   // Setup FD_CLOEXEC flag
596   if (closeOnExec_ &&
597       (-1 == folly::setCloseOnExec(fd, closeOnExec_))) {
598     LOG(ERROR) << "failed to set FD_CLOEXEC on async server socket: " <<
599             strerror(errno);
600   }
601
602   // Set TCP nodelay if available, MAC OS X Hack
603   // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
604 #ifndef TCP_NOPUSH
605   if (family != AF_UNIX) {
606     if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) != 0) {
607       // This isn't a fatal error; just log an error message and continue
608       LOG(ERROR) << "failed to set TCP_NODELAY on async server socket: " <<
609               strerror(errno);
610     }
611   }
612 #endif
613
614   if (shutdownSocketSet_) {
615     shutdownSocketSet_->add(fd);
616   }
617 }
618
619 void AsyncServerSocket::handlerReady(
620   uint16_t events, int fd, sa_family_t addressFamily) noexcept {
621   assert(!callbacks_.empty());
622   DestructorGuard dg(this);
623
624   // Only accept up to maxAcceptAtOnce_ connections at a time,
625   // to avoid starving other I/O handlers using this EventBase.
626   for (uint32_t n = 0; n < maxAcceptAtOnce_; ++n) {
627     SocketAddress address;
628
629     sockaddr_storage addrStorage;
630     socklen_t addrLen = sizeof(addrStorage);
631     sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
632
633     // In some cases, accept() doesn't seem to update these correctly.
634     saddr->sa_family = addressFamily;
635     if (addressFamily == AF_UNIX) {
636       addrLen = sizeof(struct sockaddr_un);
637     }
638
639     // Accept a new client socket
640 #ifdef SOCK_NONBLOCK
641     int clientSocket = accept4(fd, saddr, &addrLen, SOCK_NONBLOCK);
642 #else
643     int clientSocket = accept(fd, saddr, &addrLen);
644 #endif
645
646     address.setFromSockaddr(saddr, addrLen);
647
648     std::chrono::time_point<std::chrono::steady_clock> nowMs =
649       std::chrono::steady_clock::now();
650     int64_t timeSinceLastAccept = std::max(
651       int64_t(0),
652       nowMs.time_since_epoch().count() -
653       lastAccepTimestamp_.time_since_epoch().count());
654     lastAccepTimestamp_ = nowMs;
655     if (acceptRate_ < 1) {
656       acceptRate_ *= 1 + acceptRateAdjustSpeed_ * timeSinceLastAccept;
657       if (acceptRate_ >= 1) {
658         acceptRate_ = 1;
659       } else if (rand() > acceptRate_ * RAND_MAX) {
660         ++numDroppedConnections_;
661         if (clientSocket >= 0) {
662           ::close(clientSocket);
663         }
664         continue;
665       }
666     }
667
668     if (clientSocket < 0) {
669       if (errno == EAGAIN) {
670         // No more sockets to accept right now.
671         // Check for this code first, since it's the most common.
672         return;
673       } else if (errno == EMFILE || errno == ENFILE) {
674         // We're out of file descriptors.  Perhaps we're accepting connections
675         // too quickly. Pause accepting briefly to back off and give the server
676         // a chance to recover.
677         LOG(ERROR) << "accept failed: out of file descriptors; entering accept "
678                 "back-off state";
679         enterBackoff();
680
681         // Dispatch the error message
682         dispatchError("accept() failed", errno);
683       } else {
684         dispatchError("accept() failed", errno);
685       }
686       return;
687     }
688
689 #ifndef SOCK_NONBLOCK
690     // Explicitly set the new connection to non-blocking mode
691     if (fcntl(clientSocket, F_SETFL, O_NONBLOCK) != 0) {
692       ::close(clientSocket);
693       dispatchError("failed to set accepted socket to non-blocking mode",
694                     errno);
695       return;
696     }
697 #endif
698
699     // Inform the callback about the new connection
700     dispatchSocket(clientSocket, std::move(address));
701
702     // If we aren't accepting any more, break out of the loop
703     if (!accepting_ || callbacks_.empty()) {
704       break;
705     }
706   }
707 }
708
709 void AsyncServerSocket::dispatchSocket(int socket,
710                                         SocketAddress&& address) {
711   uint32_t startingIndex = callbackIndex_;
712
713   // Short circuit if the callback is in the primary EventBase thread
714
715   CallbackInfo *info = nextCallback();
716   if (info->eventBase == nullptr) {
717     info->callback->connectionAccepted(socket, address);
718     return;
719   }
720
721   // Create a message to send over the notification queue
722   QueueMessage msg;
723   msg.type = MessageType::MSG_NEW_CONN;
724   msg.address = std::move(address);
725   msg.fd = socket;
726
727   // Loop until we find a free queue to write to
728   while (true) {
729     if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
730       // Success! return.
731       return;
732    }
733
734     // We couldn't add to queue.  Fall through to below
735
736     ++numDroppedConnections_;
737     if (acceptRateAdjustSpeed_ > 0) {
738       // aggressively decrease accept rate when in trouble
739       static const double kAcceptRateDecreaseSpeed = 0.1;
740       acceptRate_ *= 1 - kAcceptRateDecreaseSpeed;
741     }
742
743
744     if (callbackIndex_ == startingIndex) {
745       // The notification queue was full
746       // We can't really do anything at this point other than close the socket.
747       //
748       // This should only happen if a user's service is behaving extremely
749       // badly and none of the EventBase threads are looping fast enough to
750       // process the incoming connections.  If the service is overloaded, it
751       // should use pauseAccepting() to temporarily back off accepting new
752       // connections, before they reach the point where their threads can't
753       // even accept new messages.
754       LOG(ERROR) << "failed to dispatch newly accepted socket:"
755                  << " all accept callback queues are full";
756       ::close(socket);
757       return;
758     }
759
760     info = nextCallback();
761   }
762 }
763
764 void AsyncServerSocket::dispatchError(const char *msgstr, int errnoValue) {
765   uint32_t startingIndex = callbackIndex_;
766   CallbackInfo *info = nextCallback();
767
768   // Create a message to send over the notification queue
769   QueueMessage msg;
770   msg.type = MessageType::MSG_ERROR;
771   msg.err = errnoValue;
772   msg.msg = std::move(msgstr);
773
774   while (true) {
775     // Short circuit if the callback is in the primary EventBase thread
776     if (info->eventBase == nullptr) {
777       std::runtime_error ex(
778         std::string(msgstr) +  folly::to<std::string>(errnoValue));
779       info->callback->acceptError(ex);
780       return;
781     }
782
783     if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
784       return;
785     }
786     // Fall through and try another callback
787
788     if (callbackIndex_ == startingIndex) {
789       // The notification queues for all of the callbacks were full.
790       // We can't really do anything at this point.
791       LOG(ERROR) << "failed to dispatch accept error: all accept callback "
792         "queues are full: error msg:  " <<
793         msg.msg.c_str() << errnoValue;
794       return;
795     }
796     info = nextCallback();
797   }
798 }
799
800 void AsyncServerSocket::enterBackoff() {
801   // If this is the first time we have entered the backoff state,
802   // allocate backoffTimeout_.
803   if (backoffTimeout_ == nullptr) {
804     try {
805       backoffTimeout_ = new BackoffTimeout(this);
806     } catch (const std::bad_alloc& ex) {
807       // Man, we couldn't even allocate the timer to re-enable accepts.
808       // We must be in pretty bad shape.  Don't pause accepting for now,
809       // since we won't be able to re-enable ourselves later.
810       LOG(ERROR) << "failed to allocate AsyncServerSocket backoff"
811                  << " timer; unable to temporarly pause accepting";
812       return;
813     }
814   }
815
816   // For now, we simply pause accepting for 1 second.
817   //
818   // We could add some smarter backoff calculation here in the future.  (e.g.,
819   // start sleeping for longer if we keep hitting the backoff frequently.)
820   // Typically the user needs to figure out why the server is overloaded and
821   // fix it in some other way, though.  The backoff timer is just a simple
822   // mechanism to try and give the connection processing code a little bit of
823   // breathing room to catch up, and to avoid just spinning and failing to
824   // accept over and over again.
825   const uint32_t timeoutMS = 1000;
826   if (!backoffTimeout_->scheduleTimeout(timeoutMS)) {
827     LOG(ERROR) << "failed to schedule AsyncServerSocket backoff timer;"
828                << "unable to temporarly pause accepting";
829     return;
830   }
831
832   // The backoff timer is scheduled to re-enable accepts.
833   // Go ahead and disable accepts for now.  We leave accepting_ set to true,
834   // since that tracks the desired state requested by the user.
835   for (auto& handler : sockets_) {
836     handler.unregisterHandler();
837   }
838 }
839
840 void AsyncServerSocket::backoffTimeoutExpired() {
841   // accepting_ should still be true.
842   // If pauseAccepting() was called while in the backoff state it will cancel
843   // the backoff timeout.
844   assert(accepting_);
845   // We can't be detached from the EventBase without being paused
846   assert(eventBase_ != nullptr && eventBase_->isInEventBaseThread());
847
848   // If all of the callbacks were removed, we shouldn't re-enable accepts
849   if (callbacks_.empty()) {
850     return;
851   }
852
853   // Register the handler.
854   for (auto& handler : sockets_) {
855     if (!handler.registerHandler(
856           EventHandler::READ | EventHandler::PERSIST)) {
857       // We're hosed.  We could just re-schedule backoffTimeout_ to
858       // re-try again after a little bit.  However, we don't want to
859       // loop retrying forever if we can't re-enable accepts.  Just
860       // abort the entire program in this state; things are really bad
861       // and restarting the entire server is probably the best remedy.
862       LOG(ERROR)
863         << "failed to re-enable AsyncServerSocket accepts after backoff; "
864         << "crashing now";
865       abort();
866     }
867   }
868 }
869
870
871
872 } // folly