2 * Copyright 2017 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(
93 QueueMessage&& msg) noexcept {
95 case MessageType::MSG_NEW_CONN:
97 if (connectionEventCallback_) {
98 connectionEventCallback_->onConnectionDequeuedByAcceptorCallback(
101 callback_->connectionAccepted(msg.fd, msg.address);
104 case MessageType::MSG_ERROR:
106 std::runtime_error ex(msg.msg);
107 callback_->acceptError(ex);
112 LOG(ERROR) << "invalid accept notification message type "
114 std::runtime_error ex(
115 "received invalid accept notification message type");
116 callback_->acceptError(ex);
122 * AsyncServerSocket::BackoffTimeout
124 class AsyncServerSocket::BackoffTimeout : public AsyncTimeout {
126 // Disallow copy, move, and default constructors.
127 BackoffTimeout(BackoffTimeout&&) = delete;
128 explicit BackoffTimeout(AsyncServerSocket* socket)
129 : AsyncTimeout(socket->getEventBase()), socket_(socket) {}
131 void timeoutExpired() noexcept override { socket_->backoffTimeoutExpired(); }
134 AsyncServerSocket* socket_;
138 * AsyncServerSocket methods
141 AsyncServerSocket::AsyncServerSocket(EventBase* eventBase)
142 : eventBase_(eventBase),
144 maxAcceptAtOnce_(kDefaultMaxAcceptAtOnce),
145 maxNumMsgsInQueue_(kDefaultMaxMessagesInQueue),
146 acceptRateAdjustSpeed_(0),
148 lastAccepTimestamp_(std::chrono::steady_clock::now()),
149 numDroppedConnections_(0),
151 backoffTimeout_(nullptr),
153 keepAliveEnabled_(true),
155 shutdownSocketSet_(nullptr) {
158 void AsyncServerSocket::setShutdownSocketSet(ShutdownSocketSet* newSS) {
159 if (shutdownSocketSet_ == newSS) {
162 if (shutdownSocketSet_) {
163 for (auto& h : sockets_) {
164 shutdownSocketSet_->remove(h.socket_);
167 shutdownSocketSet_ = newSS;
168 if (shutdownSocketSet_) {
169 for (auto& h : sockets_) {
170 shutdownSocketSet_->add(h.socket_);
175 AsyncServerSocket::~AsyncServerSocket() {
176 assert(callbacks_.empty());
179 int AsyncServerSocket::stopAccepting(int shutdownFlags) {
181 for (auto& handler : sockets_) {
182 VLOG(10) << "AsyncServerSocket::stopAccepting " << this <<
185 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
187 // When destroy is called, unregister and close the socket immediately.
190 // Close the sockets in reverse order as they were opened to avoid
191 // the condition where another process concurrently tries to open
192 // the same port, succeed to bind the first socket but fails on the
193 // second because it hasn't been closed yet.
194 for (; !sockets_.empty(); sockets_.pop_back()) {
195 auto& handler = sockets_.back();
196 handler.unregisterHandler();
197 if (shutdownSocketSet_) {
198 shutdownSocketSet_->close(handler.socket_);
199 } else if (shutdownFlags >= 0) {
200 result = shutdownNoInt(handler.socket_, shutdownFlags);
201 pendingCloseSockets_.push_back(handler.socket_);
203 closeNoInt(handler.socket_);
207 // Destroy the backoff timout. This will cancel it if it is running.
208 delete backoffTimeout_;
209 backoffTimeout_ = nullptr;
211 // Close all of the callback queues to notify them that they are being
212 // destroyed. No one should access the AsyncServerSocket any more once
213 // destroy() is called. However, clear out callbacks_ before invoking the
214 // accept callbacks just in case. This will potentially help us detect the
215 // bug if one of the callbacks calls addAcceptCallback() or
216 // removeAcceptCallback().
217 std::vector<CallbackInfo> callbacksCopy;
218 callbacks_.swap(callbacksCopy);
219 for (std::vector<CallbackInfo>::iterator it = callbacksCopy.begin();
220 it != callbacksCopy.end();
222 // consumer may not be set if we are running in primary event base
224 DCHECK(it->eventBase);
225 it->consumer->stop(it->eventBase, it->callback);
227 DCHECK(it->callback);
228 it->callback->acceptStopped();
235 void AsyncServerSocket::destroy() {
237 for (auto s : pendingCloseSockets_) {
240 // Then call DelayedDestruction::destroy() to take care of
241 // whether or not we need immediate or delayed destruction
242 DelayedDestruction::destroy();
245 void AsyncServerSocket::attachEventBase(EventBase *eventBase) {
246 assert(eventBase_ == nullptr);
247 assert(eventBase->isInEventBaseThread());
249 eventBase_ = eventBase;
250 for (auto& handler : sockets_) {
251 handler.attachEventBase(eventBase);
255 void AsyncServerSocket::detachEventBase() {
256 assert(eventBase_ != nullptr);
257 assert(eventBase_->isInEventBaseThread());
260 eventBase_ = nullptr;
261 for (auto& handler : sockets_) {
262 handler.detachEventBase();
266 void AsyncServerSocket::useExistingSockets(const std::vector<int>& fds) {
267 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
269 if (sockets_.size() > 0) {
270 throw std::invalid_argument(
271 "cannot call useExistingSocket() on a "
272 "AsyncServerSocket that already has a socket");
276 // Set addressFamily_ from this socket.
277 // Note that the socket may not have been bound yet, but
278 // setFromLocalAddress() will still work and get the correct address family.
279 // We will update addressFamily_ again anyway if bind() is called later.
280 SocketAddress address;
281 address.setFromLocalAddress(fd);
284 if (noTransparentTls_) {
285 // Ignore return value, errors are ok
286 setsockopt(fd, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
290 setupSocket(fd, address.getFamily());
291 sockets_.emplace_back(eventBase_, fd, this, address.getFamily());
292 sockets_.back().changeHandlerFD(fd);
296 void AsyncServerSocket::useExistingSocket(int fd) {
297 useExistingSockets({fd});
300 void AsyncServerSocket::bindSocket(
302 const SocketAddress& address,
303 bool isExistingSocket) {
304 sockaddr_storage addrStorage;
305 address.getAddress(&addrStorage);
306 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
308 if (fsp::bind(fd, saddr, address.getActualSize()) != 0) {
309 if (!isExistingSocket) {
312 folly::throwSystemError(errno,
313 "failed to bind to async server socket: " +
318 if (noTransparentTls_) {
319 // Ignore return value, errors are ok
320 setsockopt(fd, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
324 // If we just created this socket, update the EventHandler and set socket_
325 if (!isExistingSocket) {
326 sockets_.emplace_back(eventBase_, fd, this, address.getFamily());
330 void AsyncServerSocket::bind(const SocketAddress& address) {
331 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
333 // useExistingSocket() may have been called to initialize socket_ already.
334 // However, in the normal case we need to create a new socket now.
335 // Don't set socket_ yet, so that socket_ will remain uninitialized if an
338 if (sockets_.size() == 0) {
339 fd = createSocket(address.getFamily());
340 } else if (sockets_.size() == 1) {
341 if (address.getFamily() != sockets_[0].addressFamily_) {
342 throw std::invalid_argument(
343 "Attempted to bind address to socket with "
344 "different address family");
346 fd = sockets_[0].socket_;
348 throw std::invalid_argument(
349 "Attempted to bind to multiple fds");
352 bindSocket(fd, address, !sockets_.empty());
355 void AsyncServerSocket::bind(
356 const std::vector<IPAddress>& ipAddresses,
358 if (ipAddresses.empty()) {
359 throw std::invalid_argument("No ip addresses were provided");
361 if (!sockets_.empty()) {
362 throw std::invalid_argument("Cannot call bind on a AsyncServerSocket "
363 "that already has a socket.");
366 for (const IPAddress& ipAddress : ipAddresses) {
367 SocketAddress address(ipAddress.toFullyQualified(), port);
368 int fd = createSocket(address.getFamily());
370 bindSocket(fd, address, false);
372 if (sockets_.size() == 0) {
373 throw std::runtime_error(
374 "did not bind any async server socket for port and addresses");
378 void AsyncServerSocket::bind(uint16_t port) {
379 struct addrinfo hints, *res0;
380 char sport[sizeof("65536")];
382 memset(&hints, 0, sizeof(hints));
383 hints.ai_family = AF_UNSPEC;
384 hints.ai_socktype = SOCK_STREAM;
385 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
386 snprintf(sport, sizeof(sport), "%u", port);
388 // On Windows the value we need to pass to bind to all available
389 // addresses is an empty string. Everywhere else, it's nullptr.
390 constexpr const char* kWildcardNode = kIsWindows ? "" : nullptr;
391 if (getaddrinfo(kWildcardNode, sport, &hints, &res0)) {
392 throw std::invalid_argument(
393 "Attempted to bind address to socket with "
397 SCOPE_EXIT { freeaddrinfo(res0); };
399 auto setupAddress = [&] (struct addrinfo* res) {
400 int s = fsp::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
401 // IPv6/IPv4 may not be supported by the kernel
402 if (s < 0 && errno == EAFNOSUPPORT) {
408 setupSocket(s, res->ai_family);
414 if (res->ai_family == AF_INET6) {
416 CHECK(0 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
417 &v6only, sizeof(v6only)));
420 // Bind to the socket
421 if (fsp::bind(s, res->ai_addr, socklen_t(res->ai_addrlen)) != 0) {
422 folly::throwSystemError(
424 "failed to bind to async server socket for port ",
425 SocketAddress::getPortFrom(res->ai_addr),
427 SocketAddress::getFamilyNameFrom(res->ai_addr, "<unknown>"));
431 if (noTransparentTls_) {
432 // Ignore return value, errors are ok
433 setsockopt(s, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0);
437 SocketAddress address;
438 address.setFromLocalAddress(s);
440 sockets_.emplace_back(eventBase_, s, this, address.getFamily());
443 const int kNumTries = 25;
444 for (int tries = 1; true; tries++) {
445 // Prefer AF_INET6 addresses. RFC 3484 mandates that getaddrinfo
446 // should return IPv6 first and then IPv4 addresses, but glibc's
447 // getaddrinfo(nullptr) with AI_PASSIVE returns:
448 // - 0.0.0.0 (IPv4-only)
449 // - :: (IPv6+IPv4) in this order
450 // See: https://sourceware.org/bugzilla/show_bug.cgi?id=9981
451 for (struct addrinfo* res = res0; res; res = res->ai_next) {
452 if (res->ai_family == AF_INET6) {
457 // If port == 0, then we should try to bind to the same port on ipv4 and
458 // ipv6. So if we did bind to ipv6, figure out that port and use it.
459 if (sockets_.size() == 1 && port == 0) {
460 SocketAddress address;
461 address.setFromLocalAddress(sockets_.back().socket_);
462 snprintf(sport, sizeof(sport), "%u", address.getPort());
464 CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0));
468 for (struct addrinfo* res = res0; res; res = res->ai_next) {
469 if (res->ai_family != AF_INET6) {
473 } catch (const std::system_error&) {
474 // If we can't bind to the same port on ipv4 as ipv6 when using
475 // port=0 then we will retry again before giving up after
476 // kNumTries attempts. We do this by closing the sockets that
477 // were opened, then restarting from scratch.
478 if (port == 0 && !sockets_.empty() && tries != kNumTries) {
479 for (const auto& socket : sockets_) {
480 if (socket.socket_ <= 0) {
482 } else if (shutdownSocketSet_) {
483 shutdownSocketSet_->close(socket.socket_);
485 closeNoInt(socket.socket_);
489 snprintf(sport, sizeof(sport), "%u", port);
491 CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0));
501 if (sockets_.size() == 0) {
502 throw std::runtime_error(
503 "did not bind any async server socket for port");
507 void AsyncServerSocket::listen(int backlog) {
508 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
511 for (auto& handler : sockets_) {
512 if (fsp::listen(handler.socket_, backlog) == -1) {
513 folly::throwSystemError(errno,
514 "failed to listen on async server socket");
519 void AsyncServerSocket::getAddress(SocketAddress* addressReturn) const {
520 CHECK(sockets_.size() >= 1);
521 VLOG_IF(2, sockets_.size() > 1)
522 << "Warning: getAddress() called and multiple addresses available ("
523 << sockets_.size() << "). Returning only the first one.";
525 addressReturn->setFromLocalAddress(sockets_[0].socket_);
528 std::vector<SocketAddress> AsyncServerSocket::getAddresses()
530 CHECK(sockets_.size() >= 1);
531 auto tsaVec = std::vector<SocketAddress>(sockets_.size());
532 auto tsaIter = tsaVec.begin();
533 for (const auto& socket : sockets_) {
534 (tsaIter++)->setFromLocalAddress(socket.socket_);
539 void AsyncServerSocket::addAcceptCallback(AcceptCallback *callback,
540 EventBase *eventBase,
541 uint32_t maxAtOnce) {
542 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
544 // If this is the first accept callback and we are supposed to be accepting,
545 // start accepting once the callback is installed.
546 bool runStartAccepting = accepting_ && callbacks_.empty();
548 callbacks_.emplace_back(callback, eventBase);
551 // If this is the first accept callback and we are supposed to be accepting,
553 if (runStartAccepting) {
559 // Run in AsyncServerSocket's eventbase; notify that we are
560 // starting to accept connections
561 callback->acceptStarted();
565 // Start the remote acceptor.
567 // It would be nice if we could avoid starting the remote acceptor if
568 // eventBase == eventBase_. However, that would cause issues if
569 // detachEventBase() and attachEventBase() were ever used to change the
570 // primary EventBase for the server socket. Therefore we require the caller
571 // to specify a nullptr EventBase if they want to ensure that the callback is
572 // always invoked in the primary EventBase, and to be able to invoke that
573 // callback more efficiently without having to use a notification queue.
574 RemoteAcceptor* acceptor = nullptr;
576 acceptor = new RemoteAcceptor(callback, connectionEventCallback_);
577 acceptor->start(eventBase, maxAtOnce, maxNumMsgsInQueue_);
579 callbacks_.pop_back();
583 callbacks_.back().consumer = acceptor;
586 void AsyncServerSocket::removeAcceptCallback(AcceptCallback *callback,
587 EventBase *eventBase) {
588 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
590 // Find the matching AcceptCallback.
591 // We just do a simple linear search; we don't expect removeAcceptCallback()
592 // to be called frequently, and we expect there to only be a small number of
594 std::vector<CallbackInfo>::iterator it = callbacks_.begin();
597 if (it == callbacks_.end()) {
598 throw std::runtime_error("AsyncServerSocket::removeAcceptCallback(): "
599 "accept callback not found");
601 if (it->callback == callback &&
602 (it->eventBase == eventBase || eventBase == nullptr)) {
609 // Remove this callback from callbacks_.
611 // Do this before invoking the acceptStopped() callback, in case
612 // acceptStopped() invokes one of our methods that examines callbacks_.
614 // Save a copy of the CallbackInfo first.
615 CallbackInfo info(*it);
616 callbacks_.erase(it);
617 if (n < callbackIndex_) {
618 // We removed an element before callbackIndex_. Move callbackIndex_ back
619 // one step, since things after n have been shifted back by 1.
622 // We removed something at or after callbackIndex_.
623 // If we removed the last element and callbackIndex_ was pointing at it,
624 // we need to reset callbackIndex_ to 0.
625 if (callbackIndex_ >= callbacks_.size()) {
631 // consumer could be nullptr is we run callbacks in primary event
633 DCHECK(info.eventBase);
634 info.consumer->stop(info.eventBase, info.callback);
636 // callback invoked in the primary event base, just call directly
637 DCHECK(info.callback);
638 callback->acceptStopped();
641 // If we are supposed to be accepting but the last accept callback
642 // was removed, unregister for events until a callback is added.
643 if (accepting_ && callbacks_.empty()) {
644 for (auto& handler : sockets_) {
645 handler.unregisterHandler();
650 void AsyncServerSocket::startAccepting() {
651 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
654 if (callbacks_.empty()) {
655 // We can't actually begin accepting if no callbacks are defined.
656 // Wait until a callback is added to start accepting.
660 for (auto& handler : sockets_) {
661 if (!handler.registerHandler(
662 EventHandler::READ | EventHandler::PERSIST)) {
663 throw std::runtime_error("failed to register for accept events");
668 void AsyncServerSocket::pauseAccepting() {
669 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
671 for (auto& handler : sockets_) {
672 handler. unregisterHandler();
675 // If we were in the accept backoff state, disable the backoff timeout
676 if (backoffTimeout_) {
677 backoffTimeout_->cancelTimeout();
681 int AsyncServerSocket::createSocket(int family) {
682 int fd = fsp::socket(family, SOCK_STREAM, 0);
684 folly::throwSystemError(errno, "error creating async server socket");
688 setupSocket(fd, family);
696 void AsyncServerSocket::setupSocket(int fd, int family) {
697 // Put the socket in non-blocking mode
698 if (fcntl(fd, F_SETFL, O_NONBLOCK) != 0) {
699 folly::throwSystemError(errno,
700 "failed to put socket in non-blocking mode");
703 // Set reuseaddr to avoid 2MSL delay on server restart
705 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) {
706 // This isn't a fatal error; just log an error message and continue
707 LOG(ERROR) << "failed to set SO_REUSEADDR on async server socket " << errno;
710 // Set reuseport to support multiple accept threads
712 if (reusePortEnabled_ &&
713 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(int)) != 0) {
714 LOG(ERROR) << "failed to set SO_REUSEPORT on async server socket "
717 folly::throwSystemError(errno, "failed to bind to the async server socket");
719 SocketAddress address;
720 address.setFromLocalAddress(fd);
721 folly::throwSystemError(errno,
722 "failed to bind to async server socket: " +
727 // Set keepalive as desired
728 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
729 (keepAliveEnabled_) ? &one : &zero, sizeof(int)) != 0) {
730 LOG(ERROR) << "failed to set SO_KEEPALIVE on async server socket: " <<
734 // Setup FD_CLOEXEC flag
736 (-1 == folly::setCloseOnExec(fd, closeOnExec_))) {
737 LOG(ERROR) << "failed to set FD_CLOEXEC on async server socket: " <<
741 // Set TCP nodelay if available, MAC OS X Hack
742 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
744 if (family != AF_UNIX) {
745 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) != 0) {
746 // This isn't a fatal error; just log an error message and continue
747 LOG(ERROR) << "failed to set TCP_NODELAY on async server socket: " <<
754 if (tfo_ && detail::tfo_enable(fd, tfoMaxQueueSize_) != 0) {
755 // This isn't a fatal error; just log an error message and continue
756 LOG(WARNING) << "failed to set TCP_FASTOPEN on async server socket: "
757 << folly::errnoStr(errno);
761 if (shutdownSocketSet_) {
762 shutdownSocketSet_->add(fd);
766 void AsyncServerSocket::handlerReady(uint16_t /* events */,
768 sa_family_t addressFamily) noexcept {
769 assert(!callbacks_.empty());
770 DestructorGuard dg(this);
772 // Only accept up to maxAcceptAtOnce_ connections at a time,
773 // to avoid starving other I/O handlers using this EventBase.
774 for (uint32_t n = 0; n < maxAcceptAtOnce_; ++n) {
775 SocketAddress address;
777 sockaddr_storage addrStorage;
778 socklen_t addrLen = sizeof(addrStorage);
779 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
781 // In some cases, accept() doesn't seem to update these correctly.
782 saddr->sa_family = addressFamily;
783 if (addressFamily == AF_UNIX) {
784 addrLen = sizeof(struct sockaddr_un);
787 // Accept a new client socket
789 int clientSocket = accept4(fd, saddr, &addrLen, SOCK_NONBLOCK);
791 int clientSocket = accept(fd, saddr, &addrLen);
794 address.setFromSockaddr(saddr, addrLen);
796 if (clientSocket >= 0 && connectionEventCallback_) {
797 connectionEventCallback_->onConnectionAccepted(clientSocket, address);
800 std::chrono::time_point<std::chrono::steady_clock> nowMs =
801 std::chrono::steady_clock::now();
802 auto timeSinceLastAccept = std::max<int64_t>(
804 nowMs.time_since_epoch().count() -
805 lastAccepTimestamp_.time_since_epoch().count());
806 lastAccepTimestamp_ = nowMs;
807 if (acceptRate_ < 1) {
808 acceptRate_ *= 1 + acceptRateAdjustSpeed_ * timeSinceLastAccept;
809 if (acceptRate_ >= 1) {
811 } else if (rand() > acceptRate_ * RAND_MAX) {
812 ++numDroppedConnections_;
813 if (clientSocket >= 0) {
814 closeNoInt(clientSocket);
815 if (connectionEventCallback_) {
816 connectionEventCallback_->onConnectionDropped(clientSocket,
824 if (clientSocket < 0) {
825 if (errno == EAGAIN) {
826 // No more sockets to accept right now.
827 // Check for this code first, since it's the most common.
829 } else if (errno == EMFILE || errno == ENFILE) {
830 // We're out of file descriptors. Perhaps we're accepting connections
831 // too quickly. Pause accepting briefly to back off and give the server
832 // a chance to recover.
833 LOG(ERROR) << "accept failed: out of file descriptors; entering accept "
837 // Dispatch the error message
838 dispatchError("accept() failed", errno);
840 dispatchError("accept() failed", errno);
842 if (connectionEventCallback_) {
843 connectionEventCallback_->onConnectionAcceptError(errno);
848 #ifndef SOCK_NONBLOCK
849 // Explicitly set the new connection to non-blocking mode
850 if (fcntl(clientSocket, F_SETFL, O_NONBLOCK) != 0) {
851 closeNoInt(clientSocket);
852 dispatchError("failed to set accepted socket to non-blocking mode",
854 if (connectionEventCallback_) {
855 connectionEventCallback_->onConnectionDropped(clientSocket, address);
861 // Inform the callback about the new connection
862 dispatchSocket(clientSocket, std::move(address));
864 // If we aren't accepting any more, break out of the loop
865 if (!accepting_ || callbacks_.empty()) {
871 void AsyncServerSocket::dispatchSocket(int socket,
872 SocketAddress&& address) {
873 uint32_t startingIndex = callbackIndex_;
875 // Short circuit if the callback is in the primary EventBase thread
877 CallbackInfo *info = nextCallback();
878 if (info->eventBase == nullptr) {
879 info->callback->connectionAccepted(socket, address);
883 const SocketAddress addr(address);
884 // Create a message to send over the notification queue
886 msg.type = MessageType::MSG_NEW_CONN;
887 msg.address = std::move(address);
890 // Loop until we find a free queue to write to
892 if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
893 if (connectionEventCallback_) {
894 connectionEventCallback_->onConnectionEnqueuedForAcceptorCallback(
902 // We couldn't add to queue. Fall through to below
904 ++numDroppedConnections_;
905 if (acceptRateAdjustSpeed_ > 0) {
906 // aggressively decrease accept rate when in trouble
907 static const double kAcceptRateDecreaseSpeed = 0.1;
908 acceptRate_ *= 1 - kAcceptRateDecreaseSpeed;
912 if (callbackIndex_ == startingIndex) {
913 // The notification queue was full
914 // We can't really do anything at this point other than close the socket.
916 // This should only happen if a user's service is behaving extremely
917 // badly and none of the EventBase threads are looping fast enough to
918 // process the incoming connections. If the service is overloaded, it
919 // should use pauseAccepting() to temporarily back off accepting new
920 // connections, before they reach the point where their threads can't
921 // even accept new messages.
922 LOG(ERROR) << "failed to dispatch newly accepted socket:"
923 << " all accept callback queues are full";
925 if (connectionEventCallback_) {
926 connectionEventCallback_->onConnectionDropped(socket, addr);
931 info = nextCallback();
935 void AsyncServerSocket::dispatchError(const char *msgstr, int errnoValue) {
936 uint32_t startingIndex = callbackIndex_;
937 CallbackInfo *info = nextCallback();
939 // Create a message to send over the notification queue
941 msg.type = MessageType::MSG_ERROR;
942 msg.err = errnoValue;
943 msg.msg = std::move(msgstr);
946 // Short circuit if the callback is in the primary EventBase thread
947 if (info->eventBase == nullptr) {
948 std::runtime_error ex(
949 std::string(msgstr) + folly::to<std::string>(errnoValue));
950 info->callback->acceptError(ex);
954 if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
957 // Fall through and try another callback
959 if (callbackIndex_ == startingIndex) {
960 // The notification queues for all of the callbacks were full.
961 // We can't really do anything at this point.
962 LOG(ERROR) << "failed to dispatch accept error: all accept callback "
963 "queues are full: error msg: " <<
964 msg.msg.c_str() << errnoValue;
967 info = nextCallback();
971 void AsyncServerSocket::enterBackoff() {
972 // If this is the first time we have entered the backoff state,
973 // allocate backoffTimeout_.
974 if (backoffTimeout_ == nullptr) {
976 backoffTimeout_ = new BackoffTimeout(this);
977 } catch (const std::bad_alloc&) {
978 // Man, we couldn't even allocate the timer to re-enable accepts.
979 // We must be in pretty bad shape. Don't pause accepting for now,
980 // since we won't be able to re-enable ourselves later.
981 LOG(ERROR) << "failed to allocate AsyncServerSocket backoff"
982 << " timer; unable to temporarly pause accepting";
983 if (connectionEventCallback_) {
984 connectionEventCallback_->onBackoffError();
990 // For now, we simply pause accepting for 1 second.
992 // We could add some smarter backoff calculation here in the future. (e.g.,
993 // start sleeping for longer if we keep hitting the backoff frequently.)
994 // Typically the user needs to figure out why the server is overloaded and
995 // fix it in some other way, though. The backoff timer is just a simple
996 // mechanism to try and give the connection processing code a little bit of
997 // breathing room to catch up, and to avoid just spinning and failing to
998 // accept over and over again.
999 const uint32_t timeoutMS = 1000;
1000 if (!backoffTimeout_->scheduleTimeout(timeoutMS)) {
1001 LOG(ERROR) << "failed to schedule AsyncServerSocket backoff timer;"
1002 << "unable to temporarly pause accepting";
1003 if (connectionEventCallback_) {
1004 connectionEventCallback_->onBackoffError();
1009 // The backoff timer is scheduled to re-enable accepts.
1010 // Go ahead and disable accepts for now. We leave accepting_ set to true,
1011 // since that tracks the desired state requested by the user.
1012 for (auto& handler : sockets_) {
1013 handler.unregisterHandler();
1015 if (connectionEventCallback_) {
1016 connectionEventCallback_->onBackoffStarted();
1020 void AsyncServerSocket::backoffTimeoutExpired() {
1021 // accepting_ should still be true.
1022 // If pauseAccepting() was called while in the backoff state it will cancel
1023 // the backoff timeout.
1025 // We can't be detached from the EventBase without being paused
1026 assert(eventBase_ != nullptr && eventBase_->isInEventBaseThread());
1028 // If all of the callbacks were removed, we shouldn't re-enable accepts
1029 if (callbacks_.empty()) {
1030 if (connectionEventCallback_) {
1031 connectionEventCallback_->onBackoffEnded();
1036 // Register the handler.
1037 for (auto& handler : sockets_) {
1038 if (!handler.registerHandler(
1039 EventHandler::READ | EventHandler::PERSIST)) {
1040 // We're hosed. We could just re-schedule backoffTimeout_ to
1041 // re-try again after a little bit. However, we don't want to
1042 // loop retrying forever if we can't re-enable accepts. Just
1043 // abort the entire program in this state; things are really bad
1044 // and restarting the entire server is probably the best remedy.
1046 << "failed to re-enable AsyncServerSocket accepts after backoff; "
1051 if (connectionEventCallback_) {
1052 connectionEventCallback_->onBackoffEnded();