2 * Copyright 2017-present 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.
29 #include <unordered_map>
30 #include <unordered_set>
33 #include <boost/intrusive/list.hpp>
34 #include <boost/utility.hpp>
35 #include <glog/logging.h>
37 #include <folly/Executor.h>
38 #include <folly/Function.h>
39 #include <folly/Portability.h>
40 #include <folly/ScopeGuard.h>
41 #include <folly/executors/DrivableExecutor.h>
42 #include <folly/experimental/ExecutionObserver.h>
43 #include <folly/io/async/AsyncTimeout.h>
44 #include <folly/io/async/HHWheelTimer.h>
45 #include <folly/io/async/Request.h>
46 #include <folly/io/async/TimeoutManager.h>
47 #include <folly/portability/Event.h>
48 #include <folly/synchronization/CallOnce.h>
52 using Cob = Func; // defined in folly/Executor.h
53 template <typename MessageT>
54 class NotificationQueue;
57 class EventBaseLocalBase;
59 class EventBaseLocalBaseBase {
61 virtual void onEventBaseDestruction(EventBase& evb) = 0;
62 virtual ~EventBaseLocalBaseBase() = default;
68 class EventBaseObserver {
70 virtual ~EventBaseObserver() = default;
72 virtual uint32_t getSampleRate() const = 0;
74 virtual void loopSample(
75 int64_t busyTime, int64_t idleTime) = 0;
78 // Helper class that sets and retrieves the EventBase associated with a given
79 // request via RequestContext. See Request.h for that mechanism.
80 class RequestEventBase : public RequestData {
82 static EventBase* get() {
83 auto data = dynamic_cast<RequestEventBase*>(
84 RequestContext::get()->getContextData(kContextDataName));
91 static void set(EventBase* eb) {
92 RequestContext::get()->setContextData(
94 std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
97 bool hasCallback() override {
102 explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
104 static constexpr const char* kContextDataName{"EventBase"};
107 class VirtualEventBase;
110 * This class is a wrapper for all asynchronous I/O processing functionality
112 * EventBase provides a main loop that notifies EventHandler callback objects
113 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
114 * when a specified timeout has expired. More complex, higher-level callback
115 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
117 * A EventBase object can only drive an event loop for a single thread. To
118 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
119 * thread per CPU, and use a separate EventBase for each thread.
121 * In general, most EventBase methods may only be called from the thread
122 * running the EventBase's loop. There are a few exceptions to this rule, for
123 * methods that are explicitly intended to allow communication with a
124 * EventBase from other threads. When it is safe to call a method from
125 * another thread it is explicitly listed in the method comments.
127 class EventBase : private boost::noncopyable,
128 public TimeoutManager,
129 public DrivableExecutor {
131 using Func = folly::Function<void()>;
134 * A callback interface to use with runInLoop()
136 * Derive from this class if you need to delay some code execution until the
137 * next iteration of the event loop. This allows you to schedule code to be
138 * invoked from the top-level of the loop, after your immediate callers have
141 * If a LoopCallback object is destroyed while it is scheduled to be run in
142 * the next loop iteration, it will automatically be cancelled.
145 : public boost::intrusive::list_base_hook<
146 boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
148 virtual ~LoopCallback() = default;
150 virtual void runLoopCallback() noexcept = 0;
151 void cancelLoopCallback() {
156 bool isLoopCallbackScheduled() const {
161 typedef boost::intrusive::list<
163 boost::intrusive::constant_time_size<false> > List;
165 // EventBase needs access to LoopCallbackList (and therefore to hook_)
166 friend class EventBase;
167 friend class VirtualEventBase;
168 std::shared_ptr<RequestContext> context_;
171 class FunctionLoopCallback : public LoopCallback {
173 explicit FunctionLoopCallback(Func&& function)
174 : function_(std::move(function)) {}
176 void runLoopCallback() noexcept override {
185 // Like FunctionLoopCallback, but saves one allocation. Use with caution.
187 // The caller is responsible for maintaining the lifetime of this callback
188 // until after the point at which the contained function is called.
189 class StackFunctionLoopCallback : public LoopCallback {
191 explicit StackFunctionLoopCallback(Func&& function)
192 : function_(std::move(function)) {}
193 void runLoopCallback() noexcept override {
194 Func(std::move(function_))();
202 * Create a new EventBase object.
204 * Same as EventBase(true), which constructs an EventBase that measures time.
206 EventBase() : EventBase(true) {}
209 * Create a new EventBase object.
211 * @param enableTimeMeasurement Informs whether this event base should measure
212 * time. Disabling it would likely improve
213 * performance, but will disable some features
214 * that relies on time-measurement, including:
215 * observer, max latency and avg loop time.
217 explicit EventBase(bool enableTimeMeasurement);
220 * Create a new EventBase object that will use the specified libevent
221 * event_base object to drive the event loop.
223 * The EventBase will take ownership of this event_base, and will call
224 * event_base_free(evb) when the EventBase is destroyed.
226 * @param enableTimeMeasurement Informs whether this event base should measure
227 * time. Disabling it would likely improve
228 * performance, but will disable some features
229 * that relies on time-measurement, including:
230 * observer, max latency and avg loop time.
232 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
233 ~EventBase() override;
236 * Runs the event loop.
238 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
239 * and AsyncTimeout callbacks as their events become ready. loop() will
240 * only return when there are no more events remaining to process, or after
241 * terminateLoopSoon() has been called.
243 * loop() may be called again to restart event processing after a previous
244 * call to loop() or loopForever() has returned.
246 * Returns true if the loop completed normally (if it processed all
247 * outstanding requests, or if terminateLoopSoon() was called). If an error
248 * occurs waiting for events, false will be returned.
253 * Wait for some events to become active, run them, then return.
255 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
256 * are not any events to process.
258 * This is useful for callers that want to run the loop manually.
260 * Returns the same result as loop().
262 bool loopOnce(int flags = 0);
265 * Runs the event loop.
267 * loopForever() behaves like loop(), except that it keeps running even if
268 * when there are no more user-supplied EventHandlers or AsyncTimeouts
269 * registered. It will only return after terminateLoopSoon() has been
272 * This is useful for callers that want to wait for other threads to call
273 * runInEventBaseThread(), even when there are no other scheduled events.
275 * loopForever() may be called again to restart event processing after a
276 * previous call to loop() or loopForever() has returned.
278 * Throws a std::system_error if an error occurs.
283 * Causes the event loop to exit soon.
285 * This will cause an existing call to loop() or loopForever() to stop event
286 * processing and return, even if there are still events remaining to be
289 * It is safe to call terminateLoopSoon() from another thread to cause loop()
290 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
291 * may also be called from the loop thread itself (for example, a
292 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
293 * cause the loop to exit after the callback returns.) If the loop is not
294 * running, this will cause the next call to loop to terminate soon after
295 * starting. If a loop runs out of work (and so terminates on its own)
296 * concurrently with a call to terminateLoopSoon(), this may cause a race
299 * Note that the caller is responsible for ensuring that cleanup of all event
300 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
301 * exit even when there are pending events present, there may be remaining
302 * callbacks present waiting to be invoked. If the loop is later restarted
303 * pending events will continue to be processed normally, however if the
304 * EventBase is destroyed after calling terminateLoopSoon() it is the
305 * caller's responsibility to ensure that cleanup happens properly even if
306 * some outstanding events are never processed.
308 void terminateLoopSoon();
311 * Adds the given callback to a queue of things run after the current pass
312 * through the event loop completes. Note that if this callback calls
313 * runInLoop() the new callback won't be called until the main event loop
314 * has gone through a cycle.
316 * This method may only be called from the EventBase's thread. This
317 * essentially allows an event handler to schedule an additional callback to
318 * be invoked after it returns.
320 * Use runInEventBaseThread() to schedule functions from another thread.
322 * The thisIteration parameter makes this callback run in this loop
323 * iteration, instead of the next one, even if called from a
324 * runInLoop callback (normal io callbacks that call runInLoop will
325 * always run in this iteration). This was originally added to
326 * support detachEventBase, as a user callback may have called
327 * terminateLoopSoon(), but we want to make sure we detach. Also,
328 * detachEventBase almost always must be called from the base event
329 * loop to ensure the stack is unwound, since most users of
330 * EventBase are not thread safe.
332 * Ideally we would not need thisIteration, and instead just use
333 * runInLoop with loop() (instead of terminateLoopSoon).
335 void runInLoop(LoopCallback* callback, bool thisIteration = false);
338 * Convenience function to call runInLoop() with a folly::Function.
340 * This creates a LoopCallback object to wrap the folly::Function, and invoke
341 * the folly::Function when the loop callback fires. This is slightly more
342 * expensive than defining your own LoopCallback, but more convenient in
343 * areas that aren't too performance sensitive.
345 * This method may only be called from the EventBase's thread. This
346 * essentially allows an event handler to schedule an additional callback to
347 * be invoked after it returns.
349 * Use runInEventBaseThread() to schedule functions from another thread.
351 void runInLoop(Func c, bool thisIteration = false);
354 * Adds the given callback to a queue of things run before destruction
355 * of current EventBase.
357 * This allows users of EventBase that run in it, but don't control it,
358 * to be notified before EventBase gets destructed.
360 * Note: will be called from the thread that invoked EventBase destructor,
361 * before the final run of loop callbacks.
363 void runOnDestruction(LoopCallback* callback);
366 * Adds a callback that will run immediately *before* the event loop.
367 * This is very similar to runInLoop(), but will not cause the loop to break:
368 * For example, this callback could be used to get loop times.
370 void runBeforeLoop(LoopCallback* callback);
373 * Run the specified function in the EventBase's thread.
375 * This method is thread-safe, and may be called from another thread.
377 * If runInEventBaseThread() is called when the EventBase loop is not
378 * running, the function call will be delayed until the next time the loop is
381 * If runInEventBaseThread() returns true the function has successfully been
382 * scheduled to run in the loop thread. However, if the loop is terminated
383 * (and never later restarted) before it has a chance to run the requested
384 * function, the function will be run upon the EventBase's destruction.
386 * If two calls to runInEventBaseThread() are made from the same thread, the
387 * functions will always be run in the order that they were scheduled.
388 * Ordering between functions scheduled from separate threads is not
391 * @param fn The function to run. The function must not throw any
393 * @param arg An argument to pass to the function.
395 * @return Returns true if the function was successfully scheduled, or false
396 * if there was an error scheduling the function.
398 template <typename T>
399 bool runInEventBaseThread(void (*fn)(T*), T* arg);
402 * Run the specified function in the EventBase's thread
404 * This version of runInEventBaseThread() takes a folly::Function object.
405 * Note that this may be less efficient than the version that takes a plain
406 * function pointer and void* argument, if moving the function is expensive
407 * (e.g., if it wraps a lambda which captures some values with expensive move
410 * If the loop is terminated (and never later restarted) before it has a
411 * chance to run the requested function, the function will be run upon the
412 * EventBase's destruction.
414 * The function must not throw any exceptions.
416 bool runInEventBaseThread(Func fn);
419 * Like runInEventBaseThread, but the caller waits for the callback to be
422 template <typename T>
423 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
426 * Like runInEventBaseThread, but the caller waits for the callback to be
429 bool runInEventBaseThreadAndWait(Func fn);
432 * Like runInEventBaseThreadAndWait, except if the caller is already in the
433 * event base thread, the functor is simply run inline.
435 template <typename T>
436 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
439 * Like runInEventBaseThreadAndWait, except if the caller is already in the
440 * event base thread, the functor is simply run inline.
442 bool runImmediatelyOrRunInEventBaseThreadAndWait(Func fn);
445 * Set the maximum desired latency in us and provide a callback which will be
446 * called when that latency is exceeded.
447 * OBS: This functionality depends on time-measurement.
449 void setMaxLatency(std::chrono::microseconds maxLatency, Func maxLatencyCob) {
450 assert(enableTimeMeasurement_);
451 maxLatency_ = maxLatency;
452 maxLatencyCob_ = std::move(maxLatencyCob);
456 * Set smoothing coefficient for loop load average; # of milliseconds
457 * for exp(-1) (1/2.71828...) decay.
459 void setLoadAvgMsec(std::chrono::milliseconds ms);
462 * reset the load average to a desired value
464 void resetLoadAvg(double value = 0.0);
467 * Get the average loop time in microseconds (an exponentially-smoothed ave)
469 double getAvgLoopTime() const {
470 assert(enableTimeMeasurement_);
471 return avgLoopTime_.get();
475 * check if the event base loop is running.
477 bool isRunning() const {
478 return loopThread_.load(std::memory_order_relaxed) != std::thread::id();
482 * wait until the event loop starts (after starting the event loop thread).
484 void waitUntilRunning();
486 size_t getNotificationQueueSize() const;
488 void setMaxReadAtOnce(uint32_t maxAtOnce);
491 * Verify that current thread is the EventBase thread, if the EventBase is
494 bool isInEventBaseThread() const {
495 auto tid = loopThread_.load(std::memory_order_relaxed);
496 return tid == std::thread::id() || tid == std::this_thread::get_id();
499 bool inRunningEventBaseThread() const {
500 return loopThread_.load(std::memory_order_relaxed) ==
501 std::this_thread::get_id();
505 * Equivalent to CHECK(isInEventBaseThread()) (and assert/DCHECK for
506 * dcheckIsInEventBaseThread), but it prints more information on
509 void checkIsInEventBaseThread() const;
510 void dcheckIsInEventBaseThread() const {
512 checkIsInEventBaseThread();
516 HHWheelTimer& timer() {
518 wheelTimer_ = HHWheelTimer::newTimer(this);
520 return *wheelTimer_.get();
523 // --------- interface to underlying libevent base ------------
524 // Avoid using these functions if possible. These functions are not
525 // guaranteed to always be present if we ever provide alternative EventBase
526 // implementations that do not use libevent internally.
527 event_base* getLibeventBase() const { return evb_; }
528 static const char* getLibeventVersion();
529 static const char* getLibeventMethod();
532 * only EventHandler/AsyncTimeout subclasses and ourselves should
535 * This is used to mark the beginning of a new loop cycle by the
536 * first handler fired within that cycle.
539 void bumpHandlingTime() final;
541 class SmoothLoopTime {
543 explicit SmoothLoopTime(std::chrono::microseconds timeInterval)
544 : expCoeff_(-1.0 / timeInterval.count()),
546 oldBusyLeftover_(0) {
547 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
550 void setTimeInterval(std::chrono::microseconds timeInterval);
551 void reset(double value = 0.0);
554 std::chrono::microseconds idle,
555 std::chrono::microseconds busy);
561 void dampen(double factor) {
568 std::chrono::microseconds oldBusyLeftover_;
571 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
572 assert(enableTimeMeasurement_);
573 observer_ = observer;
576 const std::shared_ptr<EventBaseObserver>& getObserver() {
581 * Setup execution observation/instrumentation for every EventHandler
582 * executed in this EventBase.
584 * @param executionObserver EventHandle's execution observer.
586 void setExecutionObserver(ExecutionObserver* observer) {
587 executionObserver_ = observer;
591 * Gets the execution observer associated with this EventBase.
593 ExecutionObserver* getExecutionObserver() {
594 return executionObserver_;
598 * Set the name of the thread that runs this event base.
600 void setName(const std::string& name);
603 * Returns the name of the thread that runs this event base.
605 const std::string& getName();
607 /// Implements the Executor interface
608 void add(Cob fn) override {
609 // runInEventBaseThread() takes a const&,
610 // so no point in doing std::move here.
611 runInEventBaseThread(std::move(fn));
614 /// Implements the DrivableExecutor interface
615 void drive() override {
616 ++loopKeepAliveCount_;
618 --loopKeepAliveCount_;
623 /// Returns you a handle which make loop() behave like loopForever() until
624 /// destroyed. loop() will return to its original behavior only when all
625 /// loop keep-alives are released.
626 KeepAlive getKeepAliveToken() override {
628 return makeKeepAlive();
632 void attachTimeoutManager(
634 TimeoutManager::InternalEnum internal) final;
636 void detachTimeoutManager(AsyncTimeout* obj) final;
638 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
641 void cancelTimeout(AsyncTimeout* obj) final;
643 bool isInTimeoutManagerThread() final {
644 return isInEventBaseThread();
647 // Returns a VirtualEventBase attached to this EventBase. Can be used to
648 // pass to APIs which expect VirtualEventBase. This VirtualEventBase will be
649 // destroyed together with the EventBase.
651 // Any number of VirtualEventBases instances may be independently constructed,
652 // which are backed by this EventBase. This method should be only used if you
653 // don't need to manage the life time of the VirtualEventBase used.
654 folly::VirtualEventBase& getVirtualEventBase();
657 void keepAliveAcquire() override {
658 if (inRunningEventBaseThread()) {
659 loopKeepAliveCount_++;
661 loopKeepAliveCountAtomic_.fetch_add(1, std::memory_order_relaxed);
665 void keepAliveRelease() override {
666 if (!inRunningEventBaseThread()) {
667 return add([=] { keepAliveRelease(); });
669 loopKeepAliveCount_--;
673 void applyLoopKeepAlive();
675 ssize_t loopKeepAliveCount();
678 * Helper function that tells us whether we have already handled
679 * some event/timeout/callback in this loop iteration.
681 bool nothingHandledYet() const noexcept;
683 typedef LoopCallback::List LoopCallbackList;
684 class FunctionRunner;
686 bool loopBody(int flags = 0);
688 // executes any callbacks queued by runInLoop(); returns false if none found
689 bool runLoopCallbacks();
691 void initNotificationQueue();
693 // should only be accessed through public getter
694 HHWheelTimer::UniquePtr wheelTimer_;
696 LoopCallbackList loopCallbacks_;
697 LoopCallbackList runBeforeLoopCallbacks_;
698 LoopCallbackList onDestructionCallbacks_;
700 // This will be null most of the time, but point to currentCallbacks
701 // if we are in the middle of running loop callbacks, such that
702 // runInLoop(..., true) will always run in the current loop
704 LoopCallbackList* runOnceCallbacks_;
706 // stop_ is set by terminateLoopSoon() and is used by the main loop
707 // to determine if it should exit
708 std::atomic<bool> stop_;
710 // The ID of the thread running the main loop.
711 // std::thread::id{} if loop is not running.
712 std::atomic<std::thread::id> loopThread_;
714 // pointer to underlying event_base class doing the heavy lifting
717 // A notification queue for runInEventBaseThread() to use
718 // to send function requests to the EventBase thread.
719 std::unique_ptr<NotificationQueue<Func>> queue_;
720 std::unique_ptr<FunctionRunner> fnRunner_;
721 ssize_t loopKeepAliveCount_{0};
722 std::atomic<ssize_t> loopKeepAliveCountAtomic_{0};
723 bool loopKeepAliveActive_{false};
725 // limit for latency in microseconds (0 disables)
726 std::chrono::microseconds maxLatency_;
728 // exponentially-smoothed average loop time for latency-limiting
729 SmoothLoopTime avgLoopTime_;
731 // smoothed loop time used to invoke latency callbacks; differs from
732 // avgLoopTime_ in that it's scaled down after triggering a callback
733 // to reduce spamminess
734 SmoothLoopTime maxLatencyLoopTime_;
736 // callback called when latency limit is exceeded
739 // Enables/disables time measurements in loopBody(). if disabled, the
740 // following functionality that relies on time-measurement, will not
741 // be supported: avg loop time, observer and max latency.
742 const bool enableTimeMeasurement_;
744 // Wrap-around loop counter to detect beginning of each loop
745 uint64_t nextLoopCnt_;
746 uint64_t latestLoopCnt_;
747 std::chrono::steady_clock::time_point startWork_;
748 // Prevent undefined behavior from invoking event_base_loop() reentrantly.
749 // This is needed since many projects use libevent-1.4, which lacks commit
750 // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
751 // https://github.com/libevent/libevent/.
752 bool invokingLoop_{false};
754 // Observer to export counters
755 std::shared_ptr<EventBaseObserver> observer_;
756 uint32_t observerSampleCount_;
758 // EventHandler's execution observer.
759 ExecutionObserver* executionObserver_;
761 // Name of the thread running this EventBase
764 // allow runOnDestruction() to be called from any threads
765 std::mutex onDestructionCallbacksMutex_;
767 // see EventBaseLocal
768 friend class detail::EventBaseLocalBase;
769 template <typename T> friend class EventBaseLocal;
770 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
771 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
773 folly::once_flag virtualEventBaseInitFlag_;
774 std::unique_ptr<VirtualEventBase> virtualEventBase_;
777 template <typename T>
778 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
779 return runInEventBaseThread([=] { fn(arg); });
782 template <typename T>
783 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
784 return runInEventBaseThreadAndWait([=] { fn(arg); });
787 template <typename T>
788 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
791 return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });