2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
30 #include <unordered_map>
31 #include <unordered_set>
34 #include <boost/intrusive/list.hpp>
35 #include <boost/utility.hpp>
37 #include <folly/Executor.h>
38 #include <folly/Function.h>
39 #include <folly/Portability.h>
40 #include <folly/experimental/ExecutionObserver.h>
41 #include <folly/futures/DrivableExecutor.h>
42 #include <folly/io/async/AsyncTimeout.h>
43 #include <folly/io/async/Request.h>
44 #include <folly/io/async/TimeoutManager.h>
45 #include <glog/logging.h>
47 #include <event.h> // libevent
51 typedef std::function<void()> Cob;
52 template <typename MessageT>
53 class NotificationQueue;
56 class EventBaseLocalBase;
58 class EventBaseLocalBaseBase {
60 virtual void onEventBaseDestruction(EventBase& evb) = 0;
61 virtual ~EventBaseLocalBaseBase() = default;
67 class EventBaseObserver {
69 virtual ~EventBaseObserver() = default;
71 virtual uint32_t getSampleRate() const = 0;
73 virtual void loopSample(
74 int64_t busyTime, int64_t idleTime) = 0;
77 // Helper class that sets and retrieves the EventBase associated with a given
78 // request via RequestContext. See Request.h for that mechanism.
79 class RequestEventBase : public RequestData {
81 static EventBase* get() {
82 auto data = dynamic_cast<RequestEventBase*>(
83 RequestContext::get()->getContextData(kContextDataName));
90 static void set(EventBase* eb) {
91 RequestContext::get()->setContextData(
93 std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
97 explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
99 static constexpr const char* kContextDataName{"EventBase"};
103 * This class is a wrapper for all asynchronous I/O processing functionality
105 * EventBase provides a main loop that notifies EventHandler callback objects
106 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
107 * when a specified timeout has expired. More complex, higher-level callback
108 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
110 * A EventBase object can only drive an event loop for a single thread. To
111 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
112 * thread per CPU, and use a separate EventBase for each thread.
114 * In general, most EventBase methods may only be called from the thread
115 * running the EventBase's loop. There are a few exceptions to this rule, for
116 * methods that are explicitly intended to allow communication with a
117 * EventBase from other threads. When it is safe to call a method from
118 * another thread it is explicitly listed in the method comments.
120 class EventBase : private boost::noncopyable,
121 public TimeoutManager,
122 public DrivableExecutor {
124 using Func = folly::Function<void()>;
127 * A callback interface to use with runInLoop()
129 * Derive from this class if you need to delay some code execution until the
130 * next iteration of the event loop. This allows you to schedule code to be
131 * invoked from the top-level of the loop, after your immediate callers have
134 * If a LoopCallback object is destroyed while it is scheduled to be run in
135 * the next loop iteration, it will automatically be cancelled.
139 virtual ~LoopCallback() = default;
141 virtual void runLoopCallback() noexcept = 0;
142 void cancelLoopCallback() {
146 bool isLoopCallbackScheduled() const {
147 return hook_.is_linked();
151 typedef boost::intrusive::list_member_hook<
152 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
156 typedef boost::intrusive::list<
158 boost::intrusive::member_hook<LoopCallback, ListHook,
159 &LoopCallback::hook_>,
160 boost::intrusive::constant_time_size<false> > List;
162 // EventBase needs access to LoopCallbackList (and therefore to hook_)
163 friend class EventBase;
164 std::shared_ptr<RequestContext> context_;
168 * Create a new EventBase object.
170 * @param enableTimeMeasurement Informs whether this event base should measure
171 * time. Disabling it would likely improve
172 * performance, but will disable some features
173 * that relies on time-measurement, including:
174 * observer, max latency and avg loop time.
176 explicit EventBase(bool enableTimeMeasurement = true);
179 * Create a new EventBase object that will use the specified libevent
180 * event_base object to drive the event loop.
182 * The EventBase will take ownership of this event_base, and will call
183 * event_base_free(evb) when the EventBase is destroyed.
185 * @param enableTimeMeasurement Informs whether this event base should measure
186 * time. Disabling it would likely improve
187 * performance, but will disable some features
188 * that relies on time-measurement, including:
189 * observer, max latency and avg loop time.
191 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
195 * Runs the event loop.
197 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
198 * and AsyncTimeout callbacks as their events become ready. loop() will
199 * only return when there are no more events remaining to process, or after
200 * terminateLoopSoon() has been called.
202 * loop() may be called again to restart event processing after a previous
203 * call to loop() or loopForever() has returned.
205 * Returns true if the loop completed normally (if it processed all
206 * outstanding requests, or if terminateLoopSoon() was called). If an error
207 * occurs waiting for events, false will be returned.
212 * Wait for some events to become active, run them, then return.
214 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
215 * are not any events to process.
217 * This is useful for callers that want to run the loop manually.
219 * Returns the same result as loop().
221 bool loopOnce(int flags = 0);
224 * Runs the event loop.
226 * loopForever() behaves like loop(), except that it keeps running even if
227 * when there are no more user-supplied EventHandlers or AsyncTimeouts
228 * registered. It will only return after terminateLoopSoon() has been
231 * This is useful for callers that want to wait for other threads to call
232 * runInEventBaseThread(), even when there are no other scheduled events.
234 * loopForever() may be called again to restart event processing after a
235 * previous call to loop() or loopForever() has returned.
237 * Throws a std::system_error if an error occurs.
242 * Causes the event loop to exit soon.
244 * This will cause an existing call to loop() or loopForever() to stop event
245 * processing and return, even if there are still events remaining to be
248 * It is safe to call terminateLoopSoon() from another thread to cause loop()
249 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
250 * may also be called from the loop thread itself (for example, a
251 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
252 * cause the loop to exit after the callback returns.) If the loop is not
253 * running, this will cause the next call to loop to terminate soon after
254 * starting. If a loop runs out of work (and so terminates on its own)
255 * concurrently with a call to terminateLoopSoon(), this may cause a race
258 * Note that the caller is responsible for ensuring that cleanup of all event
259 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
260 * exit even when there are pending events present, there may be remaining
261 * callbacks present waiting to be invoked. If the loop is later restarted
262 * pending events will continue to be processed normally, however if the
263 * EventBase is destroyed after calling terminateLoopSoon() it is the
264 * caller's responsibility to ensure that cleanup happens properly even if
265 * some outstanding events are never processed.
267 void terminateLoopSoon();
270 * Adds the given callback to a queue of things run after the current pass
271 * through the event loop completes. Note that if this callback calls
272 * runInLoop() the new callback won't be called until the main event loop
273 * has gone through a cycle.
275 * This method may only be called from the EventBase's thread. This
276 * essentially allows an event handler to schedule an additional callback to
277 * be invoked after it returns.
279 * Use runInEventBaseThread() to schedule functions from another thread.
281 * The thisIteration parameter makes this callback run in this loop
282 * iteration, instead of the next one, even if called from a
283 * runInLoop callback (normal io callbacks that call runInLoop will
284 * always run in this iteration). This was originally added to
285 * support detachEventBase, as a user callback may have called
286 * terminateLoopSoon(), but we want to make sure we detach. Also,
287 * detachEventBase almost always must be called from the base event
288 * loop to ensure the stack is unwound, since most users of
289 * EventBase are not thread safe.
291 * Ideally we would not need thisIteration, and instead just use
292 * runInLoop with loop() (instead of terminateLoopSoon).
294 void runInLoop(LoopCallback* callback, bool thisIteration = false);
297 * Convenience function to call runInLoop() with a std::function.
299 * This creates a LoopCallback object to wrap the std::function, and invoke
300 * the std::function when the loop callback fires. This is slightly more
301 * expensive than defining your own LoopCallback, but more convenient in
302 * areas that aren't performance sensitive where you just want to use
303 * std::bind. (std::bind is fairly slow on even by itself.)
305 * This method may only be called from the EventBase's thread. This
306 * essentially allows an event handler to schedule an additional callback to
307 * be invoked after it returns.
309 * Use runInEventBaseThread() to schedule functions from another thread.
311 void runInLoop(Func c, bool thisIteration = false);
314 * Adds the given callback to a queue of things run before destruction
315 * of current EventBase.
317 * This allows users of EventBase that run in it, but don't control it,
318 * to be notified before EventBase gets destructed.
320 * Note: will be called from the thread that invoked EventBase destructor,
321 * before the final run of loop callbacks.
323 void runOnDestruction(LoopCallback* callback);
326 * Adds the given callback to a queue of things run after the notification
327 * queue is drained before the destruction of current EventBase.
329 * Note: will be called from the thread that invoked EventBase destructor,
330 * after the final run of loop callbacks.
332 void runAfterDrain(Func cob);
335 * Adds a callback that will run immediately *before* the event loop.
336 * This is very similar to runInLoop(), but will not cause the loop to break:
337 * For example, this callback could be used to get loop times.
339 void runBeforeLoop(LoopCallback* callback);
342 * Run the specified function in the EventBase's thread.
344 * This method is thread-safe, and may be called from another thread.
346 * If runInEventBaseThread() is called when the EventBase loop is not
347 * running, the function call will be delayed until the next time the loop is
350 * If runInEventBaseThread() returns true the function has successfully been
351 * scheduled to run in the loop thread. However, if the loop is terminated
352 * (and never later restarted) before it has a chance to run the requested
353 * function, the function will be run upon the EventBase's destruction.
355 * If two calls to runInEventBaseThread() are made from the same thread, the
356 * functions will always be run in the order that they were scheduled.
357 * Ordering between functions scheduled from separate threads is not
360 * @param fn The function to run. The function must not throw any
362 * @param arg An argument to pass to the function.
364 * @return Returns true if the function was successfully scheduled, or false
365 * if there was an error scheduling the function.
367 template <typename T>
368 bool runInEventBaseThread(void (*fn)(T*), T* arg);
371 * Run the specified function in the EventBase's thread
373 * This version of runInEventBaseThread() takes a std::function object.
374 * Note that this is less efficient than the version that takes a plain
375 * function pointer and void* argument, as it has to allocate memory to copy
376 * the std::function object.
378 * If the loop is terminated (and never later restarted) before it has a
379 * chance to run the requested function, the function will be run upon the
380 * EventBase's destruction.
382 * The function must not throw any exceptions.
384 bool runInEventBaseThread(Func fn);
387 * Like runInEventBaseThread, but the caller waits for the callback to be
390 template <typename T>
391 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
394 * Like runInEventBaseThread, but the caller waits for the callback to be
397 bool runInEventBaseThreadAndWait(Func fn);
400 * Like runInEventBaseThreadAndWait, except if the caller is already in the
401 * event base thread, the functor is simply run inline.
403 template <typename T>
404 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
407 * Like runInEventBaseThreadAndWait, except if the caller is already in the
408 * event base thread, the functor is simply run inline.
410 bool runImmediatelyOrRunInEventBaseThreadAndWait(Func fn);
413 * Runs the given Cob at some time after the specified number of
414 * milliseconds. (No guarantees exactly when.)
416 * Throws a std::system_error if an error occurs.
420 uint32_t milliseconds,
421 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
424 * @see tryRunAfterDelay for more details
426 * @return true iff the cob was successfully registered.
429 bool tryRunAfterDelay(
431 uint32_t milliseconds,
432 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
435 * Set the maximum desired latency in us and provide a callback which will be
436 * called when that latency is exceeded.
437 * OBS: This functionality depends on time-measurement.
439 void setMaxLatency(int64_t maxLatency, Func maxLatencyCob) {
440 assert(enableTimeMeasurement_);
441 maxLatency_ = maxLatency;
442 maxLatencyCob_ = std::move(maxLatencyCob);
447 * Set smoothing coefficient for loop load average; # of milliseconds
448 * for exp(-1) (1/2.71828...) decay.
450 void setLoadAvgMsec(uint32_t ms);
453 * reset the load average to a desired value
455 void resetLoadAvg(double value = 0.0);
458 * Get the average loop time in microseconds (an exponentially-smoothed ave)
460 double getAvgLoopTime() const {
461 assert(enableTimeMeasurement_);
462 return avgLoopTime_.get();
466 * check if the event base loop is running.
468 bool isRunning() const {
469 return loopThread_.load(std::memory_order_relaxed) != 0;
473 * wait until the event loop starts (after starting the event loop thread).
475 void waitUntilRunning();
477 int getNotificationQueueSize() const;
479 void setMaxReadAtOnce(uint32_t maxAtOnce);
482 * Verify that current thread is the EventBase thread, if the EventBase is
485 bool isInEventBaseThread() const {
486 auto tid = loopThread_.load(std::memory_order_relaxed);
487 return tid == 0 || pthread_equal(tid, pthread_self());
490 bool inRunningEventBaseThread() const {
491 return pthread_equal(
492 loopThread_.load(std::memory_order_relaxed), pthread_self());
495 // --------- interface to underlying libevent base ------------
496 // Avoid using these functions if possible. These functions are not
497 // guaranteed to always be present if we ever provide alternative EventBase
498 // implementations that do not use libevent internally.
499 event_base* getLibeventBase() const { return evb_; }
500 static const char* getLibeventVersion();
501 static const char* getLibeventMethod();
504 * only EventHandler/AsyncTimeout subclasses and ourselves should
507 * This is used to mark the beginning of a new loop cycle by the
508 * first handler fired within that cycle.
511 bool bumpHandlingTime() override;
513 class SmoothLoopTime {
515 explicit SmoothLoopTime(uint64_t timeInterval)
516 : expCoeff_(-1.0/timeInterval)
518 , oldBusyLeftover_(0) {
519 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
522 void setTimeInterval(uint64_t timeInterval);
523 void reset(double value = 0.0);
525 void addSample(int64_t idle, int64_t busy);
531 void dampen(double factor) {
538 int64_t oldBusyLeftover_;
541 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
542 assert(enableTimeMeasurement_);
543 observer_ = observer;
546 const std::shared_ptr<EventBaseObserver>& getObserver() {
551 * Setup execution observation/instrumentation for every EventHandler
552 * executed in this EventBase.
554 * @param executionObserver EventHandle's execution observer.
556 void setExecutionObserver(ExecutionObserver* observer) {
557 executionObserver_ = observer;
561 * Gets the execution observer associated with this EventBase.
563 ExecutionObserver* getExecutionObserver() {
564 return executionObserver_;
568 * Set the name of the thread that runs this event base.
570 void setName(const std::string& name);
573 * Returns the name of the thread that runs this event base.
575 const std::string& getName();
577 /// Implements the Executor interface
578 void add(Cob fn) override {
579 // runInEventBaseThread() takes a const&,
580 // so no point in doing std::move here.
581 runInEventBaseThread(std::move(fn));
584 /// Implements the DrivableExecutor interface
585 void drive() override {
591 void attachTimeoutManager(AsyncTimeout* obj,
592 TimeoutManager::InternalEnum internal) override;
594 void detachTimeoutManager(AsyncTimeout* obj) override;
596 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
599 void cancelTimeout(AsyncTimeout* obj) override;
601 bool isInTimeoutManagerThread() override {
602 return isInEventBaseThread();
606 * Helper function that tells us whether we have already handled
607 * some event/timeout/callback in this loop iteration.
609 bool nothingHandledYet();
611 // --------- libevent callbacks (not for client use) ------------
613 static void runFunctionPtr(Cob* fn);
615 // small object used as a callback arg with enough info to execute the
616 // appropriate client-provided Cob
617 class CobTimeout : public AsyncTimeout {
619 CobTimeout(EventBase* b, Func c, TimeoutManager::InternalEnum in)
620 : AsyncTimeout(b, in), cob_(std::move(c)) {}
622 virtual void timeoutExpired() noexcept;
628 typedef boost::intrusive::list_member_hook<
629 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
633 typedef boost::intrusive::list<
635 boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
636 boost::intrusive::constant_time_size<false> > List;
639 typedef LoopCallback::List LoopCallbackList;
640 class FunctionRunner;
642 bool loopBody(int flags = 0);
644 // executes any callbacks queued by runInLoop(); returns false if none found
645 bool runLoopCallbacks(bool setContext = true);
647 void initNotificationQueue();
649 CobTimeout::List pendingCobTimeouts_;
651 LoopCallbackList loopCallbacks_;
652 LoopCallbackList runBeforeLoopCallbacks_;
653 LoopCallbackList onDestructionCallbacks_;
654 LoopCallbackList runAfterDrainCallbacks_;
656 // This will be null most of the time, but point to currentCallbacks
657 // if we are in the middle of running loop callbacks, such that
658 // runInLoop(..., true) will always run in the current loop
660 LoopCallbackList* runOnceCallbacks_;
662 // stop_ is set by terminateLoopSoon() and is used by the main loop
663 // to determine if it should exit
664 std::atomic<bool> stop_;
666 // The ID of the thread running the main loop.
667 // 0 if loop is not running.
668 // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
669 // even that atomic<pthread_t> is valid), but that's how it is
670 // everywhere (at least on Linux, FreeBSD, and OSX).
671 std::atomic<pthread_t> loopThread_;
673 // pointer to underlying event_base class doing the heavy lifting
676 // A notification queue for runInEventBaseThread() to use
677 // to send function requests to the EventBase thread.
678 std::unique_ptr<NotificationQueue<Func>> queue_;
679 std::unique_ptr<FunctionRunner> fnRunner_;
681 // limit for latency in microseconds (0 disables)
684 // exponentially-smoothed average loop time for latency-limiting
685 SmoothLoopTime avgLoopTime_;
687 // smoothed loop time used to invoke latency callbacks; differs from
688 // avgLoopTime_ in that it's scaled down after triggering a callback
689 // to reduce spamminess
690 SmoothLoopTime maxLatencyLoopTime_;
692 // callback called when latency limit is exceeded
695 // Enables/disables time measurements in loopBody(). if disabled, the
696 // following functionality that relies on time-measurement, will not
697 // be supported: avg loop time, observer and max latency.
698 const bool enableTimeMeasurement_;
700 // we'll wait this long before running deferred callbacks if the event
702 static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
704 // Wrap-around loop counter to detect beginning of each loop
705 uint64_t nextLoopCnt_;
706 uint64_t latestLoopCnt_;
709 // Observer to export counters
710 std::shared_ptr<EventBaseObserver> observer_;
711 uint32_t observerSampleCount_;
713 // EventHandler's execution observer.
714 ExecutionObserver* executionObserver_;
716 // Name of the thread running this EventBase
719 // allow runOnDestruction() to be called from any threads
720 std::mutex onDestructionCallbacksMutex_;
722 // allow runAfterDrain() to be called from any threads
723 std::mutex runAfterDrainCallbacksMutex_;
725 // see EventBaseLocal
726 friend class detail::EventBaseLocalBase;
727 template <typename T> friend class EventBaseLocal;
728 std::mutex localStorageMutex_;
729 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
730 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
736 * Define a small functor (2 pointers) and specialize
737 * std::__is_location_invariant so that std::function does not require
740 * std::function<void()> func = SmallFunctor{f, p};
742 * TODO(lucian): remove this hack once GCC <= 4.9 are deprecated.
743 * In GCC >= 5.0 just use a lambda like:
745 * std::function<void()> func = [=] { f(p); };
747 * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61909
750 struct SmallFunctor {
753 void operator()() { fn(p); }
758 template <typename T>
759 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
760 return runInEventBaseThread(detail::SmallFunctor<T>{fn, arg});
763 template <typename T>
764 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
765 return runInEventBaseThreadAndWait(detail::SmallFunctor<T>{fn, arg});
768 template <typename T>
769 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*),
771 return runImmediatelyOrRunInEventBaseThreadAndWait(
772 detail::SmallFunctor<T>{fn, arg});
777 FOLLY_NAMESPACE_STD_BEGIN
780 * GCC's libstdc++ uses __is_location_invariant to decide wether to
781 * use small object optimization and embed the functor's contents in
782 * the std::function object.
784 * (gcc 4.9) $ libstdc++-v3/include/std/functional
785 * template<typename _Tp>
786 * struct __is_location_invariant
787 * : integral_constant<bool, (is_pointer<_Tp>::value
788 * || is_member_pointer<_Tp>::value)>
791 * (gcc 5.0) $ libstdc++-v3/include/std/functional
793 * template<typename _Tp>
794 * struct __is_location_invariant
795 * : is_trivially_copyable<_Tp>::type
799 * NOTE: Forward declare so this doesn't break when using other
800 * standard libraries: it just wont have any effect.
802 template <typename T>
803 struct __is_location_invariant;
805 template <typename T>
806 struct __is_location_invariant<folly::detail::SmallFunctor<T>>
807 : public std::true_type {};
809 FOLLY_NAMESPACE_STD_END