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