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/experimental/ExecutionObserver.h>
41 #include <folly/futures/DrivableExecutor.h>
42 #include <folly/io/async/AsyncTimeout.h>
43 #include <folly/io/async/HHWheelTimer.h>
44 #include <folly/io/async/Request.h>
45 #include <folly/io/async/TimeoutManager.h>
46 #include <folly/portability/PThread.h>
47 #include <glog/logging.h>
49 #include <event.h> // libevent
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"};
105 * This class is a wrapper for all asynchronous I/O processing functionality
107 * EventBase provides a main loop that notifies EventHandler callback objects
108 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
109 * when a specified timeout has expired. More complex, higher-level callback
110 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
112 * A EventBase object can only drive an event loop for a single thread. To
113 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
114 * thread per CPU, and use a separate EventBase for each thread.
116 * In general, most EventBase methods may only be called from the thread
117 * running the EventBase's loop. There are a few exceptions to this rule, for
118 * methods that are explicitly intended to allow communication with a
119 * EventBase from other threads. When it is safe to call a method from
120 * another thread it is explicitly listed in the method comments.
122 class EventBase : private boost::noncopyable,
123 public TimeoutManager,
124 public DrivableExecutor {
126 using Func = folly::Function<void()>;
129 * A callback interface to use with runInLoop()
131 * Derive from this class if you need to delay some code execution until the
132 * next iteration of the event loop. This allows you to schedule code to be
133 * invoked from the top-level of the loop, after your immediate callers have
136 * If a LoopCallback object is destroyed while it is scheduled to be run in
137 * the next loop iteration, it will automatically be cancelled.
140 : public boost::intrusive::list_base_hook<
141 boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
143 virtual ~LoopCallback() = default;
145 virtual void runLoopCallback() noexcept = 0;
146 void cancelLoopCallback() {
150 bool isLoopCallbackScheduled() const {
155 typedef boost::intrusive::list<
157 boost::intrusive::constant_time_size<false> > List;
159 // EventBase needs access to LoopCallbackList (and therefore to hook_)
160 friend class EventBase;
161 std::shared_ptr<RequestContext> context_;
165 * Create a new EventBase object.
167 * @param enableTimeMeasurement Informs whether this event base should measure
168 * time. Disabling it would likely improve
169 * performance, but will disable some features
170 * that relies on time-measurement, including:
171 * observer, max latency and avg loop time.
173 explicit EventBase(bool enableTimeMeasurement = true);
176 * Create a new EventBase object that will use the specified libevent
177 * event_base object to drive the event loop.
179 * The EventBase will take ownership of this event_base, and will call
180 * event_base_free(evb) when the EventBase is destroyed.
182 * @param enableTimeMeasurement Informs whether this event base should measure
183 * time. Disabling it would likely improve
184 * performance, but will disable some features
185 * that relies on time-measurement, including:
186 * observer, max latency and avg loop time.
188 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
192 * Runs the event loop.
194 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
195 * and AsyncTimeout callbacks as their events become ready. loop() will
196 * only return when there are no more events remaining to process, or after
197 * terminateLoopSoon() has been called.
199 * loop() may be called again to restart event processing after a previous
200 * call to loop() or loopForever() has returned.
202 * Returns true if the loop completed normally (if it processed all
203 * outstanding requests, or if terminateLoopSoon() was called). If an error
204 * occurs waiting for events, false will be returned.
209 * Wait for some events to become active, run them, then return.
211 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
212 * are not any events to process.
214 * This is useful for callers that want to run the loop manually.
216 * Returns the same result as loop().
218 bool loopOnce(int flags = 0);
221 * Runs the event loop.
223 * loopForever() behaves like loop(), except that it keeps running even if
224 * when there are no more user-supplied EventHandlers or AsyncTimeouts
225 * registered. It will only return after terminateLoopSoon() has been
228 * This is useful for callers that want to wait for other threads to call
229 * runInEventBaseThread(), even when there are no other scheduled events.
231 * loopForever() may be called again to restart event processing after a
232 * previous call to loop() or loopForever() has returned.
234 * Throws a std::system_error if an error occurs.
239 * Causes the event loop to exit soon.
241 * This will cause an existing call to loop() or loopForever() to stop event
242 * processing and return, even if there are still events remaining to be
245 * It is safe to call terminateLoopSoon() from another thread to cause loop()
246 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
247 * may also be called from the loop thread itself (for example, a
248 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
249 * cause the loop to exit after the callback returns.) If the loop is not
250 * running, this will cause the next call to loop to terminate soon after
251 * starting. If a loop runs out of work (and so terminates on its own)
252 * concurrently with a call to terminateLoopSoon(), this may cause a race
255 * Note that the caller is responsible for ensuring that cleanup of all event
256 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
257 * exit even when there are pending events present, there may be remaining
258 * callbacks present waiting to be invoked. If the loop is later restarted
259 * pending events will continue to be processed normally, however if the
260 * EventBase is destroyed after calling terminateLoopSoon() it is the
261 * caller's responsibility to ensure that cleanup happens properly even if
262 * some outstanding events are never processed.
264 void terminateLoopSoon();
267 * Adds the given callback to a queue of things run after the current pass
268 * through the event loop completes. Note that if this callback calls
269 * runInLoop() the new callback won't be called until the main event loop
270 * has gone through a cycle.
272 * This method may only be called from the EventBase's thread. This
273 * essentially allows an event handler to schedule an additional callback to
274 * be invoked after it returns.
276 * Use runInEventBaseThread() to schedule functions from another thread.
278 * The thisIteration parameter makes this callback run in this loop
279 * iteration, instead of the next one, even if called from a
280 * runInLoop callback (normal io callbacks that call runInLoop will
281 * always run in this iteration). This was originally added to
282 * support detachEventBase, as a user callback may have called
283 * terminateLoopSoon(), but we want to make sure we detach. Also,
284 * detachEventBase almost always must be called from the base event
285 * loop to ensure the stack is unwound, since most users of
286 * EventBase are not thread safe.
288 * Ideally we would not need thisIteration, and instead just use
289 * runInLoop with loop() (instead of terminateLoopSoon).
291 void runInLoop(LoopCallback* callback, bool thisIteration = false);
294 * Convenience function to call runInLoop() with a folly::Function.
296 * This creates a LoopCallback object to wrap the folly::Function, and invoke
297 * the folly::Function when the loop callback fires. This is slightly more
298 * expensive than defining your own LoopCallback, but more convenient in
299 * areas that aren't too performance sensitive.
301 * This method may only be called from the EventBase's thread. This
302 * essentially allows an event handler to schedule an additional callback to
303 * be invoked after it returns.
305 * Use runInEventBaseThread() to schedule functions from another thread.
307 void runInLoop(Func c, bool thisIteration = false);
310 * Adds the given callback to a queue of things run before destruction
311 * of current EventBase.
313 * This allows users of EventBase that run in it, but don't control it,
314 * to be notified before EventBase gets destructed.
316 * Note: will be called from the thread that invoked EventBase destructor,
317 * before the final run of loop callbacks.
319 void runOnDestruction(LoopCallback* callback);
322 * Adds the given callback to a queue of things run after the notification
323 * queue is drained before the destruction of current EventBase.
325 * Note: will be called from the thread that invoked EventBase destructor,
326 * after the final run of loop callbacks.
328 void runAfterDrain(Func cob);
331 * Adds a callback that will run immediately *before* the event loop.
332 * This is very similar to runInLoop(), but will not cause the loop to break:
333 * For example, this callback could be used to get loop times.
335 void runBeforeLoop(LoopCallback* callback);
338 * Run the specified function in the EventBase's thread.
340 * This method is thread-safe, and may be called from another thread.
342 * If runInEventBaseThread() is called when the EventBase loop is not
343 * running, the function call will be delayed until the next time the loop is
346 * If runInEventBaseThread() returns true the function has successfully been
347 * scheduled to run in the loop thread. However, if the loop is terminated
348 * (and never later restarted) before it has a chance to run the requested
349 * function, the function will be run upon the EventBase's destruction.
351 * If two calls to runInEventBaseThread() are made from the same thread, the
352 * functions will always be run in the order that they were scheduled.
353 * Ordering between functions scheduled from separate threads is not
356 * @param fn The function to run. The function must not throw any
358 * @param arg An argument to pass to the function.
360 * @return Returns true if the function was successfully scheduled, or false
361 * if there was an error scheduling the function.
363 template <typename T>
364 bool runInEventBaseThread(void (*fn)(T*), T* arg);
367 * Run the specified function in the EventBase's thread
369 * This version of runInEventBaseThread() takes a folly::Function object.
370 * Note that this may be less efficient than the version that takes a plain
371 * function pointer and void* argument, if moving the function is expensive
372 * (e.g., if it wraps a lambda which captures some values with expensive move
375 * If the loop is terminated (and never later restarted) before it has a
376 * chance to run the requested function, the function will be run upon the
377 * EventBase's destruction.
379 * The function must not throw any exceptions.
381 bool runInEventBaseThread(Func fn);
384 * Like runInEventBaseThread, but the caller waits for the callback to be
387 template <typename T>
388 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
391 * Like runInEventBaseThread, but the caller waits for the callback to be
394 bool runInEventBaseThreadAndWait(Func fn);
397 * Like runInEventBaseThreadAndWait, except if the caller is already in the
398 * event base thread, the functor is simply run inline.
400 template <typename T>
401 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
404 * Like runInEventBaseThreadAndWait, except if the caller is already in the
405 * event base thread, the functor is simply run inline.
407 bool runImmediatelyOrRunInEventBaseThreadAndWait(Func fn);
410 * Runs the given Cob at some time after the specified number of
411 * milliseconds. (No guarantees exactly when.)
413 * Throws a std::system_error if an error occurs.
417 uint32_t milliseconds,
418 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
421 * @see tryRunAfterDelay for more details
423 * @return true iff the cob was successfully registered.
426 bool tryRunAfterDelay(
428 uint32_t milliseconds,
429 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
432 * Set the maximum desired latency in us and provide a callback which will be
433 * called when that latency is exceeded.
434 * OBS: This functionality depends on time-measurement.
436 void setMaxLatency(int64_t maxLatency, Func maxLatencyCob) {
437 assert(enableTimeMeasurement_);
438 maxLatency_ = maxLatency;
439 maxLatencyCob_ = std::move(maxLatencyCob);
444 * Set smoothing coefficient for loop load average; # of milliseconds
445 * for exp(-1) (1/2.71828...) decay.
447 void setLoadAvgMsec(uint32_t ms);
450 * reset the load average to a desired value
452 void resetLoadAvg(double value = 0.0);
455 * Get the average loop time in microseconds (an exponentially-smoothed ave)
457 double getAvgLoopTime() const {
458 assert(enableTimeMeasurement_);
459 return avgLoopTime_.get();
463 * check if the event base loop is running.
465 bool isRunning() const {
466 return loopThread_.load(std::memory_order_relaxed) != 0;
470 * wait until the event loop starts (after starting the event loop thread).
472 void waitUntilRunning();
474 int getNotificationQueueSize() const;
476 void setMaxReadAtOnce(uint32_t maxAtOnce);
479 * Verify that current thread is the EventBase thread, if the EventBase is
482 bool isInEventBaseThread() const {
483 auto tid = loopThread_.load(std::memory_order_relaxed);
484 return tid == 0 || pthread_equal(tid, pthread_self());
487 bool inRunningEventBaseThread() const {
488 return pthread_equal(
489 loopThread_.load(std::memory_order_relaxed), pthread_self());
492 HHWheelTimer& timer() {
494 wheelTimer_ = HHWheelTimer::newTimer(this);
496 return *wheelTimer_.get();
499 // --------- interface to underlying libevent base ------------
500 // Avoid using these functions if possible. These functions are not
501 // guaranteed to always be present if we ever provide alternative EventBase
502 // implementations that do not use libevent internally.
503 event_base* getLibeventBase() const { return evb_; }
504 static const char* getLibeventVersion();
505 static const char* getLibeventMethod();
508 * only EventHandler/AsyncTimeout subclasses and ourselves should
511 * This is used to mark the beginning of a new loop cycle by the
512 * first handler fired within that cycle.
515 void bumpHandlingTime() override final;
517 class SmoothLoopTime {
519 explicit SmoothLoopTime(uint64_t timeInterval)
520 : expCoeff_(-1.0/timeInterval)
522 , oldBusyLeftover_(0) {
523 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
526 void setTimeInterval(uint64_t timeInterval);
527 void reset(double value = 0.0);
529 void addSample(int64_t idle, int64_t busy);
535 void dampen(double factor) {
542 int64_t oldBusyLeftover_;
545 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
546 assert(enableTimeMeasurement_);
547 observer_ = observer;
550 const std::shared_ptr<EventBaseObserver>& getObserver() {
555 * Setup execution observation/instrumentation for every EventHandler
556 * executed in this EventBase.
558 * @param executionObserver EventHandle's execution observer.
560 void setExecutionObserver(ExecutionObserver* observer) {
561 executionObserver_ = observer;
565 * Gets the execution observer associated with this EventBase.
567 ExecutionObserver* getExecutionObserver() {
568 return executionObserver_;
572 * Set the name of the thread that runs this event base.
574 void setName(const std::string& name);
577 * Returns the name of the thread that runs this event base.
579 const std::string& getName();
581 /// Implements the Executor interface
582 void add(Cob fn) override {
583 // runInEventBaseThread() takes a const&,
584 // so no point in doing std::move here.
585 runInEventBaseThread(std::move(fn));
588 /// Implements the DrivableExecutor interface
589 void drive() override {
590 auto keepAlive = loopKeepAlive();
594 struct LoopKeepAliveDeleter {
595 void operator()(EventBase* evb) {
596 DCHECK(evb->isInEventBaseThread());
597 evb->loopKeepAliveCount_--;
600 using LoopKeepAlive = std::unique_ptr<EventBase, LoopKeepAliveDeleter>;
602 /// Returns you a handle which make loop() behave like loopForever() until
603 /// destroyed. loop() will return to its original behavior only when all
604 /// loop keep-alives are released. Loop holder is safe to release only from
605 /// EventBase thread.
607 /// May return no op LoopKeepAlive if loopForever() is already running.
608 LoopKeepAlive loopKeepAlive() {
609 DCHECK(isInEventBaseThread());
610 loopKeepAliveCount_++;
611 return LoopKeepAlive(this);
616 void attachTimeoutManager(AsyncTimeout* obj,
617 TimeoutManager::InternalEnum internal) override;
619 void detachTimeoutManager(AsyncTimeout* obj) override;
621 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
624 void cancelTimeout(AsyncTimeout* obj) override;
626 bool isInTimeoutManagerThread() override final {
627 return isInEventBaseThread();
630 void applyLoopKeepAlive();
633 * Helper function that tells us whether we have already handled
634 * some event/timeout/callback in this loop iteration.
636 bool nothingHandledYet() const noexcept;
638 // small object used as a callback arg with enough info to execute the
639 // appropriate client-provided Cob
640 class CobTimeout : public AsyncTimeout {
642 CobTimeout(EventBase* b, Func c, TimeoutManager::InternalEnum in)
643 : AsyncTimeout(b, in), cob_(std::move(c)) {}
645 virtual void timeoutExpired() noexcept;
651 typedef boost::intrusive::list_member_hook<
652 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
656 typedef boost::intrusive::list<
658 boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
659 boost::intrusive::constant_time_size<false> > List;
662 typedef LoopCallback::List LoopCallbackList;
663 class FunctionRunner;
665 bool loopBody(int flags = 0);
667 // executes any callbacks queued by runInLoop(); returns false if none found
668 bool runLoopCallbacks();
670 void initNotificationQueue();
672 // should only be accessed through public getter
673 HHWheelTimer::UniquePtr wheelTimer_;
675 CobTimeout::List pendingCobTimeouts_;
677 LoopCallbackList loopCallbacks_;
678 LoopCallbackList runBeforeLoopCallbacks_;
679 LoopCallbackList onDestructionCallbacks_;
680 LoopCallbackList runAfterDrainCallbacks_;
682 // This will be null most of the time, but point to currentCallbacks
683 // if we are in the middle of running loop callbacks, such that
684 // runInLoop(..., true) will always run in the current loop
686 LoopCallbackList* runOnceCallbacks_;
688 // stop_ is set by terminateLoopSoon() and is used by the main loop
689 // to determine if it should exit
690 std::atomic<bool> stop_;
692 // The ID of the thread running the main loop.
693 // 0 if loop is not running.
694 // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
695 // even that atomic<pthread_t> is valid), but that's how it is
696 // everywhere (at least on Linux, FreeBSD, and OSX).
697 std::atomic<pthread_t> loopThread_;
699 // pointer to underlying event_base class doing the heavy lifting
702 // A notification queue for runInEventBaseThread() to use
703 // to send function requests to the EventBase thread.
704 std::unique_ptr<NotificationQueue<Func>> queue_;
705 std::unique_ptr<FunctionRunner> fnRunner_;
706 size_t loopKeepAliveCount_{0};
707 bool loopKeepAliveActive_{false};
709 // limit for latency in microseconds (0 disables)
712 // exponentially-smoothed average loop time for latency-limiting
713 SmoothLoopTime avgLoopTime_;
715 // smoothed loop time used to invoke latency callbacks; differs from
716 // avgLoopTime_ in that it's scaled down after triggering a callback
717 // to reduce spamminess
718 SmoothLoopTime maxLatencyLoopTime_;
720 // callback called when latency limit is exceeded
723 // Enables/disables time measurements in loopBody(). if disabled, the
724 // following functionality that relies on time-measurement, will not
725 // be supported: avg loop time, observer and max latency.
726 const bool enableTimeMeasurement_;
728 // we'll wait this long before running deferred callbacks if the event
730 static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
732 // Wrap-around loop counter to detect beginning of each loop
733 uint64_t nextLoopCnt_;
734 uint64_t latestLoopCnt_;
736 // Prevent undefined behavior from invoking event_base_loop() reentrantly.
737 // This is needed since many projects use libevent-1.4, which lacks commit
738 // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
739 // https://github.com/libevent/libevent/.
740 bool invokingLoop_{false};
742 // Observer to export counters
743 std::shared_ptr<EventBaseObserver> observer_;
744 uint32_t observerSampleCount_;
746 // EventHandler's execution observer.
747 ExecutionObserver* executionObserver_;
749 // Name of the thread running this EventBase
752 // allow runOnDestruction() to be called from any threads
753 std::mutex onDestructionCallbacksMutex_;
755 // allow runAfterDrain() to be called from any threads
756 std::mutex runAfterDrainCallbacksMutex_;
758 // see EventBaseLocal
759 friend class detail::EventBaseLocalBase;
760 template <typename T> friend class EventBaseLocal;
761 std::mutex localStorageMutex_;
762 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
763 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
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); });