2 * Copyright 2017 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>
36 #include <glog/logging.h>
38 #include <folly/CallOnce.h>
39 #include <folly/Executor.h>
40 #include <folly/Function.h>
41 #include <folly/Portability.h>
42 #include <folly/ScopeGuard.h>
43 #include <folly/experimental/ExecutionObserver.h>
44 #include <folly/futures/DrivableExecutor.h>
45 #include <folly/io/async/AsyncTimeout.h>
46 #include <folly/io/async/HHWheelTimer.h>
47 #include <folly/io/async/Request.h>
48 #include <folly/io/async/TimeoutManager.h>
49 #include <folly/portability/Event.h>
54 using Cob = Func; // defined in folly/Executor.h
55 template <typename MessageT>
56 class NotificationQueue;
59 class EventBaseLocalBase;
61 class EventBaseLocalBaseBase {
63 virtual void onEventBaseDestruction(EventBase& evb) = 0;
64 virtual ~EventBaseLocalBaseBase() = default;
70 class EventBaseObserver {
72 virtual ~EventBaseObserver() = default;
74 virtual uint32_t getSampleRate() const = 0;
76 virtual void loopSample(
77 int64_t busyTime, int64_t idleTime) = 0;
80 // Helper class that sets and retrieves the EventBase associated with a given
81 // request via RequestContext. See Request.h for that mechanism.
82 class RequestEventBase : public RequestData {
84 static EventBase* get() {
85 auto data = dynamic_cast<RequestEventBase*>(
86 RequestContext::get()->getContextData(kContextDataName));
93 static void set(EventBase* eb) {
94 RequestContext::get()->setContextData(
96 std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
100 explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
102 static constexpr const char* kContextDataName{"EventBase"};
105 class VirtualEventBase;
108 * This class is a wrapper for all asynchronous I/O processing functionality
110 * EventBase provides a main loop that notifies EventHandler callback objects
111 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
112 * when a specified timeout has expired. More complex, higher-level callback
113 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
115 * A EventBase object can only drive an event loop for a single thread. To
116 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
117 * thread per CPU, and use a separate EventBase for each thread.
119 * In general, most EventBase methods may only be called from the thread
120 * running the EventBase's loop. There are a few exceptions to this rule, for
121 * methods that are explicitly intended to allow communication with a
122 * EventBase from other threads. When it is safe to call a method from
123 * another thread it is explicitly listed in the method comments.
125 class EventBase : private boost::noncopyable,
126 public TimeoutManager,
127 public DrivableExecutor {
129 using Func = folly::Function<void()>;
130 using FuncRef = folly::FunctionRef<void()>;
133 * A callback interface to use with runInLoop()
135 * Derive from this class if you need to delay some code execution until the
136 * next iteration of the event loop. This allows you to schedule code to be
137 * invoked from the top-level of the loop, after your immediate callers have
140 * If a LoopCallback object is destroyed while it is scheduled to be run in
141 * the next loop iteration, it will automatically be cancelled.
144 : public boost::intrusive::list_base_hook<
145 boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
147 virtual ~LoopCallback() = default;
149 virtual void runLoopCallback() noexcept = 0;
150 void cancelLoopCallback() {
154 bool isLoopCallbackScheduled() const {
159 typedef boost::intrusive::list<
161 boost::intrusive::constant_time_size<false> > List;
163 // EventBase needs access to LoopCallbackList (and therefore to hook_)
164 friend class EventBase;
165 friend class VirtualEventBase;
166 std::shared_ptr<RequestContext> context_;
169 class FunctionLoopCallback : public LoopCallback {
171 explicit FunctionLoopCallback(Func&& function)
172 : function_(std::move(function)) {}
174 void runLoopCallback() noexcept override {
183 // Like FunctionLoopCallback, but saves one allocation. Use with caution.
185 // The caller is responsible for maintaining the lifetime of this callback
186 // until after the point at which the contained function is called.
187 class StackFunctionLoopCallback : public LoopCallback {
189 explicit StackFunctionLoopCallback(Func&& function)
190 : function_(std::move(function)) {}
191 void runLoopCallback() noexcept override {
192 Func(std::move(function_))();
200 * Create a new EventBase object.
202 * @param enableTimeMeasurement Informs whether this event base should measure
203 * time. Disabling it would likely improve
204 * performance, but will disable some features
205 * that relies on time-measurement, including:
206 * observer, max latency and avg loop time.
208 explicit EventBase(bool enableTimeMeasurement = true);
211 * Create a new EventBase object that will use the specified libevent
212 * event_base object to drive the event loop.
214 * The EventBase will take ownership of this event_base, and will call
215 * event_base_free(evb) when the EventBase is destroyed.
217 * @param enableTimeMeasurement Informs whether this event base should measure
218 * time. Disabling it would likely improve
219 * performance, but will disable some features
220 * that relies on time-measurement, including:
221 * observer, max latency and avg loop time.
223 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
224 ~EventBase() override;
227 * Runs the event loop.
229 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
230 * and AsyncTimeout callbacks as their events become ready. loop() will
231 * only return when there are no more events remaining to process, or after
232 * terminateLoopSoon() has been called.
234 * loop() may be called again to restart event processing after a previous
235 * call to loop() or loopForever() has returned.
237 * Returns true if the loop completed normally (if it processed all
238 * outstanding requests, or if terminateLoopSoon() was called). If an error
239 * occurs waiting for events, false will be returned.
244 * Wait for some events to become active, run them, then return.
246 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
247 * are not any events to process.
249 * This is useful for callers that want to run the loop manually.
251 * Returns the same result as loop().
253 bool loopOnce(int flags = 0);
256 * Runs the event loop.
258 * loopForever() behaves like loop(), except that it keeps running even if
259 * when there are no more user-supplied EventHandlers or AsyncTimeouts
260 * registered. It will only return after terminateLoopSoon() has been
263 * This is useful for callers that want to wait for other threads to call
264 * runInEventBaseThread(), even when there are no other scheduled events.
266 * loopForever() may be called again to restart event processing after a
267 * previous call to loop() or loopForever() has returned.
269 * Throws a std::system_error if an error occurs.
274 * Causes the event loop to exit soon.
276 * This will cause an existing call to loop() or loopForever() to stop event
277 * processing and return, even if there are still events remaining to be
280 * It is safe to call terminateLoopSoon() from another thread to cause loop()
281 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
282 * may also be called from the loop thread itself (for example, a
283 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
284 * cause the loop to exit after the callback returns.) If the loop is not
285 * running, this will cause the next call to loop to terminate soon after
286 * starting. If a loop runs out of work (and so terminates on its own)
287 * concurrently with a call to terminateLoopSoon(), this may cause a race
290 * Note that the caller is responsible for ensuring that cleanup of all event
291 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
292 * exit even when there are pending events present, there may be remaining
293 * callbacks present waiting to be invoked. If the loop is later restarted
294 * pending events will continue to be processed normally, however if the
295 * EventBase is destroyed after calling terminateLoopSoon() it is the
296 * caller's responsibility to ensure that cleanup happens properly even if
297 * some outstanding events are never processed.
299 void terminateLoopSoon();
302 * Adds the given callback to a queue of things run after the current pass
303 * through the event loop completes. Note that if this callback calls
304 * runInLoop() the new callback won't be called until the main event loop
305 * has gone through a cycle.
307 * This method may only be called from the EventBase's thread. This
308 * essentially allows an event handler to schedule an additional callback to
309 * be invoked after it returns.
311 * Use runInEventBaseThread() to schedule functions from another thread.
313 * The thisIteration parameter makes this callback run in this loop
314 * iteration, instead of the next one, even if called from a
315 * runInLoop callback (normal io callbacks that call runInLoop will
316 * always run in this iteration). This was originally added to
317 * support detachEventBase, as a user callback may have called
318 * terminateLoopSoon(), but we want to make sure we detach. Also,
319 * detachEventBase almost always must be called from the base event
320 * loop to ensure the stack is unwound, since most users of
321 * EventBase are not thread safe.
323 * Ideally we would not need thisIteration, and instead just use
324 * runInLoop with loop() (instead of terminateLoopSoon).
326 void runInLoop(LoopCallback* callback, bool thisIteration = false);
329 * Convenience function to call runInLoop() with a folly::Function.
331 * This creates a LoopCallback object to wrap the folly::Function, and invoke
332 * the folly::Function when the loop callback fires. This is slightly more
333 * expensive than defining your own LoopCallback, but more convenient in
334 * areas that aren't too performance sensitive.
336 * This method may only be called from the EventBase's thread. This
337 * essentially allows an event handler to schedule an additional callback to
338 * be invoked after it returns.
340 * Use runInEventBaseThread() to schedule functions from another thread.
342 void runInLoop(Func c, bool thisIteration = false);
345 * Adds the given callback to a queue of things run before destruction
346 * of current EventBase.
348 * This allows users of EventBase that run in it, but don't control it,
349 * to be notified before EventBase gets destructed.
351 * Note: will be called from the thread that invoked EventBase destructor,
352 * before the final run of loop callbacks.
354 void runOnDestruction(LoopCallback* callback);
357 * Adds a callback that will run immediately *before* the event loop.
358 * This is very similar to runInLoop(), but will not cause the loop to break:
359 * For example, this callback could be used to get loop times.
361 void runBeforeLoop(LoopCallback* callback);
364 * Run the specified function in the EventBase's thread.
366 * This method is thread-safe, and may be called from another thread.
368 * If runInEventBaseThread() is called when the EventBase loop is not
369 * running, the function call will be delayed until the next time the loop is
372 * If runInEventBaseThread() returns true the function has successfully been
373 * scheduled to run in the loop thread. However, if the loop is terminated
374 * (and never later restarted) before it has a chance to run the requested
375 * function, the function will be run upon the EventBase's destruction.
377 * If two calls to runInEventBaseThread() are made from the same thread, the
378 * functions will always be run in the order that they were scheduled.
379 * Ordering between functions scheduled from separate threads is not
382 * @param fn The function to run. The function must not throw any
384 * @param arg An argument to pass to the function.
386 * @return Returns true if the function was successfully scheduled, or false
387 * if there was an error scheduling the function.
389 template <typename T>
390 bool runInEventBaseThread(void (*fn)(T*), T* arg);
393 * Run the specified function in the EventBase's thread
395 * This version of runInEventBaseThread() takes a folly::Function object.
396 * Note that this may be less efficient than the version that takes a plain
397 * function pointer and void* argument, if moving the function is expensive
398 * (e.g., if it wraps a lambda which captures some values with expensive move
401 * If the loop is terminated (and never later restarted) before it has a
402 * chance to run the requested function, the function will be run upon the
403 * EventBase's destruction.
405 * The function must not throw any exceptions.
407 bool runInEventBaseThread(Func fn);
410 * Like runInEventBaseThread, but the caller waits for the callback to be
413 template <typename T>
414 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
417 * Like runInEventBaseThread, but the caller waits for the callback to be
420 bool runInEventBaseThreadAndWait(FuncRef fn);
423 * Like runInEventBaseThreadAndWait, except if the caller is already in the
424 * event base thread, the functor is simply run inline.
426 template <typename T>
427 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
430 * Like runInEventBaseThreadAndWait, except if the caller is already in the
431 * event base thread, the functor is simply run inline.
433 bool runImmediatelyOrRunInEventBaseThreadAndWait(FuncRef fn);
436 * Set the maximum desired latency in us and provide a callback which will be
437 * called when that latency is exceeded.
438 * OBS: This functionality depends on time-measurement.
440 void setMaxLatency(std::chrono::microseconds maxLatency, Func maxLatencyCob) {
441 assert(enableTimeMeasurement_);
442 maxLatency_ = maxLatency;
443 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(std::chrono::milliseconds 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) != std::thread::id();
473 * wait until the event loop starts (after starting the event loop thread).
475 void waitUntilRunning();
477 size_t 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 == std::thread::id() || tid == std::this_thread::get_id();
490 bool inRunningEventBaseThread() const {
491 return loopThread_.load(std::memory_order_relaxed) ==
492 std::this_thread::get_id();
496 * Equivalent to CHECK(isInEventBaseThread()) (and assert/DCHECK for
497 * dcheckIsInEventBaseThread), but it prints more information on
500 void checkIsInEventBaseThread() const;
501 void dcheckIsInEventBaseThread() const {
503 checkIsInEventBaseThread();
507 HHWheelTimer& timer() {
509 wheelTimer_ = HHWheelTimer::newTimer(this);
511 return *wheelTimer_.get();
514 // --------- interface to underlying libevent base ------------
515 // Avoid using these functions if possible. These functions are not
516 // guaranteed to always be present if we ever provide alternative EventBase
517 // implementations that do not use libevent internally.
518 event_base* getLibeventBase() const { return evb_; }
519 static const char* getLibeventVersion();
520 static const char* getLibeventMethod();
523 * only EventHandler/AsyncTimeout subclasses and ourselves should
526 * This is used to mark the beginning of a new loop cycle by the
527 * first handler fired within that cycle.
530 void bumpHandlingTime() final;
532 class SmoothLoopTime {
534 explicit SmoothLoopTime(std::chrono::microseconds timeInterval)
535 : expCoeff_(-1.0 / timeInterval.count()),
537 oldBusyLeftover_(0) {
538 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
541 void setTimeInterval(std::chrono::microseconds timeInterval);
542 void reset(double value = 0.0);
545 std::chrono::microseconds idle,
546 std::chrono::microseconds busy);
552 void dampen(double factor) {
559 std::chrono::microseconds oldBusyLeftover_;
562 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
563 assert(enableTimeMeasurement_);
564 observer_ = observer;
567 const std::shared_ptr<EventBaseObserver>& getObserver() {
572 * Setup execution observation/instrumentation for every EventHandler
573 * executed in this EventBase.
575 * @param executionObserver EventHandle's execution observer.
577 void setExecutionObserver(ExecutionObserver* observer) {
578 executionObserver_ = observer;
582 * Gets the execution observer associated with this EventBase.
584 ExecutionObserver* getExecutionObserver() {
585 return executionObserver_;
589 * Set the name of the thread that runs this event base.
591 void setName(const std::string& name);
594 * Returns the name of the thread that runs this event base.
596 const std::string& getName();
598 /// Implements the Executor interface
599 void add(Cob fn) override {
600 // runInEventBaseThread() takes a const&,
601 // so no point in doing std::move here.
602 runInEventBaseThread(std::move(fn));
605 /// Implements the DrivableExecutor interface
606 void drive() override {
607 ++loopKeepAliveCount_;
609 --loopKeepAliveCount_;
614 /// Returns you a handle which make loop() behave like loopForever() until
615 /// destroyed. loop() will return to its original behavior only when all
616 /// loop keep-alives are released.
617 KeepAlive getKeepAliveToken() override {
619 return makeKeepAlive();
623 void attachTimeoutManager(
625 TimeoutManager::InternalEnum internal) final;
627 void detachTimeoutManager(AsyncTimeout* obj) final;
629 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
632 void cancelTimeout(AsyncTimeout* obj) final;
634 bool isInTimeoutManagerThread() final {
635 return isInEventBaseThread();
638 // Returns a VirtualEventBase attached to this EventBase. Can be used to
639 // pass to APIs which expect VirtualEventBase. This VirtualEventBase will be
640 // destroyed together with the EventBase.
642 // Any number of VirtualEventBases instances may be independently constructed,
643 // which are backed by this EventBase. This method should be only used if you
644 // don't need to manage the life time of the VirtualEventBase used.
645 folly::VirtualEventBase& getVirtualEventBase();
648 void keepAliveAcquire() override {
649 if (inRunningEventBaseThread()) {
650 loopKeepAliveCount_++;
652 loopKeepAliveCountAtomic_.fetch_add(1, std::memory_order_relaxed);
656 void keepAliveRelease() override {
657 if (!inRunningEventBaseThread()) {
658 return add([=] { keepAliveRelease(); });
660 loopKeepAliveCount_--;
664 void applyLoopKeepAlive();
666 ssize_t loopKeepAliveCount();
669 * Helper function that tells us whether we have already handled
670 * some event/timeout/callback in this loop iteration.
672 bool nothingHandledYet() const noexcept;
674 typedef LoopCallback::List LoopCallbackList;
675 class FunctionRunner;
677 bool loopBody(int flags = 0);
679 // executes any callbacks queued by runInLoop(); returns false if none found
680 bool runLoopCallbacks();
682 void initNotificationQueue();
684 // should only be accessed through public getter
685 HHWheelTimer::UniquePtr wheelTimer_;
687 LoopCallbackList loopCallbacks_;
688 LoopCallbackList runBeforeLoopCallbacks_;
689 LoopCallbackList onDestructionCallbacks_;
691 // This will be null most of the time, but point to currentCallbacks
692 // if we are in the middle of running loop callbacks, such that
693 // runInLoop(..., true) will always run in the current loop
695 LoopCallbackList* runOnceCallbacks_;
697 // stop_ is set by terminateLoopSoon() and is used by the main loop
698 // to determine if it should exit
699 std::atomic<bool> stop_;
701 // The ID of the thread running the main loop.
702 // std::thread::id{} if loop is not running.
703 std::atomic<std::thread::id> loopThread_;
705 // pointer to underlying event_base class doing the heavy lifting
708 // A notification queue for runInEventBaseThread() to use
709 // to send function requests to the EventBase thread.
710 std::unique_ptr<NotificationQueue<Func>> queue_;
711 std::unique_ptr<FunctionRunner> fnRunner_;
712 ssize_t loopKeepAliveCount_{0};
713 std::atomic<ssize_t> loopKeepAliveCountAtomic_{0};
714 bool loopKeepAliveActive_{false};
716 // limit for latency in microseconds (0 disables)
717 std::chrono::microseconds maxLatency_;
719 // exponentially-smoothed average loop time for latency-limiting
720 SmoothLoopTime avgLoopTime_;
722 // smoothed loop time used to invoke latency callbacks; differs from
723 // avgLoopTime_ in that it's scaled down after triggering a callback
724 // to reduce spamminess
725 SmoothLoopTime maxLatencyLoopTime_;
727 // callback called when latency limit is exceeded
730 // Enables/disables time measurements in loopBody(). if disabled, the
731 // following functionality that relies on time-measurement, will not
732 // be supported: avg loop time, observer and max latency.
733 const bool enableTimeMeasurement_;
735 // Wrap-around loop counter to detect beginning of each loop
736 uint64_t nextLoopCnt_;
737 uint64_t latestLoopCnt_;
738 std::chrono::steady_clock::time_point startWork_;
739 // Prevent undefined behavior from invoking event_base_loop() reentrantly.
740 // This is needed since many projects use libevent-1.4, which lacks commit
741 // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
742 // https://github.com/libevent/libevent/.
743 bool invokingLoop_{false};
745 // Observer to export counters
746 std::shared_ptr<EventBaseObserver> observer_;
747 uint32_t observerSampleCount_;
749 // EventHandler's execution observer.
750 ExecutionObserver* executionObserver_;
752 // Name of the thread running this EventBase
755 // allow runOnDestruction() to be called from any threads
756 std::mutex onDestructionCallbacksMutex_;
758 // see EventBaseLocal
759 friend class detail::EventBaseLocalBase;
760 template <typename T> friend class EventBaseLocal;
761 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
762 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
764 folly::once_flag virtualEventBaseInitFlag_;
765 std::unique_ptr<VirtualEventBase> virtualEventBase_;
768 template <typename T>
769 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
770 return runInEventBaseThread([=] { fn(arg); });
773 template <typename T>
774 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
775 return runInEventBaseThreadAndWait([=] { fn(arg); });
778 template <typename T>
779 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
782 return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });