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/SocketAddress.h>
25 #include <folly/String.h>
26 #include <folly/detail/SocketFastOpen.h>
27 #include <folly/io/async/EventBase.h>
28 #include <folly/io/async/NotificationQueue.h>
29 #include <folly/portability/Fcntl.h>
30 #include <folly/portability/Sockets.h>
31 #include <folly/portability/Unistd.h>
35 #include <sys/types.h>
37 namespace fsp = folly::portability::sockets;
41 const uint32_t AsyncServerSocket::kDefaultMaxAcceptAtOnce;
42 const uint32_t AsyncServerSocket::kDefaultCallbackAcceptAtOnce;
43 const uint32_t AsyncServerSocket::kDefaultMaxMessagesInQueue;
45 int setCloseOnExec(int fd, int value) {
46 // Read the current flags
47 int old_flags = fcntl(fd, F_GETFD, 0);
49 // If reading the flags failed, return error indication now
53 // Set just the flag we want to set
56 new_flags = old_flags | FD_CLOEXEC;
58 new_flags = old_flags & ~FD_CLOEXEC;
60 // Store modified flag word in the descriptor
61 return fcntl(fd, F_SETFD, new_flags);
64 void AsyncServerSocket::RemoteAcceptor::start(
65 EventBase* eventBase, uint32_t maxAtOnce, uint32_t maxInQueue) {
66 setMaxReadAtOnce(maxAtOnce);
67 queue_.setMaxQueueSize(maxInQueue);
69 if (!eventBase->runInEventBaseThread([=](){
70 callback_->acceptStarted();
71 this->startConsuming(eventBase, &queue_);
73 throw std::invalid_argument("unable to start waiting on accept "
74 "notification queue in the specified "
79 void AsyncServerSocket::RemoteAcceptor::stop(
80 EventBase* eventBase, AcceptCallback* callback) {
81 if (!eventBase->runInEventBaseThread([=](){
82 callback->acceptStopped();
85 throw std::invalid_argument("unable to start waiting on accept "
86 "notification queue in the specified "
91 void AsyncServerSocket::RemoteAcceptor::messageAvailable(
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);
283 setupSocket(fd, address.getFamily());
284 sockets_.emplace_back(eventBase_, fd, this, address.getFamily());
285 sockets_.back().changeHandlerFD(fd);
289 void AsyncServerSocket::useExistingSocket(int fd) {
290 useExistingSockets({fd});
293 void AsyncServerSocket::bindSocket(
295 const SocketAddress& address,
296 bool isExistingSocket) {
297 sockaddr_storage addrStorage;
298 address.getAddress(&addrStorage);
299 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
300 if (fsp::bind(fd, saddr, address.getActualSize()) != 0) {
301 if (!isExistingSocket) {
304 folly::throwSystemError(errno,
305 "failed to bind to async server socket: " +
309 // If we just created this socket, update the EventHandler and set socket_
310 if (!isExistingSocket) {
311 sockets_.emplace_back(eventBase_, fd, this, address.getFamily());
315 void AsyncServerSocket::bind(const SocketAddress& address) {
316 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
318 // useExistingSocket() may have been called to initialize socket_ already.
319 // However, in the normal case we need to create a new socket now.
320 // Don't set socket_ yet, so that socket_ will remain uninitialized if an
323 if (sockets_.size() == 0) {
324 fd = createSocket(address.getFamily());
325 } else if (sockets_.size() == 1) {
326 if (address.getFamily() != sockets_[0].addressFamily_) {
327 throw std::invalid_argument(
328 "Attempted to bind address to socket with "
329 "different address family");
331 fd = sockets_[0].socket_;
333 throw std::invalid_argument(
334 "Attempted to bind to multiple fds");
337 bindSocket(fd, address, !sockets_.empty());
340 void AsyncServerSocket::bind(
341 const std::vector<IPAddress>& ipAddresses,
343 if (ipAddresses.empty()) {
344 throw std::invalid_argument("No ip addresses were provided");
346 if (!sockets_.empty()) {
347 throw std::invalid_argument("Cannot call bind on a AsyncServerSocket "
348 "that already has a socket.");
351 for (const IPAddress& ipAddress : ipAddresses) {
352 SocketAddress address(ipAddress.toFullyQualified(), port);
353 int fd = createSocket(address.getFamily());
355 bindSocket(fd, address, false);
357 if (sockets_.size() == 0) {
358 throw std::runtime_error(
359 "did not bind any async server socket for port and addresses");
363 void AsyncServerSocket::bind(uint16_t port) {
364 struct addrinfo hints, *res0;
365 char sport[sizeof("65536")];
367 memset(&hints, 0, sizeof(hints));
368 hints.ai_family = AF_UNSPEC;
369 hints.ai_socktype = SOCK_STREAM;
370 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
371 snprintf(sport, sizeof(sport), "%u", port);
373 if (getaddrinfo(nullptr, sport, &hints, &res0)) {
374 throw std::invalid_argument(
375 "Attempted to bind address to socket with "
379 SCOPE_EXIT { freeaddrinfo(res0); };
381 auto setupAddress = [&] (struct addrinfo* res) {
382 int s = fsp::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
383 // IPv6/IPv4 may not be supported by the kernel
384 if (s < 0 && errno == EAFNOSUPPORT) {
390 setupSocket(s, res->ai_family);
396 if (res->ai_family == AF_INET6) {
398 CHECK(0 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
399 &v6only, sizeof(v6only)));
402 // Bind to the socket
403 if (fsp::bind(s, res->ai_addr, res->ai_addrlen) != 0) {
404 folly::throwSystemError(
406 "failed to bind to async server socket for port ",
407 SocketAddress::getPortFrom(res->ai_addr),
409 SocketAddress::getFamilyNameFrom(res->ai_addr, "<unknown>"));
412 SocketAddress address;
413 address.setFromLocalAddress(s);
415 sockets_.emplace_back(eventBase_, s, this, address.getFamily());
418 const int kNumTries = 25;
419 for (int tries = 1; true; tries++) {
420 // Prefer AF_INET6 addresses. RFC 3484 mandates that getaddrinfo
421 // should return IPv6 first and then IPv4 addresses, but glibc's
422 // getaddrinfo(nullptr) with AI_PASSIVE returns:
423 // - 0.0.0.0 (IPv4-only)
424 // - :: (IPv6+IPv4) in this order
425 // See: https://sourceware.org/bugzilla/show_bug.cgi?id=9981
426 for (struct addrinfo* res = res0; res; res = res->ai_next) {
427 if (res->ai_family == AF_INET6) {
432 // If port == 0, then we should try to bind to the same port on ipv4 and
433 // ipv6. So if we did bind to ipv6, figure out that port and use it.
434 if (sockets_.size() == 1 && port == 0) {
435 SocketAddress address;
436 address.setFromLocalAddress(sockets_.back().socket_);
437 snprintf(sport, sizeof(sport), "%u", address.getPort());
439 CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0));
443 for (struct addrinfo* res = res0; res; res = res->ai_next) {
444 if (res->ai_family != AF_INET6) {
448 } catch (const std::system_error& e) {
449 // If we can't bind to the same port on ipv4 as ipv6 when using
450 // port=0 then we will retry again before giving up after
451 // kNumTries attempts. We do this by closing the sockets that
452 // were opened, then restarting from scratch.
453 if (port == 0 && !sockets_.empty() && tries != kNumTries) {
454 for (const auto& socket : sockets_) {
455 if (socket.socket_ <= 0) {
457 } else if (shutdownSocketSet_) {
458 shutdownSocketSet_->close(socket.socket_);
460 closeNoInt(socket.socket_);
464 snprintf(sport, sizeof(sport), "%u", port);
466 CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0));
476 if (sockets_.size() == 0) {
477 throw std::runtime_error(
478 "did not bind any async server socket for port");
482 void AsyncServerSocket::listen(int backlog) {
483 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
486 for (auto& handler : sockets_) {
487 if (fsp::listen(handler.socket_, backlog) == -1) {
488 folly::throwSystemError(errno,
489 "failed to listen on async server socket");
494 void AsyncServerSocket::getAddress(SocketAddress* addressReturn) const {
495 CHECK(sockets_.size() >= 1);
496 VLOG_IF(2, sockets_.size() > 1)
497 << "Warning: getAddress() called and multiple addresses available ("
498 << sockets_.size() << "). Returning only the first one.";
500 addressReturn->setFromLocalAddress(sockets_[0].socket_);
503 std::vector<SocketAddress> AsyncServerSocket::getAddresses()
505 CHECK(sockets_.size() >= 1);
506 auto tsaVec = std::vector<SocketAddress>(sockets_.size());
507 auto tsaIter = tsaVec.begin();
508 for (const auto& socket : sockets_) {
509 (tsaIter++)->setFromLocalAddress(socket.socket_);
514 void AsyncServerSocket::addAcceptCallback(AcceptCallback *callback,
515 EventBase *eventBase,
516 uint32_t maxAtOnce) {
517 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
519 // If this is the first accept callback and we are supposed to be accepting,
520 // start accepting once the callback is installed.
521 bool runStartAccepting = accepting_ && callbacks_.empty();
523 callbacks_.emplace_back(callback, eventBase);
526 // If this is the first accept callback and we are supposed to be accepting,
528 if (runStartAccepting) {
534 // Run in AsyncServerSocket's eventbase; notify that we are
535 // starting to accept connections
536 callback->acceptStarted();
540 // Start the remote acceptor.
542 // It would be nice if we could avoid starting the remote acceptor if
543 // eventBase == eventBase_. However, that would cause issues if
544 // detachEventBase() and attachEventBase() were ever used to change the
545 // primary EventBase for the server socket. Therefore we require the caller
546 // to specify a nullptr EventBase if they want to ensure that the callback is
547 // always invoked in the primary EventBase, and to be able to invoke that
548 // callback more efficiently without having to use a notification queue.
549 RemoteAcceptor* acceptor = nullptr;
551 acceptor = new RemoteAcceptor(callback, connectionEventCallback_);
552 acceptor->start(eventBase, maxAtOnce, maxNumMsgsInQueue_);
554 callbacks_.pop_back();
558 callbacks_.back().consumer = acceptor;
561 void AsyncServerSocket::removeAcceptCallback(AcceptCallback *callback,
562 EventBase *eventBase) {
563 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
565 // Find the matching AcceptCallback.
566 // We just do a simple linear search; we don't expect removeAcceptCallback()
567 // to be called frequently, and we expect there to only be a small number of
569 std::vector<CallbackInfo>::iterator it = callbacks_.begin();
572 if (it == callbacks_.end()) {
573 throw std::runtime_error("AsyncServerSocket::removeAcceptCallback(): "
574 "accept callback not found");
576 if (it->callback == callback &&
577 (it->eventBase == eventBase || eventBase == nullptr)) {
584 // Remove this callback from callbacks_.
586 // Do this before invoking the acceptStopped() callback, in case
587 // acceptStopped() invokes one of our methods that examines callbacks_.
589 // Save a copy of the CallbackInfo first.
590 CallbackInfo info(*it);
591 callbacks_.erase(it);
592 if (n < callbackIndex_) {
593 // We removed an element before callbackIndex_. Move callbackIndex_ back
594 // one step, since things after n have been shifted back by 1.
597 // We removed something at or after callbackIndex_.
598 // If we removed the last element and callbackIndex_ was pointing at it,
599 // we need to reset callbackIndex_ to 0.
600 if (callbackIndex_ >= callbacks_.size()) {
606 // consumer could be nullptr is we run callbacks in primary event
608 DCHECK(info.eventBase);
609 info.consumer->stop(info.eventBase, info.callback);
611 // callback invoked in the primary event base, just call directly
612 DCHECK(info.callback);
613 callback->acceptStopped();
616 // If we are supposed to be accepting but the last accept callback
617 // was removed, unregister for events until a callback is added.
618 if (accepting_ && callbacks_.empty()) {
619 for (auto& handler : sockets_) {
620 handler.unregisterHandler();
625 void AsyncServerSocket::startAccepting() {
626 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
629 if (callbacks_.empty()) {
630 // We can't actually begin accepting if no callbacks are defined.
631 // Wait until a callback is added to start accepting.
635 for (auto& handler : sockets_) {
636 if (!handler.registerHandler(
637 EventHandler::READ | EventHandler::PERSIST)) {
638 throw std::runtime_error("failed to register for accept events");
643 void AsyncServerSocket::pauseAccepting() {
644 assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
646 for (auto& handler : sockets_) {
647 handler. unregisterHandler();
650 // If we were in the accept backoff state, disable the backoff timeout
651 if (backoffTimeout_) {
652 backoffTimeout_->cancelTimeout();
656 int AsyncServerSocket::createSocket(int family) {
657 int fd = fsp::socket(family, SOCK_STREAM, 0);
659 folly::throwSystemError(errno, "error creating async server socket");
663 setupSocket(fd, family);
671 void AsyncServerSocket::setupSocket(int fd, int family) {
672 // Put the socket in non-blocking mode
673 if (fcntl(fd, F_SETFL, O_NONBLOCK) != 0) {
674 folly::throwSystemError(errno,
675 "failed to put socket in non-blocking mode");
678 // Set reuseaddr to avoid 2MSL delay on server restart
680 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) {
681 // This isn't a fatal error; just log an error message and continue
682 LOG(ERROR) << "failed to set SO_REUSEADDR on async server socket " << errno;
685 // Set reuseport to support multiple accept threads
687 if (reusePortEnabled_ &&
688 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(int)) != 0) {
689 LOG(ERROR) << "failed to set SO_REUSEPORT on async server socket "
692 folly::throwSystemError(errno, "failed to bind to the async server socket");
694 SocketAddress address;
695 address.setFromLocalAddress(fd);
696 folly::throwSystemError(errno,
697 "failed to bind to async server socket: " +
702 // Set keepalive as desired
703 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
704 (keepAliveEnabled_) ? &one : &zero, sizeof(int)) != 0) {
705 LOG(ERROR) << "failed to set SO_KEEPALIVE on async server socket: " <<
709 // Setup FD_CLOEXEC flag
711 (-1 == folly::setCloseOnExec(fd, closeOnExec_))) {
712 LOG(ERROR) << "failed to set FD_CLOEXEC on async server socket: " <<
716 // Set TCP nodelay if available, MAC OS X Hack
717 // See http://lists.danga.com/pipermail/memcached/2005-March/001240.html
719 if (family != AF_UNIX) {
720 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) != 0) {
721 // This isn't a fatal error; just log an error message and continue
722 LOG(ERROR) << "failed to set TCP_NODELAY on async server socket: " <<
729 if (tfo_ && detail::tfo_enable(fd, tfoMaxQueueSize_) != 0) {
730 // This isn't a fatal error; just log an error message and continue
731 LOG(WARNING) << "failed to set TCP_FASTOPEN on async server socket: "
732 << folly::errnoStr(errno);
736 if (shutdownSocketSet_) {
737 shutdownSocketSet_->add(fd);
741 void AsyncServerSocket::handlerReady(uint16_t /* events */,
743 sa_family_t addressFamily) noexcept {
744 assert(!callbacks_.empty());
745 DestructorGuard dg(this);
747 // Only accept up to maxAcceptAtOnce_ connections at a time,
748 // to avoid starving other I/O handlers using this EventBase.
749 for (uint32_t n = 0; n < maxAcceptAtOnce_; ++n) {
750 SocketAddress address;
752 sockaddr_storage addrStorage;
753 socklen_t addrLen = sizeof(addrStorage);
754 sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
756 // In some cases, accept() doesn't seem to update these correctly.
757 saddr->sa_family = addressFamily;
758 if (addressFamily == AF_UNIX) {
759 addrLen = sizeof(struct sockaddr_un);
762 // Accept a new client socket
764 int clientSocket = accept4(fd, saddr, &addrLen, SOCK_NONBLOCK);
766 int clientSocket = accept(fd, saddr, &addrLen);
769 address.setFromSockaddr(saddr, addrLen);
771 if (clientSocket >= 0 && connectionEventCallback_) {
772 connectionEventCallback_->onConnectionAccepted(clientSocket, address);
775 std::chrono::time_point<std::chrono::steady_clock> nowMs =
776 std::chrono::steady_clock::now();
777 auto timeSinceLastAccept = std::max<int64_t>(
779 nowMs.time_since_epoch().count() -
780 lastAccepTimestamp_.time_since_epoch().count());
781 lastAccepTimestamp_ = nowMs;
782 if (acceptRate_ < 1) {
783 acceptRate_ *= 1 + acceptRateAdjustSpeed_ * timeSinceLastAccept;
784 if (acceptRate_ >= 1) {
786 } else if (rand() > acceptRate_ * RAND_MAX) {
787 ++numDroppedConnections_;
788 if (clientSocket >= 0) {
789 closeNoInt(clientSocket);
790 if (connectionEventCallback_) {
791 connectionEventCallback_->onConnectionDropped(clientSocket,
799 if (clientSocket < 0) {
800 if (errno == EAGAIN) {
801 // No more sockets to accept right now.
802 // Check for this code first, since it's the most common.
804 } else if (errno == EMFILE || errno == ENFILE) {
805 // We're out of file descriptors. Perhaps we're accepting connections
806 // too quickly. Pause accepting briefly to back off and give the server
807 // a chance to recover.
808 LOG(ERROR) << "accept failed: out of file descriptors; entering accept "
812 // Dispatch the error message
813 dispatchError("accept() failed", errno);
815 dispatchError("accept() failed", errno);
817 if (connectionEventCallback_) {
818 connectionEventCallback_->onConnectionAcceptError(errno);
823 #ifndef SOCK_NONBLOCK
824 // Explicitly set the new connection to non-blocking mode
825 if (fcntl(clientSocket, F_SETFL, O_NONBLOCK) != 0) {
826 closeNoInt(clientSocket);
827 dispatchError("failed to set accepted socket to non-blocking mode",
829 if (connectionEventCallback_) {
830 connectionEventCallback_->onConnectionDropped(clientSocket, address);
836 // Inform the callback about the new connection
837 dispatchSocket(clientSocket, std::move(address));
839 // If we aren't accepting any more, break out of the loop
840 if (!accepting_ || callbacks_.empty()) {
846 void AsyncServerSocket::dispatchSocket(int socket,
847 SocketAddress&& address) {
848 uint32_t startingIndex = callbackIndex_;
850 // Short circuit if the callback is in the primary EventBase thread
852 CallbackInfo *info = nextCallback();
853 if (info->eventBase == nullptr) {
854 info->callback->connectionAccepted(socket, address);
858 const SocketAddress addr(address);
859 // Create a message to send over the notification queue
861 msg.type = MessageType::MSG_NEW_CONN;
862 msg.address = std::move(address);
865 // Loop until we find a free queue to write to
867 if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
868 if (connectionEventCallback_) {
869 connectionEventCallback_->onConnectionEnqueuedForAcceptorCallback(
877 // We couldn't add to queue. Fall through to below
879 ++numDroppedConnections_;
880 if (acceptRateAdjustSpeed_ > 0) {
881 // aggressively decrease accept rate when in trouble
882 static const double kAcceptRateDecreaseSpeed = 0.1;
883 acceptRate_ *= 1 - kAcceptRateDecreaseSpeed;
887 if (callbackIndex_ == startingIndex) {
888 // The notification queue was full
889 // We can't really do anything at this point other than close the socket.
891 // This should only happen if a user's service is behaving extremely
892 // badly and none of the EventBase threads are looping fast enough to
893 // process the incoming connections. If the service is overloaded, it
894 // should use pauseAccepting() to temporarily back off accepting new
895 // connections, before they reach the point where their threads can't
896 // even accept new messages.
897 LOG(ERROR) << "failed to dispatch newly accepted socket:"
898 << " all accept callback queues are full";
900 if (connectionEventCallback_) {
901 connectionEventCallback_->onConnectionDropped(socket, addr);
906 info = nextCallback();
910 void AsyncServerSocket::dispatchError(const char *msgstr, int errnoValue) {
911 uint32_t startingIndex = callbackIndex_;
912 CallbackInfo *info = nextCallback();
914 // Create a message to send over the notification queue
916 msg.type = MessageType::MSG_ERROR;
917 msg.err = errnoValue;
918 msg.msg = std::move(msgstr);
921 // Short circuit if the callback is in the primary EventBase thread
922 if (info->eventBase == nullptr) {
923 std::runtime_error ex(
924 std::string(msgstr) + folly::to<std::string>(errnoValue));
925 info->callback->acceptError(ex);
929 if (info->consumer->getQueue()->tryPutMessageNoThrow(std::move(msg))) {
932 // Fall through and try another callback
934 if (callbackIndex_ == startingIndex) {
935 // The notification queues for all of the callbacks were full.
936 // We can't really do anything at this point.
937 LOG(ERROR) << "failed to dispatch accept error: all accept callback "
938 "queues are full: error msg: " <<
939 msg.msg.c_str() << errnoValue;
942 info = nextCallback();
946 void AsyncServerSocket::enterBackoff() {
947 // If this is the first time we have entered the backoff state,
948 // allocate backoffTimeout_.
949 if (backoffTimeout_ == nullptr) {
951 backoffTimeout_ = new BackoffTimeout(this);
952 } catch (const std::bad_alloc& ex) {
953 // Man, we couldn't even allocate the timer to re-enable accepts.
954 // We must be in pretty bad shape. Don't pause accepting for now,
955 // since we won't be able to re-enable ourselves later.
956 LOG(ERROR) << "failed to allocate AsyncServerSocket backoff"
957 << " timer; unable to temporarly pause accepting";
958 if (connectionEventCallback_) {
959 connectionEventCallback_->onBackoffError();
965 // For now, we simply pause accepting for 1 second.
967 // We could add some smarter backoff calculation here in the future. (e.g.,
968 // start sleeping for longer if we keep hitting the backoff frequently.)
969 // Typically the user needs to figure out why the server is overloaded and
970 // fix it in some other way, though. The backoff timer is just a simple
971 // mechanism to try and give the connection processing code a little bit of
972 // breathing room to catch up, and to avoid just spinning and failing to
973 // accept over and over again.
974 const uint32_t timeoutMS = 1000;
975 if (!backoffTimeout_->scheduleTimeout(timeoutMS)) {
976 LOG(ERROR) << "failed to schedule AsyncServerSocket backoff timer;"
977 << "unable to temporarly pause accepting";
978 if (connectionEventCallback_) {
979 connectionEventCallback_->onBackoffError();
984 // The backoff timer is scheduled to re-enable accepts.
985 // Go ahead and disable accepts for now. We leave accepting_ set to true,
986 // since that tracks the desired state requested by the user.
987 for (auto& handler : sockets_) {
988 handler.unregisterHandler();
990 if (connectionEventCallback_) {
991 connectionEventCallback_->onBackoffStarted();
995 void AsyncServerSocket::backoffTimeoutExpired() {
996 // accepting_ should still be true.
997 // If pauseAccepting() was called while in the backoff state it will cancel
998 // the backoff timeout.
1000 // We can't be detached from the EventBase without being paused
1001 assert(eventBase_ != nullptr && eventBase_->isInEventBaseThread());
1003 // If all of the callbacks were removed, we shouldn't re-enable accepts
1004 if (callbacks_.empty()) {
1005 if (connectionEventCallback_) {
1006 connectionEventCallback_->onBackoffEnded();
1011 // Register the handler.
1012 for (auto& handler : sockets_) {
1013 if (!handler.registerHandler(
1014 EventHandler::READ | EventHandler::PERSIST)) {
1015 // We're hosed. We could just re-schedule backoffTimeout_ to
1016 // re-try again after a little bit. However, we don't want to
1017 // loop retrying forever if we can't re-enable accepts. Just
1018 // abort the entire program in this state; things are really bad
1019 // and restarting the entire server is probably the best remedy.
1021 << "failed to re-enable AsyncServerSocket accepts after backoff; "
1026 if (connectionEventCallback_) {
1027 connectionEventCallback_->onBackoffEnded();