Switch uses of networking headers to <folly/portability/Sockets.h>
[folly.git] / folly / io / async / AsyncServerSocket.h
1 /*
2  * Copyright 2016 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 #pragma once
18
19 #include <folly/SocketAddress.h>
20 #include <folly/io/ShutdownSocketSet.h>
21 #include <folly/io/async/AsyncSocketBase.h>
22 #include <folly/io/async/AsyncTimeout.h>
23 #include <folly/io/async/DelayedDestruction.h>
24 #include <folly/io/async/EventBase.h>
25 #include <folly/io/async/EventHandler.h>
26 #include <folly/io/async/NotificationQueue.h>
27 #include <folly/portability/Sockets.h>
28
29 #include <limits.h>
30 #include <stddef.h>
31 #include <exception>
32 #include <memory>
33 #include <vector>
34
35 // Due to the way kernel headers are included, this may or may not be defined.
36 // Number pulled from 3.10 kernel headers.
37 #ifndef SO_REUSEPORT
38 #define SO_REUSEPORT 15
39 #endif
40
41 namespace folly {
42
43 /**
44  * A listening socket that asynchronously informs a callback whenever a new
45  * connection has been accepted.
46  *
47  * Unlike most async interfaces that always invoke their callback in the same
48  * EventBase thread, AsyncServerSocket is unusual in that it can distribute
49  * the callbacks across multiple EventBase threads.
50  *
51  * This supports a common use case for network servers to distribute incoming
52  * connections across a number of EventBase threads.  (Servers typically run
53  * with one EventBase thread per CPU.)
54  *
55  * Despite being able to invoke callbacks in multiple EventBase threads,
56  * AsyncServerSocket still has one "primary" EventBase.  Operations that
57  * modify the AsyncServerSocket state may only be performed from the primary
58  * EventBase thread.
59  */
60 class AsyncServerSocket : public DelayedDestruction
61                         , public AsyncSocketBase {
62  public:
63   typedef std::unique_ptr<AsyncServerSocket, Destructor> UniquePtr;
64   // Disallow copy, move, and default construction.
65   AsyncServerSocket(AsyncServerSocket&&) = delete;
66
67   /**
68    * A callback interface to get notified of client socket events.
69    *
70    * The ConnectionEventCallback implementations need to be thread-safe as the
71    * callbacks may be called from different threads.
72    */
73   class ConnectionEventCallback {
74    public:
75     virtual ~ConnectionEventCallback() = default;
76
77     /**
78      * onConnectionAccepted() is called right after a client connection
79      * is accepted using the system accept()/accept4() APIs.
80      */
81     virtual void onConnectionAccepted(const int socket,
82                                       const SocketAddress& addr) noexcept = 0;
83
84     /**
85      * onConnectionAcceptError() is called when an error occurred accepting
86      * a connection.
87      */
88     virtual void onConnectionAcceptError(const int err) noexcept = 0;
89
90     /**
91      * onConnectionDropped() is called when a connection is dropped,
92      * probably because of some error encountered.
93      */
94     virtual void onConnectionDropped(const int socket,
95                                      const SocketAddress& addr) noexcept = 0;
96
97     /**
98      * onConnectionEnqueuedForAcceptorCallback() is called when the
99      * connection is successfully enqueued for an AcceptCallback to pick up.
100      */
101     virtual void onConnectionEnqueuedForAcceptorCallback(
102         const int socket,
103         const SocketAddress& addr) noexcept = 0;
104
105     /**
106      * onConnectionDequeuedByAcceptorCallback() is called when the
107      * connection is successfully dequeued by an AcceptCallback.
108      */
109     virtual void onConnectionDequeuedByAcceptorCallback(
110         const int socket,
111         const SocketAddress& addr) noexcept = 0;
112
113     /**
114      * onBackoffStarted is called when the socket has successfully started
115      * backing off accepting new client sockets.
116      */
117     virtual void onBackoffStarted() noexcept = 0;
118
119     /**
120      * onBackoffEnded is called when the backoff period has ended and the socket
121      * has successfully resumed accepting new connections if there is any
122      * AcceptCallback registered.
123      */
124     virtual void onBackoffEnded() noexcept = 0;
125
126     /**
127      * onBackoffError is called when there is an error entering backoff
128      */
129     virtual void onBackoffError() noexcept = 0;
130   };
131
132   class AcceptCallback {
133    public:
134     virtual ~AcceptCallback() = default;
135
136     /**
137      * connectionAccepted() is called whenever a new client connection is
138      * received.
139      *
140      * The AcceptCallback will remain installed after connectionAccepted()
141      * returns.
142      *
143      * @param fd          The newly accepted client socket.  The AcceptCallback
144      *                    assumes ownership of this socket, and is responsible
145      *                    for closing it when done.  The newly accepted file
146      *                    descriptor will have already been put into
147      *                    non-blocking mode.
148      * @param clientAddr  A reference to a SocketAddress struct containing the
149      *                    client's address.  This struct is only guaranteed to
150      *                    remain valid until connectionAccepted() returns.
151      */
152     virtual void connectionAccepted(int fd,
153                                     const SocketAddress& clientAddr)
154       noexcept = 0;
155
156     /**
157      * acceptError() is called if an error occurs while accepting.
158      *
159      * The AcceptCallback will remain installed even after an accept error,
160      * as the errors are typically somewhat transient, such as being out of
161      * file descriptors.  The server socket must be explicitly stopped if you
162      * wish to stop accepting after an error.
163      *
164      * @param ex  An exception representing the error.
165      */
166     virtual void acceptError(const std::exception& ex) noexcept = 0;
167
168     /**
169      * acceptStarted() will be called in the callback's EventBase thread
170      * after this callback has been added to the AsyncServerSocket.
171      *
172      * acceptStarted() will be called before any calls to connectionAccepted()
173      * or acceptError() are made on this callback.
174      *
175      * acceptStarted() makes it easier for callbacks to perform initialization
176      * inside the callback thread.  (The call to addAcceptCallback() must
177      * always be made from the AsyncServerSocket's primary EventBase thread.
178      * acceptStarted() provides a hook that will always be invoked in the
179      * callback's thread.)
180      *
181      * Note that the call to acceptStarted() is made once the callback is
182      * added, regardless of whether or not the AsyncServerSocket is actually
183      * accepting at the moment.  acceptStarted() will be called even if the
184      * AsyncServerSocket is paused when the callback is added (including if
185      * the initial call to startAccepting() on the AsyncServerSocket has not
186      * been made yet).
187      */
188     virtual void acceptStarted() noexcept {}
189
190     /**
191      * acceptStopped() will be called when this AcceptCallback is removed from
192      * the AsyncServerSocket, or when the AsyncServerSocket is destroyed,
193      * whichever occurs first.
194      *
195      * No more calls to connectionAccepted() or acceptError() will be made
196      * after acceptStopped() is invoked.
197      */
198     virtual void acceptStopped() noexcept {}
199   };
200
201   static const uint32_t kDefaultMaxAcceptAtOnce = 30;
202   static const uint32_t kDefaultCallbackAcceptAtOnce = 5;
203   static const uint32_t kDefaultMaxMessagesInQueue = 1024;
204   /**
205    * Create a new AsyncServerSocket with the specified EventBase.
206    *
207    * @param eventBase  The EventBase to use for driving the asynchronous I/O.
208    *                   If this parameter is nullptr, attachEventBase() must be
209    *                   called before this socket can begin accepting
210    *                   connections.
211    */
212   explicit AsyncServerSocket(EventBase* eventBase = nullptr);
213
214   /**
215    * Helper function to create a shared_ptr<AsyncServerSocket>.
216    *
217    * This passes in the correct destructor object, since AsyncServerSocket's
218    * destructor is protected and cannot be invoked directly.
219    */
220   static std::shared_ptr<AsyncServerSocket>
221   newSocket(EventBase* evb = nullptr) {
222     return std::shared_ptr<AsyncServerSocket>(new AsyncServerSocket(evb),
223                                                  Destructor());
224   }
225
226   void setShutdownSocketSet(ShutdownSocketSet* newSS);
227
228   /**
229    * Destroy the socket.
230    *
231    * AsyncServerSocket::destroy() must be called to destroy the socket.
232    * The normal destructor is private, and should not be invoked directly.
233    * This prevents callers from deleting a AsyncServerSocket while it is
234    * invoking a callback.
235    *
236    * destroy() must be invoked from the socket's primary EventBase thread.
237    *
238    * If there are AcceptCallbacks still installed when destroy() is called,
239    * acceptStopped() will be called on these callbacks to notify them that
240    * accepting has stopped.  Accept callbacks being driven by other EventBase
241    * threads may continue to receive new accept callbacks for a brief period of
242    * time after destroy() returns.  They will not receive any more callback
243    * invocations once acceptStopped() is invoked.
244    */
245   virtual void destroy();
246
247   /**
248    * Attach this AsyncServerSocket to its primary EventBase.
249    *
250    * This may only be called if the AsyncServerSocket is not already attached
251    * to a EventBase.  The AsyncServerSocket must be attached to a EventBase
252    * before it can begin accepting connections.
253    */
254   void attachEventBase(EventBase *eventBase);
255
256   /**
257    * Detach the AsyncServerSocket from its primary EventBase.
258    *
259    * detachEventBase() may only be called if the AsyncServerSocket is not
260    * currently accepting connections.
261    */
262   void detachEventBase();
263
264   /**
265    * Get the EventBase used by this socket.
266    */
267   EventBase* getEventBase() const {
268     return eventBase_;
269   }
270
271   /**
272    * Create a AsyncServerSocket from an existing socket file descriptor.
273    *
274    * useExistingSocket() will cause the AsyncServerSocket to take ownership of
275    * the specified file descriptor, and use it to listen for new connections.
276    * The AsyncServerSocket will close the file descriptor when it is
277    * destroyed.
278    *
279    * useExistingSocket() must be called before bind() or listen().
280    *
281    * The supplied file descriptor will automatically be put into non-blocking
282    * mode.  The caller may have already directly called bind() and possibly
283    * listen on the file descriptor.  If so the caller should skip calling the
284    * corresponding AsyncServerSocket::bind() and listen() methods.
285    *
286    * On error a TTransportException will be thrown and the caller will retain
287    * ownership of the file descriptor.
288    */
289   void useExistingSocket(int fd);
290   void useExistingSockets(const std::vector<int>& fds);
291
292   /**
293    * Return the underlying file descriptor
294    */
295   std::vector<int> getSockets() const {
296     std::vector<int> sockets;
297     for (auto& handler : sockets_) {
298       sockets.push_back(handler.socket_);
299     }
300     return sockets;
301   }
302
303   /**
304    * Backwards compatible getSocket, warns if > 1 socket
305    */
306   int getSocket() const {
307     if (sockets_.size() > 1) {
308       VLOG(2) << "Warning: getSocket can return multiple fds, " <<
309         "but getSockets was not called, so only returning the first";
310     }
311     if (sockets_.size() == 0) {
312       return -1;
313     } else {
314       return sockets_[0].socket_;
315     }
316   }
317
318   /**
319    * Bind to the specified address.
320    *
321    * This must be called from the primary EventBase thread.
322    *
323    * Throws TTransportException on error.
324    */
325   virtual void bind(const SocketAddress& address);
326
327   /**
328    * Bind to the specified port for the specified addresses.
329    *
330    * This must be called from the primary EventBase thread.
331    *
332    * Throws TTransportException on error.
333    */
334   virtual void bind(
335       const std::vector<IPAddress>& ipAddresses,
336       uint16_t port);
337
338   /**
339    * Bind to the specified port.
340    *
341    * This must be called from the primary EventBase thread.
342    *
343    * Throws TTransportException on error.
344    */
345   virtual void bind(uint16_t port);
346
347   /**
348    * Get the local address to which the socket is bound.
349    *
350    * Throws TTransportException on error.
351    */
352   void getAddress(SocketAddress* addressReturn) const;
353
354   /**
355    * Get all the local addresses to which the socket is bound.
356    *
357    * Throws TTransportException on error.
358    */
359   std::vector<SocketAddress> getAddresses() const;
360
361   /**
362    * Begin listening for connections.
363    *
364    * This calls ::listen() with the specified backlog.
365    *
366    * Once listen() is invoked the socket will actually be open so that remote
367    * clients may establish connections.  (Clients that attempt to connect
368    * before listen() is called will receive a connection refused error.)
369    *
370    * At least one callback must be set and startAccepting() must be called to
371    * actually begin notifying the accept callbacks of newly accepted
372    * connections.  The backlog parameter controls how many connections the
373    * kernel will accept and buffer internally while the accept callbacks are
374    * paused (or if accepting is enabled but the callbacks cannot keep up).
375    *
376    * bind() must be called before calling listen().
377    * listen() must be called from the primary EventBase thread.
378    *
379    * Throws TTransportException on error.
380    */
381   virtual void listen(int backlog);
382
383   /**
384    * Add an AcceptCallback.
385    *
386    * When a new socket is accepted, one of the AcceptCallbacks will be invoked
387    * with the new socket.  The AcceptCallbacks are invoked in a round-robin
388    * fashion.  This allows the accepted sockets to be distributed among a pool
389    * of threads, each running its own EventBase object.  This is a common model,
390    * since most asynchronous-style servers typically run one EventBase thread
391    * per CPU.
392    *
393    * The EventBase object associated with each AcceptCallback must be running
394    * its loop.  If the EventBase loop is not running, sockets will still be
395    * scheduled for the callback, but the callback cannot actually get invoked
396    * until the loop runs.
397    *
398    * This method must be invoked from the AsyncServerSocket's primary
399    * EventBase thread.
400    *
401    * Note that startAccepting() must be called on the AsyncServerSocket to
402    * cause it to actually start accepting sockets once callbacks have been
403    * installed.
404    *
405    * @param callback   The callback to invoke.
406    * @param eventBase  The EventBase to use to invoke the callback.  This
407    *     parameter may be nullptr, in which case the callback will be invoked in
408    *     the AsyncServerSocket's primary EventBase.
409    * @param maxAtOnce  The maximum number of connections to accept in this
410    *                   callback on a single iteration of the event base loop.
411    *                   This only takes effect when eventBase is non-nullptr.
412    *                   When using a nullptr eventBase for the callback, the
413    *                   setMaxAcceptAtOnce() method controls how many
414    *                   connections the main event base will accept at once.
415    */
416   virtual void addAcceptCallback(
417     AcceptCallback *callback,
418     EventBase *eventBase,
419     uint32_t maxAtOnce = kDefaultCallbackAcceptAtOnce);
420
421   /**
422    * Remove an AcceptCallback.
423    *
424    * This allows a single AcceptCallback to be removed from the round-robin
425    * pool.
426    *
427    * This method must be invoked from the AsyncServerSocket's primary
428    * EventBase thread.  Use EventBase::runInEventBaseThread() to schedule the
429    * operation in the correct EventBase if your code is not in the server
430    * socket's primary EventBase.
431    *
432    * Given that the accept callback is being driven by a different EventBase,
433    * the AcceptCallback may continue to be invoked for a short period of time
434    * after removeAcceptCallback() returns in this thread.  Once the other
435    * EventBase thread receives the notification to stop, it will call
436    * acceptStopped() on the callback to inform it that it is fully stopped and
437    * will not receive any new sockets.
438    *
439    * If the last accept callback is removed while the socket is accepting,
440    * the socket will implicitly pause accepting.  If a callback is later added,
441    * it will resume accepting immediately, without requiring startAccepting()
442    * to be invoked.
443    *
444    * @param callback   The callback to uninstall.
445    * @param eventBase  The EventBase associated with this callback.  This must
446    *     be the same EventBase that was used when the callback was installed
447    *     with addAcceptCallback().
448    */
449   void removeAcceptCallback(AcceptCallback *callback, EventBase *eventBase);
450
451   /**
452    * Begin accepting connctions on this socket.
453    *
454    * bind() and listen() must be called before calling startAccepting().
455    *
456    * When a AsyncServerSocket is initially created, it will not begin
457    * accepting connections until at least one callback has been added and
458    * startAccepting() has been called.  startAccepting() can also be used to
459    * resume accepting connections after a call to pauseAccepting().
460    *
461    * If startAccepting() is called when there are no accept callbacks
462    * installed, the socket will not actually begin accepting until an accept
463    * callback is added.
464    *
465    * This method may only be called from the primary EventBase thread.
466    */
467   virtual void startAccepting();
468
469   /**
470    * Pause accepting connections.
471    *
472    * startAccepting() may be called to resume accepting.
473    *
474    * This method may only be called from the primary EventBase thread.
475    * If there are AcceptCallbacks being driven by other EventBase threads they
476    * may continue to receive callbacks for a short period of time after
477    * pauseAccepting() returns.
478    *
479    * Unlike removeAcceptCallback() or destroy(), acceptStopped() will not be
480    * called on the AcceptCallback objects simply due to a temporary pause.  If
481    * the server socket is later destroyed while paused, acceptStopped() will be
482    * called all of the installed AcceptCallbacks.
483    */
484   void pauseAccepting();
485
486   /**
487    * Shutdown the listen socket and notify all callbacks that accept has
488    * stopped, but don't close the socket.  This invokes shutdown(2) with the
489    * supplied argument.  Passing -1 will close the socket now.  Otherwise, the
490    * close will be delayed until this object is destroyed.
491    *
492    * Only use this if you have reason to pass special flags to shutdown.
493    * Otherwise just destroy the socket.
494    *
495    * This method has no effect when a ShutdownSocketSet option is used.
496    *
497    * Returns the result of shutdown on sockets_[n-1]
498    */
499   int stopAccepting(int shutdownFlags = -1);
500
501   /**
502    * Get the maximum number of connections that will be accepted each time
503    * around the event loop.
504    */
505   uint32_t getMaxAcceptAtOnce() const {
506     return maxAcceptAtOnce_;
507   }
508
509   /**
510    * Set the maximum number of connections that will be accepted each time
511    * around the event loop.
512    *
513    * This provides a very coarse-grained way of controlling how fast the
514    * AsyncServerSocket will accept connections.  If you find that when your
515    * server is overloaded AsyncServerSocket accepts connections more quickly
516    * than your code can process them, you can try lowering this number so that
517    * fewer connections will be accepted each event loop iteration.
518    *
519    * For more explicit control over the accept rate, you can also use
520    * pauseAccepting() to temporarily pause accepting when your server is
521    * overloaded, and then use startAccepting() later to resume accepting.
522    */
523   void setMaxAcceptAtOnce(uint32_t numConns) {
524     maxAcceptAtOnce_ = numConns;
525   }
526
527   /**
528    * Get the maximum number of unprocessed messages which a NotificationQueue
529    * can hold.
530    */
531   uint32_t getMaxNumMessagesInQueue() const {
532     return maxNumMsgsInQueue_;
533   }
534
535   /**
536    * Set the maximum number of unprocessed messages in NotificationQueue.
537    * No new message will be sent to that NotificationQueue if there are more
538    * than such number of unprocessed messages in that queue.
539    *
540    * Only works if called before addAcceptCallback.
541    */
542   void setMaxNumMessagesInQueue(uint32_t num) {
543     maxNumMsgsInQueue_ = num;
544   }
545
546   /**
547    * Get the speed of adjusting connection accept rate.
548    */
549   double getAcceptRateAdjustSpeed() const {
550     return acceptRateAdjustSpeed_;
551   }
552
553   /**
554    * Set the speed of adjusting connection accept rate.
555    */
556   void setAcceptRateAdjustSpeed(double speed) {
557     acceptRateAdjustSpeed_ = speed;
558   }
559
560   /**
561    * Get the number of connections dropped by the AsyncServerSocket
562    */
563   uint64_t getNumDroppedConnections() const {
564     return numDroppedConnections_;
565   }
566
567   /**
568    * Get the current number of unprocessed messages in NotificationQueue.
569    *
570    * This method must be invoked from the AsyncServerSocket's primary
571    * EventBase thread.  Use EventBase::runInEventBaseThread() to schedule the
572    * operation in the correct EventBase if your code is not in the server
573    * socket's primary EventBase.
574    */
575   int64_t getNumPendingMessagesInQueue() const {
576     assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread());
577     int64_t numMsgs = 0;
578     for (const auto& callback : callbacks_) {
579       numMsgs += callback.consumer->getQueue()->size();
580     }
581     return numMsgs;
582   }
583
584   /**
585    * Set whether or not SO_KEEPALIVE should be enabled on the server socket
586    * (and thus on all subsequently-accepted connections). By default, keepalive
587    * is enabled.
588    *
589    * Note that TCP keepalive usually only kicks in after the connection has
590    * been idle for several hours. Applications should almost always have their
591    * own, shorter idle timeout.
592    */
593   void setKeepAliveEnabled(bool enabled) {
594     keepAliveEnabled_ = enabled;
595
596     for (auto& handler : sockets_) {
597       if (handler.socket_ < 0) {
598         continue;
599       }
600
601       int val = (enabled) ? 1 : 0;
602       if (setsockopt(handler.socket_, SOL_SOCKET,
603                      SO_KEEPALIVE, &val, sizeof(val)) != 0) {
604         LOG(ERROR) << "failed to set SO_KEEPALIVE on async server socket: %s" <<
605                 strerror(errno);
606       }
607     }
608   }
609
610   /**
611    * Get whether or not SO_KEEPALIVE is enabled on the server socket.
612    */
613   bool getKeepAliveEnabled() const {
614     return keepAliveEnabled_;
615   }
616
617   /**
618    * Set whether or not SO_REUSEPORT should be enabled on the server socket,
619    * allowing multiple binds to the same port
620    */
621   void setReusePortEnabled(bool enabled) {
622     reusePortEnabled_ = enabled;
623
624     for (auto& handler : sockets_) {
625       if (handler.socket_ < 0) {
626         continue;
627       }
628
629       int val = (enabled) ? 1 : 0;
630       if (setsockopt(handler.socket_, SOL_SOCKET,
631                      SO_REUSEPORT, &val, sizeof(val)) != 0) {
632         LOG(ERROR) <<
633           "failed to set SO_REUSEPORT on async server socket " << errno;
634         folly::throwSystemError(errno,
635                                 "failed to bind to async server socket");
636       }
637     }
638   }
639
640   /**
641    * Get whether or not SO_REUSEPORT is enabled on the server socket.
642    */
643   bool getReusePortEnabled_() const {
644     return reusePortEnabled_;
645   }
646
647   /**
648    * Set whether or not the socket should close during exec() (FD_CLOEXEC). By
649    * default, this is enabled
650    */
651   void setCloseOnExec(bool closeOnExec) {
652     closeOnExec_ = closeOnExec;
653   }
654
655   /**
656    * Get whether or not FD_CLOEXEC is enabled on the server socket.
657    */
658   bool getCloseOnExec() const {
659     return closeOnExec_;
660   }
661
662   /**
663    * Tries to enable TFO if the machine supports it.
664    */
665   void setTFOEnabled(bool enabled, uint32_t maxTFOQueueSize) {
666     tfo_ = enabled;
667     tfoMaxQueueSize_ = maxTFOQueueSize;
668   }
669
670   /**
671    * Get whether or not the socket is accepting new connections
672    */
673   bool getAccepting() const {
674     return accepting_;
675   }
676
677   /**
678    * Set the ConnectionEventCallback
679    */
680   void setConnectionEventCallback(
681       ConnectionEventCallback* const connectionEventCallback) {
682     connectionEventCallback_ = connectionEventCallback;
683   }
684
685   /**
686    * Get the ConnectionEventCallback
687    */
688   ConnectionEventCallback* getConnectionEventCallback() const {
689     return connectionEventCallback_;
690   }
691
692  protected:
693   /**
694    * Protected destructor.
695    *
696    * Invoke destroy() instead to destroy the AsyncServerSocket.
697    */
698   virtual ~AsyncServerSocket();
699
700  private:
701   enum class MessageType {
702     MSG_NEW_CONN = 0,
703     MSG_ERROR = 1
704   };
705
706   struct QueueMessage {
707     MessageType type;
708     int fd;
709     int err;
710     SocketAddress address;
711     std::string msg;
712   };
713
714   /**
715    * A class to receive notifications to invoke AcceptCallback objects
716    * in other EventBase threads.
717    *
718    * A RemoteAcceptor object is created for each AcceptCallback that
719    * is installed in a separate EventBase thread.  The RemoteAcceptor
720    * receives notification of new sockets via a NotificationQueue,
721    * and then invokes the AcceptCallback.
722    */
723   class RemoteAcceptor
724       : private NotificationQueue<QueueMessage>::Consumer {
725   public:
726     explicit RemoteAcceptor(AcceptCallback *callback,
727                             ConnectionEventCallback *connectionEventCallback)
728       : callback_(callback),
729         connectionEventCallback_(connectionEventCallback) {}
730
731     ~RemoteAcceptor() = default;
732
733     void start(EventBase *eventBase, uint32_t maxAtOnce, uint32_t maxInQueue);
734     void stop(EventBase* eventBase, AcceptCallback* callback);
735
736     virtual void messageAvailable(QueueMessage&& message);
737
738     NotificationQueue<QueueMessage>* getQueue() {
739       return &queue_;
740     }
741
742   private:
743     AcceptCallback *callback_;
744     ConnectionEventCallback* connectionEventCallback_;
745
746     NotificationQueue<QueueMessage> queue_;
747   };
748
749   /**
750    * A struct to keep track of the callbacks associated with this server
751    * socket.
752    */
753   struct CallbackInfo {
754     CallbackInfo(AcceptCallback *cb, EventBase *evb)
755       : callback(cb),
756         eventBase(evb),
757         consumer(nullptr) {}
758
759     AcceptCallback *callback;
760     EventBase *eventBase;
761
762     RemoteAcceptor* consumer;
763   };
764
765   class BackoffTimeout;
766
767   virtual void handlerReady(
768     uint16_t events, int socket, sa_family_t family) noexcept;
769
770   int createSocket(int family);
771   void setupSocket(int fd, int family);
772   void bindSocket(int fd, const SocketAddress& address, bool isExistingSocket);
773   void dispatchSocket(int socket, SocketAddress&& address);
774   void dispatchError(const char *msg, int errnoValue);
775   void enterBackoff();
776   void backoffTimeoutExpired();
777
778   CallbackInfo* nextCallback() {
779     CallbackInfo* info = &callbacks_[callbackIndex_];
780
781     ++callbackIndex_;
782     if (callbackIndex_ >= callbacks_.size()) {
783       callbackIndex_ = 0;
784     }
785
786     return info;
787   }
788
789   struct ServerEventHandler : public EventHandler {
790     ServerEventHandler(EventBase* eventBase, int socket,
791                        AsyncServerSocket* parent,
792                       sa_family_t addressFamily)
793         : EventHandler(eventBase, socket)
794         , eventBase_(eventBase)
795         , socket_(socket)
796         , parent_(parent)
797         , addressFamily_(addressFamily) {}
798
799     ServerEventHandler(const ServerEventHandler& other)
800     : EventHandler(other.eventBase_, other.socket_)
801     , eventBase_(other.eventBase_)
802     , socket_(other.socket_)
803     , parent_(other.parent_)
804     , addressFamily_(other.addressFamily_) {}
805
806     ServerEventHandler& operator=(
807         const ServerEventHandler& other) {
808       if (this != &other) {
809         eventBase_ = other.eventBase_;
810         socket_ = other.socket_;
811         parent_ = other.parent_;
812         addressFamily_ = other.addressFamily_;
813
814         detachEventBase();
815         attachEventBase(other.eventBase_);
816         changeHandlerFD(other.socket_);
817       }
818       return *this;
819     }
820
821     // Inherited from EventHandler
822     virtual void handlerReady(uint16_t events) noexcept {
823       parent_->handlerReady(events, socket_, addressFamily_);
824     }
825
826     EventBase* eventBase_;
827     int socket_;
828     AsyncServerSocket* parent_;
829     sa_family_t addressFamily_;
830   };
831
832   EventBase *eventBase_;
833   std::vector<ServerEventHandler> sockets_;
834   std::vector<int> pendingCloseSockets_;
835   bool accepting_;
836   uint32_t maxAcceptAtOnce_;
837   uint32_t maxNumMsgsInQueue_;
838   double acceptRateAdjustSpeed_;  //0 to disable auto adjust
839   double acceptRate_;
840   std::chrono::time_point<std::chrono::steady_clock> lastAccepTimestamp_;
841   uint64_t numDroppedConnections_;
842   uint32_t callbackIndex_;
843   BackoffTimeout *backoffTimeout_;
844   std::vector<CallbackInfo> callbacks_;
845   bool keepAliveEnabled_;
846   bool reusePortEnabled_{false};
847   bool closeOnExec_;
848   bool tfo_{false};
849   uint32_t tfoMaxQueueSize_{0};
850   ShutdownSocketSet* shutdownSocketSet_;
851   ConnectionEventCallback* connectionEventCallback_{nullptr};
852 };
853
854 } // folly