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