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/Request.h>
44 #include <folly/io/async/TimeoutManager.h>
45 #include <folly/portability/PThread.h>
46 #include <glog/logging.h>
48 #include <event.h> // libevent
52 typedef std::function<void()> Cob;
53 template <typename MessageT>
54 class NotificationQueue;
57 class EventBaseLocalBase;
59 class EventBaseLocalBaseBase {
61 virtual void onEventBaseDestruction(EventBase& evb) = 0;
62 virtual ~EventBaseLocalBaseBase() = default;
68 class EventBaseObserver {
70 virtual ~EventBaseObserver() = default;
72 virtual uint32_t getSampleRate() const = 0;
74 virtual void loopSample(
75 int64_t busyTime, int64_t idleTime) = 0;
78 // Helper class that sets and retrieves the EventBase associated with a given
79 // request via RequestContext. See Request.h for that mechanism.
80 class RequestEventBase : public RequestData {
82 static EventBase* get() {
83 auto data = dynamic_cast<RequestEventBase*>(
84 RequestContext::get()->getContextData(kContextDataName));
91 static void set(EventBase* eb) {
92 RequestContext::get()->setContextData(
94 std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
98 explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
100 static constexpr const char* kContextDataName{"EventBase"};
104 * This class is a wrapper for all asynchronous I/O processing functionality
106 * EventBase provides a main loop that notifies EventHandler callback objects
107 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
108 * when a specified timeout has expired. More complex, higher-level callback
109 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
111 * A EventBase object can only drive an event loop for a single thread. To
112 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
113 * thread per CPU, and use a separate EventBase for each thread.
115 * In general, most EventBase methods may only be called from the thread
116 * running the EventBase's loop. There are a few exceptions to this rule, for
117 * methods that are explicitly intended to allow communication with a
118 * EventBase from other threads. When it is safe to call a method from
119 * another thread it is explicitly listed in the method comments.
121 class EventBase : private boost::noncopyable,
122 public TimeoutManager,
123 public DrivableExecutor {
125 using Func = folly::Function<void()>;
128 * A callback interface to use with runInLoop()
130 * Derive from this class if you need to delay some code execution until the
131 * next iteration of the event loop. This allows you to schedule code to be
132 * invoked from the top-level of the loop, after your immediate callers have
135 * If a LoopCallback object is destroyed while it is scheduled to be run in
136 * the next loop iteration, it will automatically be cancelled.
140 virtual ~LoopCallback() = default;
142 virtual void runLoopCallback() noexcept = 0;
143 void cancelLoopCallback() {
147 bool isLoopCallbackScheduled() const {
148 return hook_.is_linked();
152 typedef boost::intrusive::list_member_hook<
153 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
157 typedef boost::intrusive::list<
159 boost::intrusive::member_hook<LoopCallback, ListHook,
160 &LoopCallback::hook_>,
161 boost::intrusive::constant_time_size<false> > List;
163 // EventBase needs access to LoopCallbackList (and therefore to hook_)
164 friend class EventBase;
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 the given callback to a queue of things run after the notification
327 * queue is drained before the destruction of current EventBase.
329 * Note: will be called from the thread that invoked EventBase destructor,
330 * after the final run of loop callbacks.
332 void runAfterDrain(Func cob);
335 * Adds a callback that will run immediately *before* the event loop.
336 * This is very similar to runInLoop(), but will not cause the loop to break:
337 * For example, this callback could be used to get loop times.
339 void runBeforeLoop(LoopCallback* callback);
342 * Run the specified function in the EventBase's thread.
344 * This method is thread-safe, and may be called from another thread.
346 * If runInEventBaseThread() is called when the EventBase loop is not
347 * running, the function call will be delayed until the next time the loop is
350 * If runInEventBaseThread() returns true the function has successfully been
351 * scheduled to run in the loop thread. However, if the loop is terminated
352 * (and never later restarted) before it has a chance to run the requested
353 * function, the function will be run upon the EventBase's destruction.
355 * If two calls to runInEventBaseThread() are made from the same thread, the
356 * functions will always be run in the order that they were scheduled.
357 * Ordering between functions scheduled from separate threads is not
360 * @param fn The function to run. The function must not throw any
362 * @param arg An argument to pass to the function.
364 * @return Returns true if the function was successfully scheduled, or false
365 * if there was an error scheduling the function.
367 template <typename T>
368 bool runInEventBaseThread(void (*fn)(T*), T* arg);
371 * Run the specified function in the EventBase's thread
373 * This version of runInEventBaseThread() takes a folly::Function object.
374 * Note that this may be less efficient than the version that takes a plain
375 * function pointer and void* argument, if moving the function is expensive
376 * (e.g., if it wraps a lambda which captures some values with expensive move
379 * If the loop is terminated (and never later restarted) before it has a
380 * chance to run the requested function, the function will be run upon the
381 * EventBase's destruction.
383 * The function must not throw any exceptions.
385 bool runInEventBaseThread(Func fn);
388 * Like runInEventBaseThread, but the caller waits for the callback to be
391 template <typename T>
392 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
395 * Like runInEventBaseThread, but the caller waits for the callback to be
398 bool runInEventBaseThreadAndWait(Func fn);
401 * Like runInEventBaseThreadAndWait, except if the caller is already in the
402 * event base thread, the functor is simply run inline.
404 template <typename T>
405 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
408 * Like runInEventBaseThreadAndWait, except if the caller is already in the
409 * event base thread, the functor is simply run inline.
411 bool runImmediatelyOrRunInEventBaseThreadAndWait(Func fn);
414 * Runs the given Cob at some time after the specified number of
415 * milliseconds. (No guarantees exactly when.)
417 * Throws a std::system_error if an error occurs.
421 uint32_t milliseconds,
422 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
425 * @see tryRunAfterDelay for more details
427 * @return true iff the cob was successfully registered.
430 bool tryRunAfterDelay(
432 uint32_t milliseconds,
433 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
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(int64_t maxLatency, Func maxLatencyCob) {
441 assert(enableTimeMeasurement_);
442 maxLatency_ = maxLatency;
443 maxLatencyCob_ = std::move(maxLatencyCob);
448 * Set smoothing coefficient for loop load average; # of milliseconds
449 * for exp(-1) (1/2.71828...) decay.
451 void setLoadAvgMsec(uint32_t ms);
454 * reset the load average to a desired value
456 void resetLoadAvg(double value = 0.0);
459 * Get the average loop time in microseconds (an exponentially-smoothed ave)
461 double getAvgLoopTime() const {
462 assert(enableTimeMeasurement_);
463 return avgLoopTime_.get();
467 * check if the event base loop is running.
469 bool isRunning() const {
470 return loopThread_.load(std::memory_order_relaxed) != 0;
474 * wait until the event loop starts (after starting the event loop thread).
476 void waitUntilRunning();
478 int getNotificationQueueSize() const;
480 void setMaxReadAtOnce(uint32_t maxAtOnce);
483 * Verify that current thread is the EventBase thread, if the EventBase is
486 bool isInEventBaseThread() const {
487 auto tid = loopThread_.load(std::memory_order_relaxed);
488 return tid == 0 || pthread_equal(tid, pthread_self());
491 bool inRunningEventBaseThread() const {
492 return pthread_equal(
493 loopThread_.load(std::memory_order_relaxed), pthread_self());
496 // --------- interface to underlying libevent base ------------
497 // Avoid using these functions if possible. These functions are not
498 // guaranteed to always be present if we ever provide alternative EventBase
499 // implementations that do not use libevent internally.
500 event_base* getLibeventBase() const { return evb_; }
501 static const char* getLibeventVersion();
502 static const char* getLibeventMethod();
505 * only EventHandler/AsyncTimeout subclasses and ourselves should
508 * This is used to mark the beginning of a new loop cycle by the
509 * first handler fired within that cycle.
512 void bumpHandlingTime() override final;
514 class SmoothLoopTime {
516 explicit SmoothLoopTime(uint64_t timeInterval)
517 : expCoeff_(-1.0/timeInterval)
519 , oldBusyLeftover_(0) {
520 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
523 void setTimeInterval(uint64_t timeInterval);
524 void reset(double value = 0.0);
526 void addSample(int64_t idle, int64_t busy);
532 void dampen(double factor) {
539 int64_t oldBusyLeftover_;
542 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
543 assert(enableTimeMeasurement_);
544 observer_ = observer;
547 const std::shared_ptr<EventBaseObserver>& getObserver() {
552 * Setup execution observation/instrumentation for every EventHandler
553 * executed in this EventBase.
555 * @param executionObserver EventHandle's execution observer.
557 void setExecutionObserver(ExecutionObserver* observer) {
558 executionObserver_ = observer;
562 * Gets the execution observer associated with this EventBase.
564 ExecutionObserver* getExecutionObserver() {
565 return executionObserver_;
569 * Set the name of the thread that runs this event base.
571 void setName(const std::string& name);
574 * Returns the name of the thread that runs this event base.
576 const std::string& getName();
578 /// Implements the Executor interface
579 void add(Cob fn) override {
580 // runInEventBaseThread() takes a const&,
581 // so no point in doing std::move here.
582 runInEventBaseThread(std::move(fn));
585 /// Implements the DrivableExecutor interface
586 void drive() override {
590 struct LoopKeepAliveDeleter {
591 void operator()(EventBase* evb) {
592 DCHECK(evb->isInEventBaseThread());
593 evb->loopKeepAliveCount_--;
596 using LoopKeepAlive = std::unique_ptr<EventBase, LoopKeepAliveDeleter>;
598 /// Returns you a handle which make loop() behave like loopForever() until
599 /// destroyed. loop() will return to its original behavior only when all
600 /// loop keep-alives are released. Loop holder is safe to release only from
601 /// EventBase thread.
603 /// May return no op LoopKeepAlive if loopForever() is already running.
604 LoopKeepAlive loopKeepAlive() {
605 DCHECK(isInEventBaseThread());
606 loopKeepAliveCount_++;
607 return LoopKeepAlive(this);
612 void attachTimeoutManager(AsyncTimeout* obj,
613 TimeoutManager::InternalEnum internal) override;
615 void detachTimeoutManager(AsyncTimeout* obj) override;
617 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
620 void cancelTimeout(AsyncTimeout* obj) override;
622 bool isInTimeoutManagerThread() override final {
623 return isInEventBaseThread();
626 void applyLoopKeepAlive();
629 * Helper function that tells us whether we have already handled
630 * some event/timeout/callback in this loop iteration.
632 bool nothingHandledYet() const noexcept;
634 // small object used as a callback arg with enough info to execute the
635 // appropriate client-provided Cob
636 class CobTimeout : public AsyncTimeout {
638 CobTimeout(EventBase* b, Func c, TimeoutManager::InternalEnum in)
639 : AsyncTimeout(b, in), cob_(std::move(c)) {}
641 virtual void timeoutExpired() noexcept;
647 typedef boost::intrusive::list_member_hook<
648 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
652 typedef boost::intrusive::list<
654 boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
655 boost::intrusive::constant_time_size<false> > List;
658 typedef LoopCallback::List LoopCallbackList;
659 class FunctionRunner;
661 bool loopBody(int flags = 0);
663 // executes any callbacks queued by runInLoop(); returns false if none found
664 bool runLoopCallbacks(bool setContext = true);
666 void initNotificationQueue();
668 CobTimeout::List pendingCobTimeouts_;
670 LoopCallbackList loopCallbacks_;
671 LoopCallbackList runBeforeLoopCallbacks_;
672 LoopCallbackList onDestructionCallbacks_;
673 LoopCallbackList runAfterDrainCallbacks_;
675 // This will be null most of the time, but point to currentCallbacks
676 // if we are in the middle of running loop callbacks, such that
677 // runInLoop(..., true) will always run in the current loop
679 LoopCallbackList* runOnceCallbacks_;
681 // stop_ is set by terminateLoopSoon() and is used by the main loop
682 // to determine if it should exit
683 std::atomic<bool> stop_;
685 // The ID of the thread running the main loop.
686 // 0 if loop is not running.
687 // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
688 // even that atomic<pthread_t> is valid), but that's how it is
689 // everywhere (at least on Linux, FreeBSD, and OSX).
690 std::atomic<pthread_t> loopThread_;
692 // pointer to underlying event_base class doing the heavy lifting
695 // A notification queue for runInEventBaseThread() to use
696 // to send function requests to the EventBase thread.
697 std::unique_ptr<NotificationQueue<Func>> queue_;
698 std::unique_ptr<FunctionRunner> fnRunner_;
699 size_t loopKeepAliveCount_{0};
700 bool loopKeepAliveActive_{false};
702 // limit for latency in microseconds (0 disables)
705 // exponentially-smoothed average loop time for latency-limiting
706 SmoothLoopTime avgLoopTime_;
708 // smoothed loop time used to invoke latency callbacks; differs from
709 // avgLoopTime_ in that it's scaled down after triggering a callback
710 // to reduce spamminess
711 SmoothLoopTime maxLatencyLoopTime_;
713 // callback called when latency limit is exceeded
716 // Enables/disables time measurements in loopBody(). if disabled, the
717 // following functionality that relies on time-measurement, will not
718 // be supported: avg loop time, observer and max latency.
719 const bool enableTimeMeasurement_;
721 // we'll wait this long before running deferred callbacks if the event
723 static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
725 // Wrap-around loop counter to detect beginning of each loop
726 uint64_t nextLoopCnt_;
727 uint64_t latestLoopCnt_;
729 // Prevent undefined behavior from invoking event_base_loop() reentrantly.
730 // This is needed since many projects use libevent-1.4, which lacks commit
731 // b557b175c00dc462c1fce25f6e7dd67121d2c001 from
732 // https://github.com/libevent/libevent/.
733 bool invokingLoop_{false};
735 // Observer to export counters
736 std::shared_ptr<EventBaseObserver> observer_;
737 uint32_t observerSampleCount_;
739 // EventHandler's execution observer.
740 ExecutionObserver* executionObserver_;
742 // Name of the thread running this EventBase
745 // allow runOnDestruction() to be called from any threads
746 std::mutex onDestructionCallbacksMutex_;
748 // allow runAfterDrain() to be called from any threads
749 std::mutex runAfterDrainCallbacksMutex_;
751 // see EventBaseLocal
752 friend class detail::EventBaseLocalBase;
753 template <typename T> friend class EventBaseLocal;
754 std::mutex localStorageMutex_;
755 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
756 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
759 template <typename T>
760 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
761 return runInEventBaseThread([=] { fn(arg); });
764 template <typename T>
765 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
766 return runInEventBaseThreadAndWait([=] { fn(arg); });
769 template <typename T>
770 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
773 return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });