2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
30 #include <unordered_map>
31 #include <unordered_set>
34 #include <boost/intrusive/list.hpp>
35 #include <boost/utility.hpp>
37 #include <folly/Executor.h>
38 #include <folly/Function.h>
39 #include <folly/Portability.h>
40 #include <folly/ScopeGuard.h>
41 #include <folly/experimental/ExecutionObserver.h>
42 #include <folly/futures/DrivableExecutor.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/PThread.h>
48 #include <glog/logging.h>
50 #include <event.h> // libevent
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()>;
132 * A callback interface to use with runInLoop()
134 * Derive from this class if you need to delay some code execution until the
135 * next iteration of the event loop. This allows you to schedule code to be
136 * invoked from the top-level of the loop, after your immediate callers have
139 * If a LoopCallback object is destroyed while it is scheduled to be run in
140 * the next loop iteration, it will automatically be cancelled.
143 : public boost::intrusive::list_base_hook<
144 boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
146 virtual ~LoopCallback() = default;
148 virtual void runLoopCallback() noexcept = 0;
149 void cancelLoopCallback() {
153 bool isLoopCallbackScheduled() const {
158 typedef boost::intrusive::list<
160 boost::intrusive::constant_time_size<false> > List;
162 // EventBase needs access to LoopCallbackList (and therefore to hook_)
163 friend class EventBase;
164 friend class VirtualEventBase;
165 std::shared_ptr<RequestContext> context_;
169 * Create a new EventBase object.
171 * @param enableTimeMeasurement Informs whether this event base should measure
172 * time. Disabling it would likely improve
173 * performance, but will disable some features
174 * that relies on time-measurement, including:
175 * observer, max latency and avg loop time.
177 explicit EventBase(bool enableTimeMeasurement = true);
180 * Create a new EventBase object that will use the specified libevent
181 * event_base object to drive the event loop.
183 * The EventBase will take ownership of this event_base, and will call
184 * event_base_free(evb) when the EventBase is destroyed.
186 * @param enableTimeMeasurement Informs whether this event base should measure
187 * time. Disabling it would likely improve
188 * performance, but will disable some features
189 * that relies on time-measurement, including:
190 * observer, max latency and avg loop time.
192 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
196 * Runs the event loop.
198 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
199 * and AsyncTimeout callbacks as their events become ready. loop() will
200 * only return when there are no more events remaining to process, or after
201 * terminateLoopSoon() has been called.
203 * loop() may be called again to restart event processing after a previous
204 * call to loop() or loopForever() has returned.
206 * Returns true if the loop completed normally (if it processed all
207 * outstanding requests, or if terminateLoopSoon() was called). If an error
208 * occurs waiting for events, false will be returned.
213 * Wait for some events to become active, run them, then return.
215 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
216 * are not any events to process.
218 * This is useful for callers that want to run the loop manually.
220 * Returns the same result as loop().
222 bool loopOnce(int flags = 0);
225 * Runs the event loop.
227 * loopForever() behaves like loop(), except that it keeps running even if
228 * when there are no more user-supplied EventHandlers or AsyncTimeouts
229 * registered. It will only return after terminateLoopSoon() has been
232 * This is useful for callers that want to wait for other threads to call
233 * runInEventBaseThread(), even when there are no other scheduled events.
235 * loopForever() may be called again to restart event processing after a
236 * previous call to loop() or loopForever() has returned.
238 * Throws a std::system_error if an error occurs.
243 * Causes the event loop to exit soon.
245 * This will cause an existing call to loop() or loopForever() to stop event
246 * processing and return, even if there are still events remaining to be
249 * It is safe to call terminateLoopSoon() from another thread to cause loop()
250 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
251 * may also be called from the loop thread itself (for example, a
252 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
253 * cause the loop to exit after the callback returns.) If the loop is not
254 * running, this will cause the next call to loop to terminate soon after
255 * starting. If a loop runs out of work (and so terminates on its own)
256 * concurrently with a call to terminateLoopSoon(), this may cause a race
259 * Note that the caller is responsible for ensuring that cleanup of all event
260 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
261 * exit even when there are pending events present, there may be remaining
262 * callbacks present waiting to be invoked. If the loop is later restarted
263 * pending events will continue to be processed normally, however if the
264 * EventBase is destroyed after calling terminateLoopSoon() it is the
265 * caller's responsibility to ensure that cleanup happens properly even if
266 * some outstanding events are never processed.
268 void terminateLoopSoon();
271 * Adds the given callback to a queue of things run after the current pass
272 * through the event loop completes. Note that if this callback calls
273 * runInLoop() the new callback won't be called until the main event loop
274 * has gone through a cycle.
276 * This method may only be called from the EventBase's thread. This
277 * essentially allows an event handler to schedule an additional callback to
278 * be invoked after it returns.
280 * Use runInEventBaseThread() to schedule functions from another thread.
282 * The thisIteration parameter makes this callback run in this loop
283 * iteration, instead of the next one, even if called from a
284 * runInLoop callback (normal io callbacks that call runInLoop will
285 * always run in this iteration). This was originally added to
286 * support detachEventBase, as a user callback may have called
287 * terminateLoopSoon(), but we want to make sure we detach. Also,
288 * detachEventBase almost always must be called from the base event
289 * loop to ensure the stack is unwound, since most users of
290 * EventBase are not thread safe.
292 * Ideally we would not need thisIteration, and instead just use
293 * runInLoop with loop() (instead of terminateLoopSoon).
295 void runInLoop(LoopCallback* callback, bool thisIteration = false);
298 * Convenience function to call runInLoop() with a folly::Function.
300 * This creates a LoopCallback object to wrap the folly::Function, and invoke
301 * the folly::Function when the loop callback fires. This is slightly more
302 * expensive than defining your own LoopCallback, but more convenient in
303 * areas that aren't too performance sensitive.
305 * This method may only be called from the EventBase's thread. This
306 * essentially allows an event handler to schedule an additional callback to
307 * be invoked after it returns.
309 * Use runInEventBaseThread() to schedule functions from another thread.
311 void runInLoop(Func c, bool thisIteration = false);
314 * Adds the given callback to a queue of things run before destruction
315 * of current EventBase.
317 * This allows users of EventBase that run in it, but don't control it,
318 * to be notified before EventBase gets destructed.
320 * Note: will be called from the thread that invoked EventBase destructor,
321 * before the final run of loop callbacks.
323 void runOnDestruction(LoopCallback* callback);
326 * Adds a callback that will run immediately *before* the event loop.
327 * This is very similar to runInLoop(), but will not cause the loop to break:
328 * For example, this callback could be used to get loop times.
330 void runBeforeLoop(LoopCallback* callback);
333 * Run the specified function in the EventBase's thread.
335 * This method is thread-safe, and may be called from another thread.
337 * If runInEventBaseThread() is called when the EventBase loop is not
338 * running, the function call will be delayed until the next time the loop is
341 * If runInEventBaseThread() returns true the function has successfully been
342 * scheduled to run in the loop thread. However, if the loop is terminated
343 * (and never later restarted) before it has a chance to run the requested
344 * function, the function will be run upon the EventBase's destruction.
346 * If two calls to runInEventBaseThread() are made from the same thread, the
347 * functions will always be run in the order that they were scheduled.
348 * Ordering between functions scheduled from separate threads is not
351 * @param fn The function to run. The function must not throw any
353 * @param arg An argument to pass to the function.
355 * @return Returns true if the function was successfully scheduled, or false
356 * if there was an error scheduling the function.
358 template <typename T>
359 bool runInEventBaseThread(void (*fn)(T*), T* arg);
362 * Run the specified function in the EventBase's thread
364 * This version of runInEventBaseThread() takes a folly::Function object.
365 * Note that this may be less efficient than the version that takes a plain
366 * function pointer and void* argument, if moving the function is expensive
367 * (e.g., if it wraps a lambda which captures some values with expensive move
370 * If the loop is terminated (and never later restarted) before it has a
371 * chance to run the requested function, the function will be run upon the
372 * EventBase's destruction.
374 * The function must not throw any exceptions.
376 bool runInEventBaseThread(Func fn);
379 * Like runInEventBaseThread, but the caller waits for the callback to be
382 template <typename T>
383 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
386 * Like runInEventBaseThread, but the caller waits for the callback to be
389 bool runInEventBaseThreadAndWait(Func fn);
392 * Like runInEventBaseThreadAndWait, except if the caller is already in the
393 * event base thread, the functor is simply run inline.
395 template <typename T>
396 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
399 * Like runInEventBaseThreadAndWait, except if the caller is already in the
400 * event base thread, the functor is simply run inline.
402 bool runImmediatelyOrRunInEventBaseThreadAndWait(Func fn);
405 * Set the maximum desired latency in us and provide a callback which will be
406 * called when that latency is exceeded.
407 * OBS: This functionality depends on time-measurement.
409 void setMaxLatency(int64_t maxLatency, Func maxLatencyCob) {
410 assert(enableTimeMeasurement_);
411 maxLatency_ = maxLatency;
412 maxLatencyCob_ = std::move(maxLatencyCob);
416 * Set smoothing coefficient for loop load average; # of milliseconds
417 * for exp(-1) (1/2.71828...) decay.
419 void setLoadAvgMsec(uint32_t ms);
422 * reset the load average to a desired value
424 void resetLoadAvg(double value = 0.0);
427 * Get the average loop time in microseconds (an exponentially-smoothed ave)
429 double getAvgLoopTime() const {
430 assert(enableTimeMeasurement_);
431 return avgLoopTime_.get();
435 * check if the event base loop is running.
437 bool isRunning() const {
438 return loopThread_.load(std::memory_order_relaxed) != 0;
442 * wait until the event loop starts (after starting the event loop thread).
444 void waitUntilRunning();
446 int getNotificationQueueSize() const;
448 void setMaxReadAtOnce(uint32_t maxAtOnce);
451 * Verify that current thread is the EventBase thread, if the EventBase is
454 bool isInEventBaseThread() const {
455 auto tid = loopThread_.load(std::memory_order_relaxed);
456 return tid == 0 || pthread_equal(tid, pthread_self());
459 bool inRunningEventBaseThread() const {
460 return pthread_equal(
461 loopThread_.load(std::memory_order_relaxed), pthread_self());
464 HHWheelTimer& timer() {
466 wheelTimer_ = HHWheelTimer::newTimer(this);
468 return *wheelTimer_.get();
471 // --------- interface to underlying libevent base ------------
472 // Avoid using these functions if possible. These functions are not
473 // guaranteed to always be present if we ever provide alternative EventBase
474 // implementations that do not use libevent internally.
475 event_base* getLibeventBase() const { return evb_; }
476 static const char* getLibeventVersion();
477 static const char* getLibeventMethod();
480 * only EventHandler/AsyncTimeout subclasses and ourselves should
483 * This is used to mark the beginning of a new loop cycle by the
484 * first handler fired within that cycle.
487 void bumpHandlingTime() override final;
489 class SmoothLoopTime {
491 explicit SmoothLoopTime(uint64_t timeInterval)
492 : expCoeff_(-1.0/timeInterval)
494 , oldBusyLeftover_(0) {
495 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
498 void setTimeInterval(uint64_t timeInterval);
499 void reset(double value = 0.0);
501 void addSample(int64_t idle, int64_t busy);
507 void dampen(double factor) {
514 int64_t oldBusyLeftover_;
517 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
518 assert(enableTimeMeasurement_);
519 observer_ = observer;
522 const std::shared_ptr<EventBaseObserver>& getObserver() {
527 * Setup execution observation/instrumentation for every EventHandler
528 * executed in this EventBase.
530 * @param executionObserver EventHandle's execution observer.
532 void setExecutionObserver(ExecutionObserver* observer) {
533 executionObserver_ = observer;
537 * Gets the execution observer associated with this EventBase.
539 ExecutionObserver* getExecutionObserver() {
540 return executionObserver_;
544 * Set the name of the thread that runs this event base.
546 void setName(const std::string& name);
549 * Returns the name of the thread that runs this event base.
551 const std::string& getName();
553 /// Implements the Executor interface
554 void add(Cob fn) override {
555 // runInEventBaseThread() takes a const&,
556 // so no point in doing std::move here.
557 runInEventBaseThread(std::move(fn));
560 /// Implements the DrivableExecutor interface
561 void drive() override {
562 // We can't use loopKeepAlive() here since LoopKeepAlive token can only be
563 // released inside a loop.
564 ++loopKeepAliveCount_;
566 --loopKeepAliveCount_;
571 struct LoopKeepAliveDeleter {
572 void operator()(EventBase* evb) {
573 DCHECK(evb->isInEventBaseThread());
574 evb->loopKeepAliveCount_--;
577 using LoopKeepAlive = std::unique_ptr<EventBase, LoopKeepAliveDeleter>;
579 /// Returns you a handle which make loop() behave like loopForever() until
580 /// destroyed. loop() will return to its original behavior only when all
581 /// loop keep-alives are released. Loop holder is safe to release only from
582 /// EventBase thread.
584 /// May return no op LoopKeepAlive if loopForever() is already running.
585 LoopKeepAlive loopKeepAlive() {
586 DCHECK(isInEventBaseThread());
587 loopKeepAliveCount_++;
588 return LoopKeepAlive(this);
591 // Thread-safe version of loopKeepAlive()
592 LoopKeepAlive loopKeepAliveAtomic() {
593 if (inRunningEventBaseThread()) {
594 return loopKeepAlive();
596 loopKeepAliveCountAtomic_.fetch_add(1, std::memory_order_relaxed);
597 return LoopKeepAlive(this);
601 void attachTimeoutManager(
603 TimeoutManager::InternalEnum internal) override final;
605 void detachTimeoutManager(AsyncTimeout* obj) override final;
607 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
610 void cancelTimeout(AsyncTimeout* obj) override final;
612 bool isInTimeoutManagerThread() override final {
613 return isInEventBaseThread();
617 void applyLoopKeepAlive();
619 ssize_t loopKeepAliveCount();
622 * Helper function that tells us whether we have already handled
623 * some event/timeout/callback in this loop iteration.
625 bool nothingHandledYet() const noexcept;
627 typedef LoopCallback::List LoopCallbackList;
628 class FunctionRunner;
630 bool loopBody(int flags = 0);
632 // executes any callbacks queued by runInLoop(); returns false if none found
633 bool runLoopCallbacks();
635 void initNotificationQueue();
637 // should only be accessed through public getter
638 HHWheelTimer::UniquePtr wheelTimer_;
640 LoopCallbackList loopCallbacks_;
641 LoopCallbackList runBeforeLoopCallbacks_;
642 LoopCallbackList onDestructionCallbacks_;
644 // This will be null most of the time, but point to currentCallbacks
645 // if we are in the middle of running loop callbacks, such that
646 // runInLoop(..., true) will always run in the current loop
648 LoopCallbackList* runOnceCallbacks_;
650 // stop_ is set by terminateLoopSoon() and is used by the main loop
651 // to determine if it should exit
652 std::atomic<bool> stop_;
654 // The ID of the thread running the main loop.
655 // 0 if loop is not running.
656 // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
657 // even that atomic<pthread_t> is valid), but that's how it is
658 // everywhere (at least on Linux, FreeBSD, and OSX).
659 std::atomic<pthread_t> loopThread_;
661 // pointer to underlying event_base class doing the heavy lifting
664 // A notification queue for runInEventBaseThread() to use
665 // to send function requests to the EventBase thread.
666 std::unique_ptr<NotificationQueue<Func>> queue_;
667 std::unique_ptr<FunctionRunner> fnRunner_;
668 ssize_t loopKeepAliveCount_{0};
669 std::atomic<ssize_t> loopKeepAliveCountAtomic_{0};
670 bool loopKeepAliveActive_{false};
672 // limit for latency in microseconds (0 disables)
675 // exponentially-smoothed average loop time for latency-limiting
676 SmoothLoopTime avgLoopTime_;
678 // smoothed loop time used to invoke latency callbacks; differs from
679 // avgLoopTime_ in that it's scaled down after triggering a callback
680 // to reduce spamminess
681 SmoothLoopTime maxLatencyLoopTime_;
683 // callback called when latency limit is exceeded
686 // Enables/disables time measurements in loopBody(). if disabled, the
687 // following functionality that relies on time-measurement, will not
688 // be supported: avg loop time, observer and max latency.
689 const bool enableTimeMeasurement_;
691 // we'll wait this long before running deferred callbacks if the event
693 static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
695 // Wrap-around loop counter to detect beginning of each loop
696 uint64_t nextLoopCnt_;
697 uint64_t latestLoopCnt_;
699 // Prevent undefined behavior from invoking event_base_loop() reentrantly.
700 // This is needed since many projects use libevent-1.4, which lacks commit
701 // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
702 // https://github.com/libevent/libevent/.
703 bool invokingLoop_{false};
705 // Observer to export counters
706 std::shared_ptr<EventBaseObserver> observer_;
707 uint32_t observerSampleCount_;
709 // EventHandler's execution observer.
710 ExecutionObserver* executionObserver_;
712 // Name of the thread running this EventBase
715 // allow runOnDestruction() to be called from any threads
716 std::mutex onDestructionCallbacksMutex_;
718 // see EventBaseLocal
719 friend class detail::EventBaseLocalBase;
720 template <typename T> friend class EventBaseLocal;
721 std::mutex localStorageMutex_;
722 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
723 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
726 template <typename T>
727 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
728 return runInEventBaseThread([=] { fn(arg); });
731 template <typename T>
732 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
733 return runInEventBaseThreadAndWait([=] { fn(arg); });
736 template <typename T>
737 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
740 return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });