2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef __STDC_FORMAT_MACROS
18 #define __STDC_FORMAT_MACROS
21 #include <folly/io/async/AsyncServerSocket.h>
23 #include <folly/FileUtil.h>
24 #include <folly/Portability.h>
25 #include <folly/SocketAddress.h>
26 #include <folly/String.h>
27 #include <folly/detail/SocketFastOpen.h>
28 #include <folly/io/async/EventBase.h>
29 #include <folly/io/async/NotificationQueue.h>
30 #include <folly/portability/Fcntl.h>
31 #include <folly/portability/Sockets.h>
32 #include <folly/portability/Unistd.h>
36 #include <sys/types.h>
38 namespace fsp = folly::portability::sockets;
42 const uint32_t AsyncServerSocket::kDefaultMaxAcceptAtOnce;
43 const uint32_t AsyncServerSocket::kDefaultCallbackAcceptAtOnce;
44 const uint32_t AsyncServerSocket::kDefaultMaxMessagesInQueue;
46 int setCloseOnExec(int fd, int value) {
47 // Read the current flags
48 int old_flags = fcntl(fd, F_GETFD, 0);
50 // If reading the flags failed, return error indication now
54 // Set just the flag we want to set
57 new_flags = old_flags | FD_CLOEXEC;
59 new_flags = old_flags & ~FD_CLOEXEC;
61 // Store modified flag word in the descriptor
62 return fcntl(fd, F_SETFD, new_flags);
65 void AsyncServerSocket::RemoteAcceptor::start(
66 EventBase* eventBase, uint32_t maxAtOnce, uint32_t maxInQueue) {
67 setMaxReadAtOnce(maxAtOnce);
68 queue_.setMaxQueueSize(maxInQueue);
70 if (!eventBase->runInEventBaseThread([=](){
71 callback_->acceptStarted();
72 this->startConsuming(eventBase, &queue_);
74 throw std::invalid_argument("unable to start waiting on accept "
75 "notification queue in the specified "
80 void AsyncServerSocket::RemoteAcceptor::stop(
81 EventBase* eventBase, AcceptCallback* callback) {
82 if (!eventBase->runInEventBaseThread([=](){
83 callback->acceptStopped();
86 throw std::invalid_argument("unable to start waiting on accept "
87 "notification queue in the specified "
92 void AsyncServerSocket::RemoteAcceptor::messageAvailable(
96 case MessageType::MSG_NEW_CONN:
98 if (connectionEventCallback_) {
99 connectionEventCallback_->onConnectionDequeuedByAcceptorCallback(
100 msg.fd, msg.address);
102 callback_->connectionAccepted(msg.fd, msg.address);
105 case MessageType::MSG_ERROR:
107 std::runtime_error ex(msg.msg);
108 callback_->acceptError(ex);
113 LOG(ERROR) << "invalid accept notification message type "
115 std::runtime_error ex(
116 "received invalid accept notification message type");
117 callback_->acceptError(ex);
123 * AsyncServerSocket::BackoffTimeout
125 class AsyncServerSocket::BackoffTimeout : public AsyncTimeout {
127 // Disallow copy, move, and default constructors.
128 BackoffTimeout(BackoffTimeout&&) = delete;
129 explicit BackoffTimeout(AsyncServerSocket* socket)
130 : AsyncTimeout(socket->getEventBase()), socket_(socket) {}
132 void timeoutExpired() noexcept override { socket_->backoffTimeoutExpired(); }
135 AsyncServerSocket* socket_;
139 * AsyncServerSocket methods
142 AsyncServerSocket::AsyncServerSocket(EventBase* eventBase)
143 : eventBase_(eventBase),
145 maxAcceptAtOnce_(kDefaultMaxAcceptAtOnce),
146 maxNumMsgsInQueue_(kDefaultMaxMessagesInQueue),
147 acceptRateAdjustSpeed_(0),
149 lastAccepTimestamp_(std::chrono::steady_clock::now()),
150 numDroppedConnections_(0),
152 backoffTimeout_(nullptr),
154 keepAliveEnabled_(true),
156 shutdownSocketSet_(nullptr) {
159 void AsyncServerSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
160 if (shutdownSocketSet_ == newSS) {
163 if (shutdownSocketSet_) {
164 for (auto& h : sockets_) {
165 shutdownSocketSet_->remove(h.socket_);
168 shutdownSocketSet_ = newSS;
169 if (shutdownSocketSet_) {
170 for (auto& h : sockets_) {
171 shutdownSocketSet_->add(h.socket_);
176 AsyncServerSocket::~AsyncServerSocket() {
177 assert(callbacks_.empty());
180 int AsyncServerSocket::stopAccepting(int shutdownFlags) {
182 for (auto& handler : sockets_) {
183 VLOG(10) << "AsyncServerSocket::stopAccepting " << this <<
186 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
188 // When destroy is called, unregister and close the socket immediately.
191 // Close the sockets in reverse order as they were opened to avoid
192 // the condition where another process concurrently tries to open
193 // the same port, succeed to bind the first socket but fails on the
194 // second because it hasn't been closed yet.
195 for (; !sockets_.empty(); sockets_.pop_back()) {
196 auto& handler = sockets_.back();
197 handler.unregisterHandler();
198 if (shutdownSocketSet_) {
199 shutdownSocketSet_->close(handler.socket_);
200 } else if (shutdownFlags >= 0) {
201 result = shutdownNoInt(handler.socket_, shutdownFlags);
202 pendingCloseSockets_.push_back(handler.socket_);
204 closeNoInt(handler.socket_);
208 // Destroy the backoff timout. This will cancel it if it is running.
209 delete backoffTimeout_;
210 backoffTimeout_ = nullptr;
212 // Close all of the callback queues to notify them that they are being
213 // destroyed. No one should access the AsyncServerSocket any more once
214 // destroy() is called. However, clear out callbacks_ before invoking the
215 // accept callbacks just in case. This will potentially help us detect the
216 // bug if one of the callbacks calls addAcceptCallback() or
217 // removeAcceptCallback().
218 std::vector<CallbackInfo> callbacksCopy;
219 callbacks_.swap(callbacksCopy);
220 for (std::vector<CallbackInfo>::iterator it = callbacksCopy.begin();
221 it != callbacksCopy.end();
223 // consumer may not be set if we are running in primary event base
225 DCHECK(it->eventBase);
226 it->consumer->stop(it->eventBase, it->callback);
228 DCHECK(it->callback);
229 it->callback->acceptStopped();
236 void AsyncServerSocket::destroy() {
238 for (auto s : pendingCloseSockets_) {
241 // Then call DelayedDestruction::destroy() to take care of
242 // whether or not we need immediate or delayed destruction
243 DelayedDestruction::destroy();
246 void AsyncServerSocket::attachEventBase(EventBase *eventBase) {
247 assert(eventBase_ == nullptr);
248 assert(eventBase->isInEventBaseThread());
250 eventBase_ = eventBase;
251 for (auto& handler : sockets_) {
252 handler.attachEventBase(eventBase);
256 void AsyncServerSocket::detachEventBase() {
257 assert(eventBase_ != nullptr);
258 assert(eventBase_->isInEventBaseThread());
261 eventBase_ = nullptr;
262 for (auto& handler : sockets_) {
263 handler.detachEventBase();
267 void AsyncServerSocket::useExistingSockets(const std::vector<int>& fds) {
268 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
270 if (sockets_.size() > 0) {
271 throw std::invalid_argument(
272 "cannot call useExistingSocket() on a "
273 "AsyncServerSocket that already has a socket");
277 // Set addressFamily_ from this socket.
278 // Note that the socket may not have been bound yet, but
279 // setFromLocalAddress() will still work and get the correct address family.
280 // We will update addressFamily_ again anyway if bind() is called later.
281 SocketAddress address;
282 address.setFromLocalAddress(fd);
284 setupSocket(fd, address.getFamily());
285 sockets_.emplace_back(eventBase_, fd, this, address.getFamily());
286 sockets_.back().changeHandlerFD(fd);
290 void AsyncServerSocket::useExistingSocket(int fd) {
291 useExistingSockets({fd});
294 void AsyncServerSocket::bindSocket(
296 const SocketAddress& address,
297 bool isExistingSocket) {
298 sockaddr_storage addrStorage;
299 address.getAddress(&addrStorage);
300 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
301 if (fsp::bind(fd, saddr, address.getActualSize()) != 0) {
302 if (!isExistingSocket) {
305 folly::throwSystemError(errno,
306 "failed to bind to async server socket: " +
310 // If we just created this socket, update the EventHandler and set socket_
311 if (!isExistingSocket) {
312 sockets_.emplace_back(eventBase_, fd, this, address.getFamily());
316 void AsyncServerSocket::bind(const SocketAddress& address) {
317 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
319 // useExistingSocket() may have been called to initialize socket_ already.
320 // However, in the normal case we need to create a new socket now.
321 // Don't set socket_ yet, so that socket_ will remain uninitialized if an
324 if (sockets_.size() == 0) {
325 fd = createSocket(address.getFamily());
326 } else if (sockets_.size() == 1) {
327 if (address.getFamily() != sockets_[0].addressFamily_) {
328 throw std::invalid_argument(
329 "Attempted to bind address to socket with "
330 "different address family");
332 fd = sockets_[0].socket_;
334 throw std::invalid_argument(
335 "Attempted to bind to multiple fds");
338 bindSocket(fd, address, !sockets_.empty());
341 void AsyncServerSocket::bind(
342 const std::vector<IPAddress>& ipAddresses,
344 if (ipAddresses.empty()) {
345 throw std::invalid_argument("No ip addresses were provided");
347 if (!sockets_.empty()) {
348 throw std::invalid_argument("Cannot call bind on a AsyncServerSocket "
349 "that already has a socket.");
352 for (const IPAddress& ipAddress : ipAddresses) {
353 SocketAddress address(ipAddress.toFullyQualified(), port);
354 int fd = createSocket(address.getFamily());
356 bindSocket(fd, address, false);
358 if (sockets_.size() == 0) {
359 throw std::runtime_error(
360 "did not bind any async server socket for port and addresses");
364 void AsyncServerSocket::bind(uint16_t port) {
365 struct addrinfo hints, *res0;
366 char sport[sizeof("65536")];
368 memset(&hints, 0, sizeof(hints));
369 hints.ai_family = AF_UNSPEC;
370 hints.ai_socktype = SOCK_STREAM;
371 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
372 snprintf(sport, sizeof(sport), "%u", port);
374 // On Windows the value we need to pass to bind to all available
375 // addresses is an empty string. Everywhere else, it's nullptr.
376 constexpr const char* kWildcardNode = kIsWindows ? "" : nullptr;
377 if (getaddrinfo(kWildcardNode, sport, &hints, &res0)) {
378 throw std::invalid_argument(
379 "Attempted to bind address to socket with "
383 SCOPE_EXIT { freeaddrinfo(res0); };
385 auto setupAddress = [&] (struct addrinfo* res) {
386 int s = fsp::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
387 // IPv6/IPv4 may not be supported by the kernel
388 if (s < 0 && errno == EAFNOSUPPORT) {
394 setupSocket(s, res->ai_family);
400 if (res->ai_family == AF_INET6) {
402 CHECK(0 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
403 &v6only, sizeof(v6only)));
406 // Bind to the socket
407 if (fsp::bind(s, res->ai_addr, socklen_t(res->ai_addrlen)) != 0) {
408 folly::throwSystemError(
410 "failed to bind to async server socket for port ",
411 SocketAddress::getPortFrom(res->ai_addr),
413 SocketAddress::getFamilyNameFrom(res->ai_addr, "<unknown>"));
416 SocketAddress address;
417 address.setFromLocalAddress(s);
419 sockets_.emplace_back(eventBase_, s, this, address.getFamily());
422 const int kNumTries = 25;
423 for (int tries = 1; true; tries++) {
424 // Prefer AF_INET6 addresses. RFC 3484 mandates that getaddrinfo
425 // should return IPv6 first and then IPv4 addresses, but glibc's
426 // getaddrinfo(nullptr) with AI_PASSIVE returns:
427 // - 0.0.0.0 (IPv4-only)
428 // - :: (IPv6+IPv4) in this order
429 // See: https://sourceware.org/bugzilla/show_bug.cgi?id=9981
430 for (struct addrinfo* res = res0; res; res = res->ai_next) {
431 if (res->ai_family == AF_INET6) {
436 // If port == 0, then we should try to bind to the same port on ipv4 and
437 // ipv6. So if we did bind to ipv6, figure out that port and use it.
438 if (sockets_.size() == 1 && port == 0) {
439 SocketAddress address;
440 address.setFromLocalAddress(sockets_.back().socket_);
441 snprintf(sport, sizeof(sport), "%u", address.getPort());
443 CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0));
447 for (struct addrinfo* res = res0; res; res = res->ai_next) {
448 if (res->ai_family != AF_INET6) {
452 } catch (const std::system_error&) {
453 // If we can't bind to the same port on ipv4 as ipv6 when using
454 // port=0 then we will retry again before giving up after
455 // kNumTries attempts. We do this by closing the sockets that
456 // were opened, then restarting from scratch.
457 if (port == 0 && !sockets_.empty() && tries != kNumTries) {
458 for (const auto& socket : sockets_) {
459 if (socket.socket_ <= 0) {
461 } else if (shutdownSocketSet_) {
462 shutdownSocketSet_->close(socket.socket_);
464 closeNoInt(socket.socket_);
468 snprintf(sport, sizeof(sport), "%u", port);
470 CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0));
480 if (sockets_.size() == 0) {
481 throw std::runtime_error(
482 "did not bind any async server socket for port");
486 void AsyncServerSocket::listen(int backlog) {
487 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
490 for (auto& handler : sockets_) {
491 if (fsp::listen(handler.socket_, backlog) == -1) {
492 folly::throwSystemError(errno,
493 "failed to listen on async server socket");
498 void AsyncServerSocket::getAddress(SocketAddress* addressReturn) const {
499 CHECK(sockets_.size() >= 1);
500 VLOG_IF(2, sockets_.size() > 1)
501 << "Warning: getAddress() called and multiple addresses available ("
502 << sockets_.size() << "). Returning only the first one.";
504 addressReturn->setFromLocalAddress(sockets_[0].socket_);
507 std::vector<SocketAddress> AsyncServerSocket::getAddresses()
509 CHECK(sockets_.size() >= 1);
510 auto tsaVec = std::vector<SocketAddress>(sockets_.size());
511 auto tsaIter = tsaVec.begin();
512 for (const auto& socket : sockets_) {
513 (tsaIter++)->setFromLocalAddress(socket.socket_);
518 void AsyncServerSocket::addAcceptCallback(AcceptCallback *callback,
519 EventBase *eventBase,
520 uint32_t maxAtOnce) {
521 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
523 // If this is the first accept callback and we are supposed to be accepting,
524 // start accepting once the callback is installed.
525 bool runStartAccepting = accepting_ && callbacks_.empty();
527 callbacks_.emplace_back(callback, eventBase);
530 // If this is the first accept callback and we are supposed to be accepting,
532 if (runStartAccepting) {
538 // Run in AsyncServerSocket's eventbase; notify that we are
539 // starting to accept connections
540 callback->acceptStarted();
544 // Start the remote acceptor.
546 // It would be nice if we could avoid starting the remote acceptor if
547 // eventBase == eventBase_. However, that would cause issues if
548 // detachEventBase() and attachEventBase() were ever used to change the
549 // primary EventBase for the server socket. Therefore we require the caller
550 // to specify a nullptr EventBase if they want to ensure that the callback is
551 // always invoked in the primary EventBase, and to be able to invoke that
552 // callback more efficiently without having to use a notification queue.
553 RemoteAcceptor* acceptor = nullptr;
555 acceptor = new RemoteAcceptor(callback, connectionEventCallback_);
556 acceptor->start(eventBase, maxAtOnce, maxNumMsgsInQueue_);
558 callbacks_.pop_back();
562 callbacks_.back().consumer = acceptor;
565 void AsyncServerSocket::removeAcceptCallback(AcceptCallback *callback,
566 EventBase *eventBase) {
567 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
569 // Find the matching AcceptCallback.
570 // We just do a simple linear search; we don't expect removeAcceptCallback()
571 // to be called frequently, and we expect there to only be a small number of
573 std::vector<CallbackInfo>::iterator it = callbacks_.begin();
576 if (it == callbacks_.end()) {
577 throw std::runtime_error("AsyncServerSocket::removeAcceptCallback(): "
578 "accept callback not found");
580 if (it->callback == callback &&
581 (it->eventBase == eventBase || eventBase == nullptr)) {
588 // Remove this callback from callbacks_.
590 // Do this before invoking the acceptStopped() callback, in case
591 // acceptStopped() invokes one of our methods that examines callbacks_.
593 // Save a copy of the CallbackInfo first.
594 CallbackInfo info(*it);
595 callbacks_.erase(it);
596 if (n < callbackIndex_) {
597 // We removed an element before callbackIndex_. Move callbackIndex_ back
598 // one step, since things after n have been shifted back by 1.
601 // We removed something at or after callbackIndex_.
602 // If we removed the last element and callbackIndex_ was pointing at it,
603 // we need to reset callbackIndex_ to 0.
604 if (callbackIndex_ >= callbacks_.size()) {
610 // consumer could be nullptr is we run callbacks in primary event
612 DCHECK(info.eventBase);
613 info.consumer->stop(info.eventBase, info.callback);
615 // callback invoked in the primary event base, just call directly
616 DCHECK(info.callback);
617 callback->acceptStopped();
620 // If we are supposed to be accepting but the last accept callback
621 // was removed, unregister for events until a callback is added.
622 if (accepting_ && callbacks_.empty()) {
623 for (auto& handler : sockets_) {
624 handler.unregisterHandler();
629 void AsyncServerSocket::startAccepting() {
630 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
633 if (callbacks_.empty()) {
634 // We can't actually begin accepting if no callbacks are defined.
635 // Wait until a callback is added to start accepting.
639 for (auto& handler : sockets_) {
640 if (!handler.registerHandler(
641 EventHandler::READ | EventHandler::PERSIST)) {
642 throw std::runtime_error("failed to register for accept events");
647 void AsyncServerSocket::pauseAccepting() {
648 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
650 for (auto& handler : sockets_) {
651 handler. unregisterHandler();
654 // If we were in the accept backoff state, disable the backoff timeout
655 if (backoffTimeout_) {
656 backoffTimeout_->cancelTimeout();
660 int AsyncServerSocket::createSocket(int family) {
661 int fd = fsp::socket(family, SOCK_STREAM, 0);
663 folly::throwSystemError(errno, "error creating async server socket");
667 setupSocket(fd, family);
675 void AsyncServerSocket::setupSocket(int fd, int family) {
676 // Put the socket in non-blocking mode
677 if (fcntl(fd, F_SETFL, O_NONBLOCK) != 0) {
678 folly::throwSystemError(errno,
679 "failed to put socket in non-blocking mode");
682 // Set reuseaddr to avoid 2MSL delay on server restart
684 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) {
685 // This isn't a fatal error; just log an error message and continue
686 LOG(ERROR) << "failed to set SO_REUSEADDR on async server socket " << errno;
689 // Set reuseport to support multiple accept threads
691 if (reusePortEnabled_ &&
692 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(int)) != 0) {
693 LOG(ERROR) << "failed to set SO_REUSEPORT on async server socket "
696 folly::throwSystemError(errno, "failed to bind to the async server socket");
698 SocketAddress address;
699 address.setFromLocalAddress(fd);
700 folly::throwSystemError(errno,
701 "failed to bind to async server socket: " +
706 // Set keepalive as desired
707 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
708 (keepAliveEnabled_) ? &one : &zero, sizeof(int)) != 0) {
709 LOG(ERROR) << "failed to set SO_KEEPALIVE on async server socket: " <<
713 // Setup FD_CLOEXEC flag
715 (-1 == folly::setCloseOnExec(fd, closeOnExec_))) {
716 LOG(ERROR) << "failed to set FD_CLOEXEC on async server socket: " <<
720 // Set TCP nodelay if available, MAC OS X Hack
721 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
723 if (family != AF_UNIX) {
724 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) != 0) {
725 // This isn't a fatal error; just log an error message and continue
726 LOG(ERROR) << "failed to set TCP_NODELAY on async server socket: " <<
733 if (tfo_ && detail::tfo_enable(fd, tfoMaxQueueSize_) != 0) {
734 // This isn't a fatal error; just log an error message and continue
735 LOG(WARNING) << "failed to set TCP_FASTOPEN on async server socket: "
736 << folly::errnoStr(errno);
740 if (shutdownSocketSet_) {
741 shutdownSocketSet_->add(fd);
745 void AsyncServerSocket::handlerReady(uint16_t /* events */,
747 sa_family_t addressFamily) noexcept {
748 assert(!callbacks_.empty());
749 DestructorGuard dg(this);
751 // Only accept up to maxAcceptAtOnce_ connections at a time,
752 // to avoid starving other I/O handlers using this EventBase.
753 for (uint32_t n = 0; n < maxAcceptAtOnce_; ++n) {
754 SocketAddress address;
756 sockaddr_storage addrStorage;
757 socklen_t addrLen = sizeof(addrStorage);
758 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
760 // In some cases, accept() doesn't seem to update these correctly.
761 saddr->sa_family = addressFamily;
762 if (addressFamily == AF_UNIX) {
763 addrLen = sizeof(struct sockaddr_un);
766 // Accept a new client socket
768 int clientSocket = accept4(fd, saddr, &addrLen, SOCK_NONBLOCK);
770 int clientSocket = accept(fd, saddr, &addrLen);
773 address.setFromSockaddr(saddr, addrLen);
775 if (clientSocket >= 0 && connectionEventCallback_) {
776 connectionEventCallback_->onConnectionAccepted(clientSocket, address);
779 std::chrono::time_point<std::chrono::steady_clock> nowMs =
780 std::chrono::steady_clock::now();
781 auto timeSinceLastAccept = std::max<int64_t>(
783 nowMs.time_since_epoch().count() -
784 lastAccepTimestamp_.time_since_epoch().count());
785 lastAccepTimestamp_ = nowMs;
786 if (acceptRate_ < 1) {
787 acceptRate_ *= 1 + acceptRateAdjustSpeed_ * timeSinceLastAccept;
788 if (acceptRate_ >= 1) {
790 } else if (rand() > acceptRate_ * RAND_MAX) {
791 ++numDroppedConnections_;
792 if (clientSocket >= 0) {
793 closeNoInt(clientSocket);
794 if (connectionEventCallback_) {
795 connectionEventCallback_->onConnectionDropped(clientSocket,
803 if (clientSocket < 0) {
804 if (errno == EAGAIN) {
805 // No more sockets to accept right now.
806 // Check for this code first, since it's the most common.
808 } else if (errno == EMFILE || errno == ENFILE) {
809 // We're out of file descriptors. Perhaps we're accepting connections
810 // too quickly. Pause accepting briefly to back off and give the server
811 // a chance to recover.
812 LOG(ERROR) << "accept failed: out of file descriptors; entering accept "
816 // Dispatch the error message
817 dispatchError("accept() failed", errno);
819 dispatchError("accept() failed", errno);
821 if (connectionEventCallback_) {
822 connectionEventCallback_->onConnectionAcceptError(errno);
827 #ifndef SOCK_NONBLOCK
828 // Explicitly set the new connection to non-blocking mode
829 if (fcntl(clientSocket, F_SETFL, O_NONBLOCK) != 0) {
830 closeNoInt(clientSocket);
831 dispatchError("failed to set accepted socket to non-blocking mode",
833 if (connectionEventCallback_) {
834 connectionEventCallback_->onConnectionDropped(clientSocket, address);
840 // Inform the callback about the new connection
841 dispatchSocket(clientSocket, std::move(address));
843 // If we aren't accepting any more, break out of the loop
844 if (!accepting_ || callbacks_.empty()) {
850 void AsyncServerSocket::dispatchSocket(int socket,
851 SocketAddress&& address) {
852 uint32_t startingIndex = callbackIndex_;
854 // Short circuit if the callback is in the primary EventBase thread
856 CallbackInfo *info = nextCallback();
857 if (info->eventBase == nullptr) {
858 info->callback->connectionAccepted(socket, address);
862 const SocketAddress addr(address);
863 // Create a message to send over the notification queue
865 msg.type = MessageType::MSG_NEW_CONN;
866 msg.address = std::move(address);
869 // Loop until we find a free queue to write to
871 if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
872 if (connectionEventCallback_) {
873 connectionEventCallback_->onConnectionEnqueuedForAcceptorCallback(
881 // We couldn't add to queue. Fall through to below
883 ++numDroppedConnections_;
884 if (acceptRateAdjustSpeed_ > 0) {
885 // aggressively decrease accept rate when in trouble
886 static const double kAcceptRateDecreaseSpeed = 0.1;
887 acceptRate_ *= 1 - kAcceptRateDecreaseSpeed;
891 if (callbackIndex_ == startingIndex) {
892 // The notification queue was full
893 // We can't really do anything at this point other than close the socket.
895 // This should only happen if a user's service is behaving extremely
896 // badly and none of the EventBase threads are looping fast enough to
897 // process the incoming connections. If the service is overloaded, it
898 // should use pauseAccepting() to temporarily back off accepting new
899 // connections, before they reach the point where their threads can't
900 // even accept new messages.
901 LOG(ERROR) << "failed to dispatch newly accepted socket:"
902 << " all accept callback queues are full";
904 if (connectionEventCallback_) {
905 connectionEventCallback_->onConnectionDropped(socket, addr);
910 info = nextCallback();
914 void AsyncServerSocket::dispatchError(const char *msgstr, int errnoValue) {
915 uint32_t startingIndex = callbackIndex_;
916 CallbackInfo *info = nextCallback();
918 // Create a message to send over the notification queue
920 msg.type = MessageType::MSG_ERROR;
921 msg.err = errnoValue;
922 msg.msg = std::move(msgstr);
925 // Short circuit if the callback is in the primary EventBase thread
926 if (info->eventBase == nullptr) {
927 std::runtime_error ex(
928 std::string(msgstr) + folly::to<std::string>(errnoValue));
929 info->callback->acceptError(ex);
933 if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
936 // Fall through and try another callback
938 if (callbackIndex_ == startingIndex) {
939 // The notification queues for all of the callbacks were full.
940 // We can't really do anything at this point.
941 LOG(ERROR) << "failed to dispatch accept error: all accept callback "
942 "queues are full: error msg: " <<
943 msg.msg.c_str() << errnoValue;
946 info = nextCallback();
950 void AsyncServerSocket::enterBackoff() {
951 // If this is the first time we have entered the backoff state,
952 // allocate backoffTimeout_.
953 if (backoffTimeout_ == nullptr) {
955 backoffTimeout_ = new BackoffTimeout(this);
956 } catch (const std::bad_alloc&) {
957 // Man, we couldn't even allocate the timer to re-enable accepts.
958 // We must be in pretty bad shape. Don't pause accepting for now,
959 // since we won't be able to re-enable ourselves later.
960 LOG(ERROR) << "failed to allocate AsyncServerSocket backoff"
961 << " timer; unable to temporarly pause accepting";
962 if (connectionEventCallback_) {
963 connectionEventCallback_->onBackoffError();
969 // For now, we simply pause accepting for 1 second.
971 // We could add some smarter backoff calculation here in the future. (e.g.,
972 // start sleeping for longer if we keep hitting the backoff frequently.)
973 // Typically the user needs to figure out why the server is overloaded and
974 // fix it in some other way, though. The backoff timer is just a simple
975 // mechanism to try and give the connection processing code a little bit of
976 // breathing room to catch up, and to avoid just spinning and failing to
977 // accept over and over again.
978 const uint32_t timeoutMS = 1000;
979 if (!backoffTimeout_->scheduleTimeout(timeoutMS)) {
980 LOG(ERROR) << "failed to schedule AsyncServerSocket backoff timer;"
981 << "unable to temporarly pause accepting";
982 if (connectionEventCallback_) {
983 connectionEventCallback_->onBackoffError();
988 // The backoff timer is scheduled to re-enable accepts.
989 // Go ahead and disable accepts for now. We leave accepting_ set to true,
990 // since that tracks the desired state requested by the user.
991 for (auto& handler : sockets_) {
992 handler.unregisterHandler();
994 if (connectionEventCallback_) {
995 connectionEventCallback_->onBackoffStarted();
999 void AsyncServerSocket::backoffTimeoutExpired() {
1000 // accepting_ should still be true.
1001 // If pauseAccepting() was called while in the backoff state it will cancel
1002 // the backoff timeout.
1004 // We can't be detached from the EventBase without being paused
1005 assert(eventBase_ != nullptr && eventBase_->isInEventBaseThread());
1007 // If all of the callbacks were removed, we shouldn't re-enable accepts
1008 if (callbacks_.empty()) {
1009 if (connectionEventCallback_) {
1010 connectionEventCallback_->onBackoffEnded();
1015 // Register the handler.
1016 for (auto& handler : sockets_) {
1017 if (!handler.registerHandler(
1018 EventHandler::READ | EventHandler::PERSIST)) {
1019 // We're hosed. We could just re-schedule backoffTimeout_ to
1020 // re-try again after a little bit. However, we don't want to
1021 // loop retrying forever if we can't re-enable accepts. Just
1022 // abort the entire program in this state; things are really bad
1023 // and restarting the entire server is probably the best remedy.
1025 << "failed to re-enable AsyncServerSocket accepts after backoff; "
1030 if (connectionEventCallback_) {
1031 connectionEventCallback_->onBackoffEnded();