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>
37 #include <folly/CallOnce.h>
38 #include <folly/Executor.h>
39 #include <folly/Function.h>
40 #include <folly/Portability.h>
41 #include <folly/ScopeGuard.h>
42 #include <folly/experimental/ExecutionObserver.h>
43 #include <folly/futures/DrivableExecutor.h>
44 #include <folly/io/async/AsyncTimeout.h>
45 #include <folly/io/async/HHWheelTimer.h>
46 #include <folly/io/async/Request.h>
47 #include <folly/io/async/TimeoutManager.h>
48 #include <folly/portability/Event.h>
49 #include <glog/logging.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);
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();
495 HHWheelTimer& timer() {
497 wheelTimer_ = HHWheelTimer::newTimer(this);
499 return *wheelTimer_.get();
502 // --------- interface to underlying libevent base ------------
503 // Avoid using these functions if possible. These functions are not
504 // guaranteed to always be present if we ever provide alternative EventBase
505 // implementations that do not use libevent internally.
506 event_base* getLibeventBase() const { return evb_; }
507 static const char* getLibeventVersion();
508 static const char* getLibeventMethod();
511 * only EventHandler/AsyncTimeout subclasses and ourselves should
514 * This is used to mark the beginning of a new loop cycle by the
515 * first handler fired within that cycle.
518 void bumpHandlingTime() override final;
520 class SmoothLoopTime {
522 explicit SmoothLoopTime(std::chrono::microseconds timeInterval)
523 : expCoeff_(-1.0 / timeInterval.count()),
525 oldBusyLeftover_(0) {
526 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
529 void setTimeInterval(std::chrono::microseconds timeInterval);
530 void reset(double value = 0.0);
533 std::chrono::microseconds idle,
534 std::chrono::microseconds busy);
540 void dampen(double factor) {
547 std::chrono::microseconds oldBusyLeftover_;
550 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
551 assert(enableTimeMeasurement_);
552 observer_ = observer;
555 const std::shared_ptr<EventBaseObserver>& getObserver() {
560 * Setup execution observation/instrumentation for every EventHandler
561 * executed in this EventBase.
563 * @param executionObserver EventHandle's execution observer.
565 void setExecutionObserver(ExecutionObserver* observer) {
566 executionObserver_ = observer;
570 * Gets the execution observer associated with this EventBase.
572 ExecutionObserver* getExecutionObserver() {
573 return executionObserver_;
577 * Set the name of the thread that runs this event base.
579 void setName(const std::string& name);
582 * Returns the name of the thread that runs this event base.
584 const std::string& getName();
586 /// Implements the Executor interface
587 void add(Cob fn) override {
588 // runInEventBaseThread() takes a const&,
589 // so no point in doing std::move here.
590 runInEventBaseThread(std::move(fn));
593 /// Implements the DrivableExecutor interface
594 void drive() override {
595 // We can't use loopKeepAlive() here since LoopKeepAlive token can only be
596 // released inside a loop.
597 ++loopKeepAliveCount_;
599 --loopKeepAliveCount_;
604 /// Returns you a handle which make loop() behave like loopForever() until
605 /// destroyed. loop() will return to its original behavior only when all
606 /// loop keep-alives are released. Loop holder is safe to release only from
607 /// EventBase thread.
608 KeepAlive getKeepAliveToken() override {
609 if (inRunningEventBaseThread()) {
610 loopKeepAliveCount_++;
612 loopKeepAliveCountAtomic_.fetch_add(1, std::memory_order_relaxed);
614 return makeKeepAlive();
618 void attachTimeoutManager(
620 TimeoutManager::InternalEnum internal) override final;
622 void detachTimeoutManager(AsyncTimeout* obj) override final;
624 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
627 void cancelTimeout(AsyncTimeout* obj) override final;
629 bool isInTimeoutManagerThread() override final {
630 return isInEventBaseThread();
633 // Returns a VirtualEventBase attached to this EventBase. Can be used to
634 // pass to APIs which expect VirtualEventBase. This VirtualEventBase will be
635 // destroyed together with the EventBase.
637 // Any number of VirtualEventBases instances may be independently constructed,
638 // which are backed by this EventBase. This method should be only used if you
639 // don't need to manage the life time of the VirtualEventBase used.
640 folly::VirtualEventBase& getVirtualEventBase();
643 void keepAliveRelease() override {
644 DCHECK(isInEventBaseThread());
645 loopKeepAliveCount_--;
649 void applyLoopKeepAlive();
651 ssize_t loopKeepAliveCount();
654 * Helper function that tells us whether we have already handled
655 * some event/timeout/callback in this loop iteration.
657 bool nothingHandledYet() const noexcept;
659 typedef LoopCallback::List LoopCallbackList;
660 class FunctionRunner;
662 bool loopBody(int flags = 0);
664 // executes any callbacks queued by runInLoop(); returns false if none found
665 bool runLoopCallbacks();
667 void initNotificationQueue();
669 // should only be accessed through public getter
670 HHWheelTimer::UniquePtr wheelTimer_;
672 LoopCallbackList loopCallbacks_;
673 LoopCallbackList runBeforeLoopCallbacks_;
674 LoopCallbackList onDestructionCallbacks_;
676 // This will be null most of the time, but point to currentCallbacks
677 // if we are in the middle of running loop callbacks, such that
678 // runInLoop(..., true) will always run in the current loop
680 LoopCallbackList* runOnceCallbacks_;
682 // stop_ is set by terminateLoopSoon() and is used by the main loop
683 // to determine if it should exit
684 std::atomic<bool> stop_;
686 // The ID of the thread running the main loop.
687 // std::thread::id{} if loop is not running.
688 std::atomic<std::thread::id> loopThread_;
690 // pointer to underlying event_base class doing the heavy lifting
693 // A notification queue for runInEventBaseThread() to use
694 // to send function requests to the EventBase thread.
695 std::unique_ptr<NotificationQueue<Func>> queue_;
696 std::unique_ptr<FunctionRunner> fnRunner_;
697 ssize_t loopKeepAliveCount_{0};
698 std::atomic<ssize_t> loopKeepAliveCountAtomic_{0};
699 bool loopKeepAliveActive_{false};
701 // limit for latency in microseconds (0 disables)
702 std::chrono::microseconds maxLatency_;
704 // exponentially-smoothed average loop time for latency-limiting
705 SmoothLoopTime avgLoopTime_;
707 // smoothed loop time used to invoke latency callbacks; differs from
708 // avgLoopTime_ in that it's scaled down after triggering a callback
709 // to reduce spamminess
710 SmoothLoopTime maxLatencyLoopTime_;
712 // callback called when latency limit is exceeded
715 // Enables/disables time measurements in loopBody(). if disabled, the
716 // following functionality that relies on time-measurement, will not
717 // be supported: avg loop time, observer and max latency.
718 const bool enableTimeMeasurement_;
720 // Wrap-around loop counter to detect beginning of each loop
721 uint64_t nextLoopCnt_;
722 uint64_t latestLoopCnt_;
723 std::chrono::steady_clock::time_point startWork_;
724 // Prevent undefined behavior from invoking event_base_loop() reentrantly.
725 // This is needed since many projects use libevent-1.4, which lacks commit
726 // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
727 // https://github.com/libevent/libevent/.
728 bool invokingLoop_{false};
730 // Observer to export counters
731 std::shared_ptr<EventBaseObserver> observer_;
732 uint32_t observerSampleCount_;
734 // EventHandler's execution observer.
735 ExecutionObserver* executionObserver_;
737 // Name of the thread running this EventBase
740 // allow runOnDestruction() to be called from any threads
741 std::mutex onDestructionCallbacksMutex_;
743 // see EventBaseLocal
744 friend class detail::EventBaseLocalBase;
745 template <typename T> friend class EventBaseLocal;
746 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
747 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
749 folly::once_flag virtualEventBaseInitFlag_;
750 std::unique_ptr<VirtualEventBase> virtualEventBase_;
753 template <typename T>
754 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
755 return runInEventBaseThread([=] { fn(arg); });
758 template <typename T>
759 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
760 return runInEventBaseThreadAndWait([=] { fn(arg); });
763 template <typename T>
764 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
767 return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });