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