move wangle/Executor.h to folly/ root
[folly.git] / folly / io / async / EventBase.h
1 /*
2  * Copyright 2014 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 <glog/logging.h>
20 #include <folly/io/async/AsyncTimeout.h>
21 #include <folly/io/async/TimeoutManager.h>
22 #include <folly/io/async/Request.h>
23 #include <folly/Executor.h>
24 #include <memory>
25 #include <stack>
26 #include <list>
27 #include <queue>
28 #include <cstdlib>
29 #include <set>
30 #include <utility>
31 #include <boost/intrusive/list.hpp>
32 #include <boost/utility.hpp>
33 #include <functional>
34 #include <event.h>  // libevent
35 #include <errno.h>
36 #include <math.h>
37 #include <atomic>
38
39 namespace folly {
40
41 typedef std::function<void()> Cob;
42 template <typename MessageT>
43 class NotificationQueue;
44
45 class EventBaseObserver {
46  public:
47   virtual ~EventBaseObserver() {}
48
49   virtual uint32_t getSampleRate() const = 0;
50
51   virtual void loopSample(
52     int64_t busyTime, int64_t idleTime) = 0;
53 };
54
55 // Helper class that sets and retrieves the EventBase associated with a given
56 // request via RequestContext. See Request.h for that mechanism.
57 class RequestEventBase : public RequestData {
58  public:
59   static EventBase* get() {
60     auto data = dynamic_cast<RequestEventBase*>(
61         RequestContext::get()->getContextData(kContextDataName));
62     if (!data) {
63       return nullptr;
64     }
65     return data->eb_;
66   }
67
68   static void set(EventBase* eb) {
69     RequestContext::get()->setContextData(
70         kContextDataName,
71         std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
72   }
73
74  private:
75   explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
76   EventBase* eb_;
77   static constexpr const char* kContextDataName{"EventBase"};
78 };
79
80 /**
81  * This class is a wrapper for all asynchronous I/O processing functionality
82  *
83  * EventBase provides a main loop that notifies EventHandler callback objects
84  * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
85  * when a specified timeout has expired.  More complex, higher-level callback
86  * mechanisms can then be built on top of EventHandler and AsyncTimeout.
87  *
88  * A EventBase object can only drive an event loop for a single thread.  To
89  * take advantage of multiple CPU cores, most asynchronous I/O servers have one
90  * thread per CPU, and use a separate EventBase for each thread.
91  *
92  * In general, most EventBase methods may only be called from the thread
93  * running the EventBase's loop.  There are a few exceptions to this rule, for
94  * methods that are explicitly intended to allow communication with a
95  * EventBase from other threads.  When it is safe to call a method from
96  * another thread it is explicitly listed in the method comments.
97  */
98 class EventBase :
99   private boost::noncopyable, public TimeoutManager, public Executor
100 {
101  public:
102   /**
103    * A callback interface to use with runInLoop()
104    *
105    * Derive from this class if you need to delay some code execution until the
106    * next iteration of the event loop.  This allows you to schedule code to be
107    * invoked from the top-level of the loop, after your immediate callers have
108    * returned.
109    *
110    * If a LoopCallback object is destroyed while it is scheduled to be run in
111    * the next loop iteration, it will automatically be cancelled.
112    */
113   class LoopCallback {
114    public:
115     virtual ~LoopCallback() {}
116
117     virtual void runLoopCallback() noexcept = 0;
118     void cancelLoopCallback() {
119       hook_.unlink();
120     }
121
122     bool isLoopCallbackScheduled() const {
123       return hook_.is_linked();
124     }
125
126    private:
127     typedef boost::intrusive::list_member_hook<
128       boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
129
130     ListHook hook_;
131
132     typedef boost::intrusive::list<
133       LoopCallback,
134       boost::intrusive::member_hook<LoopCallback, ListHook,
135                                     &LoopCallback::hook_>,
136       boost::intrusive::constant_time_size<false> > List;
137
138     // EventBase needs access to LoopCallbackList (and therefore to hook_)
139     friend class EventBase;
140     std::shared_ptr<RequestContext> context_;
141   };
142
143   /**
144    * Create a new EventBase object.
145    */
146   EventBase();
147
148   /**
149    * Create a new EventBase object that will use the specified libevent
150    * event_base object to drive the event loop.
151    *
152    * The EventBase will take ownership of this event_base, and will call
153    * event_base_free(evb) when the EventBase is destroyed.
154    */
155   explicit EventBase(event_base* evb);
156   ~EventBase();
157
158   /**
159    * Runs the event loop.
160    *
161    * loop() will loop waiting for I/O or timeouts and invoking EventHandler
162    * and AsyncTimeout callbacks as their events become ready.  loop() will
163    * only return when there are no more events remaining to process, or after
164    * terminateLoopSoon() has been called.
165    *
166    * loop() may be called again to restart event processing after a previous
167    * call to loop() or loopForever() has returned.
168    *
169    * Returns true if the loop completed normally (if it processed all
170    * outstanding requests, or if terminateLoopSoon() was called).  If an error
171    * occurs waiting for events, false will be returned.
172    */
173   bool loop();
174
175   /**
176    * Wait for some events to become active, run them, then return.
177    *
178    * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
179    * are not any events to process.
180    *
181    * This is useful for callers that want to run the loop manually.
182    *
183    * Returns the same result as loop().
184    */
185   bool loopOnce(int flags = 0);
186
187   /**
188    * Runs the event loop.
189    *
190    * loopForever() behaves like loop(), except that it keeps running even if
191    * when there are no more user-supplied EventHandlers or AsyncTimeouts
192    * registered.  It will only return after terminateLoopSoon() has been
193    * called.
194    *
195    * This is useful for callers that want to wait for other threads to call
196    * runInEventBaseThread(), even when there are no other scheduled events.
197    *
198    * loopForever() may be called again to restart event processing after a
199    * previous call to loop() or loopForever() has returned.
200    *
201    * Throws a std::system_error if an error occurs.
202    */
203   void loopForever();
204
205   /**
206    * Causes the event loop to exit soon.
207    *
208    * This will cause an existing call to loop() or loopForever() to stop event
209    * processing and return, even if there are still events remaining to be
210    * processed.
211    *
212    * It is safe to call terminateLoopSoon() from another thread to cause loop()
213    * to wake up and return in the EventBase loop thread.  terminateLoopSoon()
214    * may also be called from the loop thread itself (for example, a
215    * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
216    * cause the loop to exit after the callback returns.)  If the loop is not
217    * running, this will cause the next call to loop to terminate soon after
218    * starting.  If a loop runs out of work (and so terminates on its own)
219    * concurrently with a call to terminateLoopSoon(), this may cause a race
220    * condition.
221    *
222    * Note that the caller is responsible for ensuring that cleanup of all event
223    * callbacks occurs properly.  Since terminateLoopSoon() causes the loop to
224    * exit even when there are pending events present, there may be remaining
225    * callbacks present waiting to be invoked.  If the loop is later restarted
226    * pending events will continue to be processed normally, however if the
227    * EventBase is destroyed after calling terminateLoopSoon() it is the
228    * caller's responsibility to ensure that cleanup happens properly even if
229    * some outstanding events are never processed.
230    */
231   void terminateLoopSoon();
232
233   /**
234    * Adds the given callback to a queue of things run after the current pass
235    * through the event loop completes.  Note that if this callback calls
236    * runInLoop() the new callback won't be called until the main event loop
237    * has gone through a cycle.
238    *
239    * This method may only be called from the EventBase's thread.  This
240    * essentially allows an event handler to schedule an additional callback to
241    * be invoked after it returns.
242    *
243    * Use runInEventBaseThread() to schedule functions from another thread.
244    *
245    * The thisIteration parameter makes this callback run in this loop
246    * iteration, instead of the next one, even if called from a
247    * runInLoop callback (normal io callbacks that call runInLoop will
248    * always run in this iteration).  This was originally added to
249    * support detachEventBase, as a user callback may have called
250    * terminateLoopSoon(), but we want to make sure we detach.  Also,
251    * detachEventBase almost always must be called from the base event
252    * loop to ensure the stack is unwound, since most users of
253    * EventBase are not thread safe.
254    *
255    * Ideally we would not need thisIteration, and instead just use
256    * runInLoop with loop() (instead of terminateLoopSoon).
257    */
258   void runInLoop(LoopCallback* callback, bool thisIteration = false);
259
260   /**
261    * Convenience function to call runInLoop() with a std::function.
262    *
263    * This creates a LoopCallback object to wrap the std::function, and invoke
264    * the std::function when the loop callback fires.  This is slightly more
265    * expensive than defining your own LoopCallback, but more convenient in
266    * areas that aren't performance sensitive where you just want to use
267    * std::bind.  (std::bind is fairly slow on even by itself.)
268    *
269    * This method may only be called from the EventBase's thread.  This
270    * essentially allows an event handler to schedule an additional callback to
271    * be invoked after it returns.
272    *
273    * Use runInEventBaseThread() to schedule functions from another thread.
274    */
275   void runInLoop(const Cob& c, bool thisIteration = false);
276
277   void runInLoop(Cob&& c, bool thisIteration = false);
278
279   /**
280    * Adds the given callback to a queue of things run before destruction
281    * of current EventBase.
282    *
283    * This allows users of EventBase that run in it, but don't control it,
284    * to be notified before EventBase gets destructed.
285    *
286    * Note: will be called from the thread that invoked EventBase destructor,
287    *       before the final run of loop callbacks.
288    */
289   void runOnDestruction(LoopCallback* callback);
290
291   /**
292    * Adds a callback that will run immediately *before* the event loop.
293    * This is very similar to runInLoop(), but will not cause the loop to break:
294    * For example, this callback could be used to get loop times.
295    */
296   void runBeforeLoop(LoopCallback* callback);
297
298   /**
299    * Run the specified function in the EventBase's thread.
300    *
301    * This method is thread-safe, and may be called from another thread.
302    *
303    * If runInEventBaseThread() is called when the EventBase loop is not
304    * running, the function call will be delayed until the next time the loop is
305    * started.
306    *
307    * If runInEventBaseThread() returns true the function has successfully been
308    * scheduled to run in the loop thread.  However, if the loop is terminated
309    * (and never later restarted) before it has a chance to run the requested
310    * function, the function will be run upon the EventBase's destruction.
311    *
312    * If two calls to runInEventBaseThread() are made from the same thread, the
313    * functions will always be run in the order that they were scheduled.
314    * Ordering between functions scheduled from separate threads is not
315    * guaranteed.
316    *
317    * @param fn  The function to run.  The function must not throw any
318    *     exceptions.
319    * @param arg An argument to pass to the function.
320    *
321    * @return Returns true if the function was successfully scheduled, or false
322    *         if there was an error scheduling the function.
323    */
324   template<typename T>
325   bool runInEventBaseThread(void (*fn)(T*), T* arg) {
326     return runInEventBaseThread(reinterpret_cast<void (*)(void*)>(fn),
327                                 reinterpret_cast<void*>(arg));
328   }
329
330   bool runInEventBaseThread(void (*fn)(void*), void* arg);
331
332   /**
333    * Run the specified function in the EventBase's thread
334    *
335    * This version of runInEventBaseThread() takes a std::function object.
336    * Note that this is less efficient than the version that takes a plain
337    * function pointer and void* argument, as it has to allocate memory to copy
338    * the std::function object.
339    *
340    * If the loop is terminated (and never later restarted) before it has a
341    * chance to run the requested function, the function will be run upon the
342    * EventBase's destruction.
343    *
344    * The function must not throw any exceptions.
345    */
346   bool runInEventBaseThread(const Cob& fn);
347
348   /**
349    * Runs the given Cob at some time after the specified number of
350    * milliseconds.  (No guarantees exactly when.)
351    *
352    * @return  true iff the cob was successfully registered.
353    */
354   bool runAfterDelay(
355       const Cob& c,
356       int milliseconds,
357       TimeoutManager::InternalEnum = TimeoutManager::InternalEnum::NORMAL);
358
359   /**
360    * Set the maximum desired latency in us and provide a callback which will be
361    * called when that latency is exceeded.
362    */
363   void setMaxLatency(int64_t maxLatency, const Cob& maxLatencyCob) {
364     maxLatency_ = maxLatency;
365     maxLatencyCob_ = maxLatencyCob;
366   }
367
368   /**
369    * Set smoothing coefficient for loop load average; # of milliseconds
370    * for exp(-1) (1/2.71828...) decay.
371    */
372   void setLoadAvgMsec(uint32_t ms);
373
374   /**
375    * reset the load average to a desired value
376    */
377   void resetLoadAvg(double value = 0.0);
378
379   /**
380    * Get the average loop time in microseconds (an exponentially-smoothed ave)
381    */
382   double getAvgLoopTime() const {
383     return avgLoopTime_.get();
384   }
385
386   /**
387     * check if the event base loop is running.
388    */
389   bool isRunning() const {
390     return loopThread_.load(std::memory_order_relaxed) != 0;
391   }
392
393   /**
394    * wait until the event loop starts (after starting the event loop thread).
395    */
396   void waitUntilRunning();
397
398   int getNotificationQueueSize() const;
399
400   void setMaxReadAtOnce(uint32_t maxAtOnce);
401
402   /**
403    * Verify that current thread is the EventBase thread, if the EventBase is
404    * running.
405    */
406   bool isInEventBaseThread() const {
407     auto tid = loopThread_.load(std::memory_order_relaxed);
408     return tid == 0 || pthread_equal(tid, pthread_self());
409   }
410
411   bool inRunningEventBaseThread() const {
412     return pthread_equal(
413       loopThread_.load(std::memory_order_relaxed), pthread_self());
414   }
415
416   // --------- interface to underlying libevent base ------------
417   // Avoid using these functions if possible.  These functions are not
418   // guaranteed to always be present if we ever provide alternative EventBase
419   // implementations that do not use libevent internally.
420   event_base* getLibeventBase() const { return evb_; }
421   static const char* getLibeventVersion();
422   static const char* getLibeventMethod();
423
424   /**
425    * only EventHandler/AsyncTimeout subclasses and ourselves should
426    * ever call this.
427    *
428    * This is used to mark the beginning of a new loop cycle by the
429    * first handler fired within that cycle.
430    *
431    */
432   bool bumpHandlingTime();
433
434   class SmoothLoopTime {
435    public:
436     explicit SmoothLoopTime(uint64_t timeInterval)
437       : expCoeff_(-1.0/timeInterval)
438       , value_(0.0)
439       , oldBusyLeftover_(0) {
440       VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
441     }
442
443     void setTimeInterval(uint64_t timeInterval);
444     void reset(double value = 0.0);
445
446     void addSample(int64_t idle, int64_t busy);
447
448     double get() const {
449       return value_;
450     }
451
452     void dampen(double factor) {
453       value_ *= factor;
454     }
455
456    private:
457     double  expCoeff_;
458     double  value_;
459     int64_t oldBusyLeftover_;
460   };
461
462   void setObserver(
463     const std::shared_ptr<EventBaseObserver>& observer) {
464     observer_ = observer;
465   }
466
467   const std::shared_ptr<EventBaseObserver>& getObserver() {
468     return observer_;
469   }
470
471   /**
472    * Set the name of the thread that runs this event base.
473    */
474   void setName(const std::string& name);
475
476   /**
477    * Returns the name of the thread that runs this event base.
478    */
479   const std::string& getName();
480
481   /// Implements the Executor interface
482   void add(Cob fn) override {
483     // runInEventBaseThread() takes a const&,
484     // so no point in doing std::move here.
485     runInEventBaseThread(fn);
486   }
487
488  private:
489
490   // TimeoutManager
491   void attachTimeoutManager(AsyncTimeout* obj,
492                             TimeoutManager::InternalEnum internal);
493
494   void detachTimeoutManager(AsyncTimeout* obj);
495
496   bool scheduleTimeout(AsyncTimeout* obj, std::chrono::milliseconds timeout);
497
498   void cancelTimeout(AsyncTimeout* obj);
499
500   bool isInTimeoutManagerThread() {
501     return isInEventBaseThread();
502   }
503
504   // Helper class used to short circuit runInEventBaseThread
505   class RunInLoopCallback : public LoopCallback {
506    public:
507     RunInLoopCallback(void (*fn)(void*), void* arg);
508     void runLoopCallback() noexcept;
509
510    private:
511     void (*fn_)(void*);
512     void* arg_;
513   };
514
515   /*
516    * Helper function that tells us whether we have already handled
517    * some event/timeout/callback in this loop iteration.
518    */
519   bool nothingHandledYet();
520
521   // --------- libevent callbacks (not for client use) ------------
522
523   static void runFunctionPtr(std::function<void()>* fn);
524
525   // small object used as a callback arg with enough info to execute the
526   // appropriate client-provided Cob
527   class CobTimeout : public AsyncTimeout {
528    public:
529     CobTimeout(EventBase* b, const Cob& c, TimeoutManager::InternalEnum in)
530         : AsyncTimeout(b, in), cob_(c) {}
531
532     virtual void timeoutExpired() noexcept;
533
534    private:
535     Cob cob_;
536
537    public:
538     typedef boost::intrusive::list_member_hook<
539       boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
540
541     ListHook hook;
542
543     typedef boost::intrusive::list<
544       CobTimeout,
545       boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
546       boost::intrusive::constant_time_size<false> > List;
547   };
548
549   typedef LoopCallback::List LoopCallbackList;
550   class FunctionRunner;
551
552   bool loopBody(int flags = 0);
553
554   // executes any callbacks queued by runInLoop(); returns false if none found
555   bool runLoopCallbacks(bool setContext = true);
556
557   void initNotificationQueue();
558
559   CobTimeout::List pendingCobTimeouts_;
560
561   LoopCallbackList loopCallbacks_;
562   LoopCallbackList runBeforeLoopCallbacks_;
563   LoopCallbackList onDestructionCallbacks_;
564
565   // This will be null most of the time, but point to currentCallbacks
566   // if we are in the middle of running loop callbacks, such that
567   // runInLoop(..., true) will always run in the current loop
568   // iteration.
569   LoopCallbackList* runOnceCallbacks_;
570
571   // stop_ is set by terminateLoopSoon() and is used by the main loop
572   // to determine if it should exit
573   bool stop_;
574
575   // The ID of the thread running the main loop.
576   // 0 if loop is not running.
577   // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
578   // even that atomic<pthread_t> is valid), but that's how it is
579   // everywhere (at least on Linux, FreeBSD, and OSX).
580   std::atomic<pthread_t> loopThread_;
581
582   // pointer to underlying event_base class doing the heavy lifting
583   event_base* evb_;
584
585   // A notification queue for runInEventBaseThread() to use
586   // to send function requests to the EventBase thread.
587   std::unique_ptr<NotificationQueue<std::pair<void (*)(void*), void*>>> queue_;
588   std::unique_ptr<FunctionRunner> fnRunner_;
589
590   // limit for latency in microseconds (0 disables)
591   int64_t maxLatency_;
592
593   // exponentially-smoothed average loop time for latency-limiting
594   SmoothLoopTime avgLoopTime_;
595
596   // smoothed loop time used to invoke latency callbacks; differs from
597   // avgLoopTime_ in that it's scaled down after triggering a callback
598   // to reduce spamminess
599   SmoothLoopTime maxLatencyLoopTime_;
600
601   // callback called when latency limit is exceeded
602   Cob maxLatencyCob_;
603
604   // we'll wait this long before running deferred callbacks if the event
605   // loop is idle.
606   static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
607
608   // Wrap-around loop counter to detect beginning of each loop
609   uint64_t nextLoopCnt_;
610   uint64_t latestLoopCnt_;
611   uint64_t startWork_;
612
613   // Observer to export counters
614   std::shared_ptr<EventBaseObserver> observer_;
615   uint32_t observerSampleCount_;
616
617   // Name of the thread running this EventBase
618   std::string name_;
619 };
620
621 } // folly