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/executors/DrivableExecutor.h>
44 #include <folly/experimental/ExecutionObserver.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>
53 using Cob = Func; // defined in folly/Executor.h
54 template <typename MessageT>
55 class NotificationQueue;
58 class EventBaseLocalBase;
60 class EventBaseLocalBaseBase {
62 virtual void onEventBaseDestruction(EventBase& evb) = 0;
63 virtual ~EventBaseLocalBaseBase() = default;
69 class EventBaseObserver {
71 virtual ~EventBaseObserver() = default;
73 virtual uint32_t getSampleRate() const = 0;
75 virtual void loopSample(
76 int64_t busyTime, int64_t idleTime) = 0;
79 // Helper class that sets and retrieves the EventBase associated with a given
80 // request via RequestContext. See Request.h for that mechanism.
81 class RequestEventBase : public RequestData {
83 static EventBase* get() {
84 auto data = dynamic_cast<RequestEventBase*>(
85 RequestContext::get()->getContextData(kContextDataName));
92 static void set(EventBase* eb) {
93 RequestContext::get()->setContextData(
95 std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
99 explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
101 static constexpr const char* kContextDataName{"EventBase"};
104 class VirtualEventBase;
107 * This class is a wrapper for all asynchronous I/O processing functionality
109 * EventBase provides a main loop that notifies EventHandler callback objects
110 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
111 * when a specified timeout has expired. More complex, higher-level callback
112 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
114 * A EventBase object can only drive an event loop for a single thread. To
115 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
116 * thread per CPU, and use a separate EventBase for each thread.
118 * In general, most EventBase methods may only be called from the thread
119 * running the EventBase's loop. There are a few exceptions to this rule, for
120 * methods that are explicitly intended to allow communication with a
121 * EventBase from other threads. When it is safe to call a method from
122 * another thread it is explicitly listed in the method comments.
124 class EventBase : private boost::noncopyable,
125 public TimeoutManager,
126 public DrivableExecutor {
128 using Func = folly::Function<void()>;
131 * A callback interface to use with runInLoop()
133 * Derive from this class if you need to delay some code execution until the
134 * next iteration of the event loop. This allows you to schedule code to be
135 * invoked from the top-level of the loop, after your immediate callers have
138 * If a LoopCallback object is destroyed while it is scheduled to be run in
139 * the next loop iteration, it will automatically be cancelled.
142 : public boost::intrusive::list_base_hook<
143 boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
145 virtual ~LoopCallback() = default;
147 virtual void runLoopCallback() noexcept = 0;
148 void cancelLoopCallback() {
152 bool isLoopCallbackScheduled() const {
157 typedef boost::intrusive::list<
159 boost::intrusive::constant_time_size<false> > List;
161 // EventBase needs access to LoopCallbackList (and therefore to hook_)
162 friend class EventBase;
163 friend class VirtualEventBase;
164 std::shared_ptr<RequestContext> context_;
167 class FunctionLoopCallback : public LoopCallback {
169 explicit FunctionLoopCallback(Func&& function)
170 : function_(std::move(function)) {}
172 void runLoopCallback() noexcept override {
181 // Like FunctionLoopCallback, but saves one allocation. Use with caution.
183 // The caller is responsible for maintaining the lifetime of this callback
184 // until after the point at which the contained function is called.
185 class StackFunctionLoopCallback : public LoopCallback {
187 explicit StackFunctionLoopCallback(Func&& function)
188 : function_(std::move(function)) {}
189 void runLoopCallback() noexcept override {
190 Func(std::move(function_))();
198 * Create a new EventBase object.
200 * @param enableTimeMeasurement Informs whether this event base should measure
201 * time. Disabling it would likely improve
202 * performance, but will disable some features
203 * that relies on time-measurement, including:
204 * observer, max latency and avg loop time.
206 explicit EventBase(bool enableTimeMeasurement = true);
209 * Create a new EventBase object that will use the specified libevent
210 * event_base object to drive the event loop.
212 * The EventBase will take ownership of this event_base, and will call
213 * event_base_free(evb) when the EventBase is destroyed.
215 * @param enableTimeMeasurement Informs whether this event base should measure
216 * time. Disabling it would likely improve
217 * performance, but will disable some features
218 * that relies on time-measurement, including:
219 * observer, max latency and avg loop time.
221 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
222 ~EventBase() override;
225 * Runs the event loop.
227 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
228 * and AsyncTimeout callbacks as their events become ready. loop() will
229 * only return when there are no more events remaining to process, or after
230 * terminateLoopSoon() has been called.
232 * loop() may be called again to restart event processing after a previous
233 * call to loop() or loopForever() has returned.
235 * Returns true if the loop completed normally (if it processed all
236 * outstanding requests, or if terminateLoopSoon() was called). If an error
237 * occurs waiting for events, false will be returned.
242 * Wait for some events to become active, run them, then return.
244 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
245 * are not any events to process.
247 * This is useful for callers that want to run the loop manually.
249 * Returns the same result as loop().
251 bool loopOnce(int flags = 0);
254 * Runs the event loop.
256 * loopForever() behaves like loop(), except that it keeps running even if
257 * when there are no more user-supplied EventHandlers or AsyncTimeouts
258 * registered. It will only return after terminateLoopSoon() has been
261 * This is useful for callers that want to wait for other threads to call
262 * runInEventBaseThread(), even when there are no other scheduled events.
264 * loopForever() may be called again to restart event processing after a
265 * previous call to loop() or loopForever() has returned.
267 * Throws a std::system_error if an error occurs.
272 * Causes the event loop to exit soon.
274 * This will cause an existing call to loop() or loopForever() to stop event
275 * processing and return, even if there are still events remaining to be
278 * It is safe to call terminateLoopSoon() from another thread to cause loop()
279 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
280 * may also be called from the loop thread itself (for example, a
281 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
282 * cause the loop to exit after the callback returns.) If the loop is not
283 * running, this will cause the next call to loop to terminate soon after
284 * starting. If a loop runs out of work (and so terminates on its own)
285 * concurrently with a call to terminateLoopSoon(), this may cause a race
288 * Note that the caller is responsible for ensuring that cleanup of all event
289 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
290 * exit even when there are pending events present, there may be remaining
291 * callbacks present waiting to be invoked. If the loop is later restarted
292 * pending events will continue to be processed normally, however if the
293 * EventBase is destroyed after calling terminateLoopSoon() it is the
294 * caller's responsibility to ensure that cleanup happens properly even if
295 * some outstanding events are never processed.
297 void terminateLoopSoon();
300 * Adds the given callback to a queue of things run after the current pass
301 * through the event loop completes. Note that if this callback calls
302 * runInLoop() the new callback won't be called until the main event loop
303 * has gone through a cycle.
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 * The thisIteration parameter makes this callback run in this loop
312 * iteration, instead of the next one, even if called from a
313 * runInLoop callback (normal io callbacks that call runInLoop will
314 * always run in this iteration). This was originally added to
315 * support detachEventBase, as a user callback may have called
316 * terminateLoopSoon(), but we want to make sure we detach. Also,
317 * detachEventBase almost always must be called from the base event
318 * loop to ensure the stack is unwound, since most users of
319 * EventBase are not thread safe.
321 * Ideally we would not need thisIteration, and instead just use
322 * runInLoop with loop() (instead of terminateLoopSoon).
324 void runInLoop(LoopCallback* callback, bool thisIteration = false);
327 * Convenience function to call runInLoop() with a folly::Function.
329 * This creates a LoopCallback object to wrap the folly::Function, and invoke
330 * the folly::Function when the loop callback fires. This is slightly more
331 * expensive than defining your own LoopCallback, but more convenient in
332 * areas that aren't too performance sensitive.
334 * This method may only be called from the EventBase's thread. This
335 * essentially allows an event handler to schedule an additional callback to
336 * be invoked after it returns.
338 * Use runInEventBaseThread() to schedule functions from another thread.
340 void runInLoop(Func c, bool thisIteration = false);
343 * Adds the given callback to a queue of things run before destruction
344 * of current EventBase.
346 * This allows users of EventBase that run in it, but don't control it,
347 * to be notified before EventBase gets destructed.
349 * Note: will be called from the thread that invoked EventBase destructor,
350 * before the final run of loop callbacks.
352 void runOnDestruction(LoopCallback* callback);
355 * Adds a callback that will run immediately *before* the event loop.
356 * This is very similar to runInLoop(), but will not cause the loop to break:
357 * For example, this callback could be used to get loop times.
359 void runBeforeLoop(LoopCallback* callback);
362 * Run the specified function in the EventBase's thread.
364 * This method is thread-safe, and may be called from another thread.
366 * If runInEventBaseThread() is called when the EventBase loop is not
367 * running, the function call will be delayed until the next time the loop is
370 * If runInEventBaseThread() returns true the function has successfully been
371 * scheduled to run in the loop thread. However, if the loop is terminated
372 * (and never later restarted) before it has a chance to run the requested
373 * function, the function will be run upon the EventBase's destruction.
375 * If two calls to runInEventBaseThread() are made from the same thread, the
376 * functions will always be run in the order that they were scheduled.
377 * Ordering between functions scheduled from separate threads is not
380 * @param fn The function to run. The function must not throw any
382 * @param arg An argument to pass to the function.
384 * @return Returns true if the function was successfully scheduled, or false
385 * if there was an error scheduling the function.
387 template <typename T>
388 bool runInEventBaseThread(void (*fn)(T*), T* arg);
391 * Run the specified function in the EventBase's thread
393 * This version of runInEventBaseThread() takes a folly::Function object.
394 * Note that this may be less efficient than the version that takes a plain
395 * function pointer and void* argument, if moving the function is expensive
396 * (e.g., if it wraps a lambda which captures some values with expensive move
399 * If the loop is terminated (and never later restarted) before it has a
400 * chance to run the requested function, the function will be run upon the
401 * EventBase's destruction.
403 * The function must not throw any exceptions.
405 bool runInEventBaseThread(Func fn);
408 * Like runInEventBaseThread, but the caller waits for the callback to be
411 template <typename T>
412 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
415 * Like runInEventBaseThread, but the caller waits for the callback to be
418 bool runInEventBaseThreadAndWait(Func fn);
421 * Like runInEventBaseThreadAndWait, except if the caller is already in the
422 * event base thread, the functor is simply run inline.
424 template <typename T>
425 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
428 * Like runInEventBaseThreadAndWait, except if the caller is already in the
429 * event base thread, the functor is simply run inline.
431 bool runImmediatelyOrRunInEventBaseThreadAndWait(Func fn);
434 * Set the maximum desired latency in us and provide a callback which will be
435 * called when that latency is exceeded.
436 * OBS: This functionality depends on time-measurement.
438 void setMaxLatency(std::chrono::microseconds maxLatency, Func maxLatencyCob) {
439 assert(enableTimeMeasurement_);
440 maxLatency_ = maxLatency;
441 maxLatencyCob_ = std::move(maxLatencyCob);
445 * Set smoothing coefficient for loop load average; # of milliseconds
446 * for exp(-1) (1/2.71828...) decay.
448 void setLoadAvgMsec(std::chrono::milliseconds ms);
451 * reset the load average to a desired value
453 void resetLoadAvg(double value = 0.0);
456 * Get the average loop time in microseconds (an exponentially-smoothed ave)
458 double getAvgLoopTime() const {
459 assert(enableTimeMeasurement_);
460 return avgLoopTime_.get();
464 * check if the event base loop is running.
466 bool isRunning() const {
467 return loopThread_.load(std::memory_order_relaxed) != std::thread::id();
471 * wait until the event loop starts (after starting the event loop thread).
473 void waitUntilRunning();
475 size_t getNotificationQueueSize() const;
477 void setMaxReadAtOnce(uint32_t maxAtOnce);
480 * Verify that current thread is the EventBase thread, if the EventBase is
483 bool isInEventBaseThread() const {
484 auto tid = loopThread_.load(std::memory_order_relaxed);
485 return tid == std::thread::id() || tid == std::this_thread::get_id();
488 bool inRunningEventBaseThread() const {
489 return loopThread_.load(std::memory_order_relaxed) ==
490 std::this_thread::get_id();
494 * Equivalent to CHECK(isInEventBaseThread()) (and assert/DCHECK for
495 * dcheckIsInEventBaseThread), but it prints more information on
498 void checkIsInEventBaseThread() const;
499 void dcheckIsInEventBaseThread() const {
501 checkIsInEventBaseThread();
505 HHWheelTimer& timer() {
507 wheelTimer_ = HHWheelTimer::newTimer(this);
509 return *wheelTimer_.get();
512 // --------- interface to underlying libevent base ------------
513 // Avoid using these functions if possible. These functions are not
514 // guaranteed to always be present if we ever provide alternative EventBase
515 // implementations that do not use libevent internally.
516 event_base* getLibeventBase() const { return evb_; }
517 static const char* getLibeventVersion();
518 static const char* getLibeventMethod();
521 * only EventHandler/AsyncTimeout subclasses and ourselves should
524 * This is used to mark the beginning of a new loop cycle by the
525 * first handler fired within that cycle.
528 void bumpHandlingTime() final;
530 class SmoothLoopTime {
532 explicit SmoothLoopTime(std::chrono::microseconds timeInterval)
533 : expCoeff_(-1.0 / timeInterval.count()),
535 oldBusyLeftover_(0) {
536 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
539 void setTimeInterval(std::chrono::microseconds timeInterval);
540 void reset(double value = 0.0);
543 std::chrono::microseconds idle,
544 std::chrono::microseconds busy);
550 void dampen(double factor) {
557 std::chrono::microseconds oldBusyLeftover_;
560 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
561 assert(enableTimeMeasurement_);
562 observer_ = observer;
565 const std::shared_ptr<EventBaseObserver>& getObserver() {
570 * Setup execution observation/instrumentation for every EventHandler
571 * executed in this EventBase.
573 * @param executionObserver EventHandle's execution observer.
575 void setExecutionObserver(ExecutionObserver* observer) {
576 executionObserver_ = observer;
580 * Gets the execution observer associated with this EventBase.
582 ExecutionObserver* getExecutionObserver() {
583 return executionObserver_;
587 * Set the name of the thread that runs this event base.
589 void setName(const std::string& name);
592 * Returns the name of the thread that runs this event base.
594 const std::string& getName();
596 /// Implements the Executor interface
597 void add(Cob fn) override {
598 // runInEventBaseThread() takes a const&,
599 // so no point in doing std::move here.
600 runInEventBaseThread(std::move(fn));
603 /// Implements the DrivableExecutor interface
604 void drive() override {
605 ++loopKeepAliveCount_;
607 --loopKeepAliveCount_;
612 /// Returns you a handle which make loop() behave like loopForever() until
613 /// destroyed. loop() will return to its original behavior only when all
614 /// loop keep-alives are released.
615 KeepAlive getKeepAliveToken() override {
617 return makeKeepAlive();
621 void attachTimeoutManager(
623 TimeoutManager::InternalEnum internal) final;
625 void detachTimeoutManager(AsyncTimeout* obj) final;
627 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
630 void cancelTimeout(AsyncTimeout* obj) final;
632 bool isInTimeoutManagerThread() final {
633 return isInEventBaseThread();
636 // Returns a VirtualEventBase attached to this EventBase. Can be used to
637 // pass to APIs which expect VirtualEventBase. This VirtualEventBase will be
638 // destroyed together with the EventBase.
640 // Any number of VirtualEventBases instances may be independently constructed,
641 // which are backed by this EventBase. This method should be only used if you
642 // don't need to manage the life time of the VirtualEventBase used.
643 folly::VirtualEventBase& getVirtualEventBase();
646 void keepAliveAcquire() override {
647 if (inRunningEventBaseThread()) {
648 loopKeepAliveCount_++;
650 loopKeepAliveCountAtomic_.fetch_add(1, std::memory_order_relaxed);
654 void keepAliveRelease() override {
655 if (!inRunningEventBaseThread()) {
656 return add([=] { keepAliveRelease(); });
658 loopKeepAliveCount_--;
662 void applyLoopKeepAlive();
664 ssize_t loopKeepAliveCount();
667 * Helper function that tells us whether we have already handled
668 * some event/timeout/callback in this loop iteration.
670 bool nothingHandledYet() const noexcept;
672 typedef LoopCallback::List LoopCallbackList;
673 class FunctionRunner;
675 bool loopBody(int flags = 0);
677 // executes any callbacks queued by runInLoop(); returns false if none found
678 bool runLoopCallbacks();
680 void initNotificationQueue();
682 // should only be accessed through public getter
683 HHWheelTimer::UniquePtr wheelTimer_;
685 LoopCallbackList loopCallbacks_;
686 LoopCallbackList runBeforeLoopCallbacks_;
687 LoopCallbackList onDestructionCallbacks_;
689 // This will be null most of the time, but point to currentCallbacks
690 // if we are in the middle of running loop callbacks, such that
691 // runInLoop(..., true) will always run in the current loop
693 LoopCallbackList* runOnceCallbacks_;
695 // stop_ is set by terminateLoopSoon() and is used by the main loop
696 // to determine if it should exit
697 std::atomic<bool> stop_;
699 // The ID of the thread running the main loop.
700 // std::thread::id{} if loop is not running.
701 std::atomic<std::thread::id> loopThread_;
703 // pointer to underlying event_base class doing the heavy lifting
706 // A notification queue for runInEventBaseThread() to use
707 // to send function requests to the EventBase thread.
708 std::unique_ptr<NotificationQueue<Func>> queue_;
709 std::unique_ptr<FunctionRunner> fnRunner_;
710 ssize_t loopKeepAliveCount_{0};
711 std::atomic<ssize_t> loopKeepAliveCountAtomic_{0};
712 bool loopKeepAliveActive_{false};
714 // limit for latency in microseconds (0 disables)
715 std::chrono::microseconds maxLatency_;
717 // exponentially-smoothed average loop time for latency-limiting
718 SmoothLoopTime avgLoopTime_;
720 // smoothed loop time used to invoke latency callbacks; differs from
721 // avgLoopTime_ in that it's scaled down after triggering a callback
722 // to reduce spamminess
723 SmoothLoopTime maxLatencyLoopTime_;
725 // callback called when latency limit is exceeded
728 // Enables/disables time measurements in loopBody(). if disabled, the
729 // following functionality that relies on time-measurement, will not
730 // be supported: avg loop time, observer and max latency.
731 const bool enableTimeMeasurement_;
733 // Wrap-around loop counter to detect beginning of each loop
734 uint64_t nextLoopCnt_;
735 uint64_t latestLoopCnt_;
736 std::chrono::steady_clock::time_point startWork_;
737 // Prevent undefined behavior from invoking event_base_loop() reentrantly.
738 // This is needed since many projects use libevent-1.4, which lacks commit
739 // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
740 // https://github.com/libevent/libevent/.
741 bool invokingLoop_{false};
743 // Observer to export counters
744 std::shared_ptr<EventBaseObserver> observer_;
745 uint32_t observerSampleCount_;
747 // EventHandler's execution observer.
748 ExecutionObserver* executionObserver_;
750 // Name of the thread running this EventBase
753 // allow runOnDestruction() to be called from any threads
754 std::mutex onDestructionCallbacksMutex_;
756 // see EventBaseLocal
757 friend class detail::EventBaseLocalBase;
758 template <typename T> friend class EventBaseLocal;
759 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
760 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
762 folly::once_flag virtualEventBaseInitFlag_;
763 std::unique_ptr<VirtualEventBase> virtualEventBase_;
766 template <typename T>
767 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
768 return runInEventBaseThread([=] { fn(arg); });
771 template <typename T>
772 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
773 return runInEventBaseThreadAndWait([=] { fn(arg); });
776 template <typename T>
777 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
780 return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });