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