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 <glog/logging.h>
47 #include <event.h> // libevent
51 typedef std::function<void()> Cob;
52 template <typename MessageT>
53 class NotificationQueue;
56 class EventBaseLocalBase;
58 class EventBaseLocalBaseBase {
60 virtual void onEventBaseDestruction(EventBase& evb) = 0;
61 virtual ~EventBaseLocalBaseBase() = default;
67 class EventBaseObserver {
69 virtual ~EventBaseObserver() = default;
71 virtual uint32_t getSampleRate() const = 0;
73 virtual void loopSample(
74 int64_t busyTime, int64_t idleTime) = 0;
77 // Helper class that sets and retrieves the EventBase associated with a given
78 // request via RequestContext. See Request.h for that mechanism.
79 class RequestEventBase : public RequestData {
81 static EventBase* get() {
82 auto data = dynamic_cast<RequestEventBase*>(
83 RequestContext::get()->getContextData(kContextDataName));
90 static void set(EventBase* eb) {
91 RequestContext::get()->setContextData(
93 std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
97 explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
99 static constexpr const char* kContextDataName{"EventBase"};
103 * This class is a wrapper for all asynchronous I/O processing functionality
105 * EventBase provides a main loop that notifies EventHandler callback objects
106 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
107 * when a specified timeout has expired. More complex, higher-level callback
108 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
110 * A EventBase object can only drive an event loop for a single thread. To
111 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
112 * thread per CPU, and use a separate EventBase for each thread.
114 * In general, most EventBase methods may only be called from the thread
115 * running the EventBase's loop. There are a few exceptions to this rule, for
116 * methods that are explicitly intended to allow communication with a
117 * EventBase from other threads. When it is safe to call a method from
118 * another thread it is explicitly listed in the method comments.
120 class EventBase : private boost::noncopyable,
121 public TimeoutManager,
122 public DrivableExecutor {
124 using Func = folly::Function<void()>;
127 * A callback interface to use with runInLoop()
129 * Derive from this class if you need to delay some code execution until the
130 * next iteration of the event loop. This allows you to schedule code to be
131 * invoked from the top-level of the loop, after your immediate callers have
134 * If a LoopCallback object is destroyed while it is scheduled to be run in
135 * the next loop iteration, it will automatically be cancelled.
139 virtual ~LoopCallback() = default;
141 virtual void runLoopCallback() noexcept = 0;
142 void cancelLoopCallback() {
146 bool isLoopCallbackScheduled() const {
147 return hook_.is_linked();
151 typedef boost::intrusive::list_member_hook<
152 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
156 typedef boost::intrusive::list<
158 boost::intrusive::member_hook<LoopCallback, ListHook,
159 &LoopCallback::hook_>,
160 boost::intrusive::constant_time_size<false> > List;
162 // EventBase needs access to LoopCallbackList (and therefore to hook_)
163 friend class EventBase;
164 std::shared_ptr<RequestContext> context_;
168 * Create a new EventBase object.
170 * @param enableTimeMeasurement Informs whether this event base should measure
171 * time. Disabling it would likely improve
172 * performance, but will disable some features
173 * that relies on time-measurement, including:
174 * observer, max latency and avg loop time.
176 explicit EventBase(bool enableTimeMeasurement = true);
179 * Create a new EventBase object that will use the specified libevent
180 * event_base object to drive the event loop.
182 * The EventBase will take ownership of this event_base, and will call
183 * event_base_free(evb) when the EventBase is destroyed.
185 * @param enableTimeMeasurement Informs whether this event base should measure
186 * time. Disabling it would likely improve
187 * performance, but will disable some features
188 * that relies on time-measurement, including:
189 * observer, max latency and avg loop time.
191 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
195 * Runs the event loop.
197 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
198 * and AsyncTimeout callbacks as their events become ready. loop() will
199 * only return when there are no more events remaining to process, or after
200 * terminateLoopSoon() has been called.
202 * loop() may be called again to restart event processing after a previous
203 * call to loop() or loopForever() has returned.
205 * Returns true if the loop completed normally (if it processed all
206 * outstanding requests, or if terminateLoopSoon() was called). If an error
207 * occurs waiting for events, false will be returned.
212 * Wait for some events to become active, run them, then return.
214 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
215 * are not any events to process.
217 * This is useful for callers that want to run the loop manually.
219 * Returns the same result as loop().
221 bool loopOnce(int flags = 0);
224 * Runs the event loop.
226 * loopForever() behaves like loop(), except that it keeps running even if
227 * when there are no more user-supplied EventHandlers or AsyncTimeouts
228 * registered. It will only return after terminateLoopSoon() has been
231 * This is useful for callers that want to wait for other threads to call
232 * runInEventBaseThread(), even when there are no other scheduled events.
234 * loopForever() may be called again to restart event processing after a
235 * previous call to loop() or loopForever() has returned.
237 * Throws a std::system_error if an error occurs.
242 * Causes the event loop to exit soon.
244 * This will cause an existing call to loop() or loopForever() to stop event
245 * processing and return, even if there are still events remaining to be
248 * It is safe to call terminateLoopSoon() from another thread to cause loop()
249 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
250 * may also be called from the loop thread itself (for example, a
251 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
252 * cause the loop to exit after the callback returns.) If the loop is not
253 * running, this will cause the next call to loop to terminate soon after
254 * starting. If a loop runs out of work (and so terminates on its own)
255 * concurrently with a call to terminateLoopSoon(), this may cause a race
258 * Note that the caller is responsible for ensuring that cleanup of all event
259 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
260 * exit even when there are pending events present, there may be remaining
261 * callbacks present waiting to be invoked. If the loop is later restarted
262 * pending events will continue to be processed normally, however if the
263 * EventBase is destroyed after calling terminateLoopSoon() it is the
264 * caller's responsibility to ensure that cleanup happens properly even if
265 * some outstanding events are never processed.
267 void terminateLoopSoon();
270 * Adds the given callback to a queue of things run after the current pass
271 * through the event loop completes. Note that if this callback calls
272 * runInLoop() the new callback won't be called until the main event loop
273 * has gone through a cycle.
275 * This method may only be called from the EventBase's thread. This
276 * essentially allows an event handler to schedule an additional callback to
277 * be invoked after it returns.
279 * Use runInEventBaseThread() to schedule functions from another thread.
281 * The thisIteration parameter makes this callback run in this loop
282 * iteration, instead of the next one, even if called from a
283 * runInLoop callback (normal io callbacks that call runInLoop will
284 * always run in this iteration). This was originally added to
285 * support detachEventBase, as a user callback may have called
286 * terminateLoopSoon(), but we want to make sure we detach. Also,
287 * detachEventBase almost always must be called from the base event
288 * loop to ensure the stack is unwound, since most users of
289 * EventBase are not thread safe.
291 * Ideally we would not need thisIteration, and instead just use
292 * runInLoop with loop() (instead of terminateLoopSoon).
294 void runInLoop(LoopCallback* callback, bool thisIteration = false);
297 * Convenience function to call runInLoop() with a folly::Function.
299 * This creates a LoopCallback object to wrap the folly::Function, and invoke
300 * the folly::Function when the loop callback fires. This is slightly more
301 * expensive than defining your own LoopCallback, but more convenient in
302 * areas that aren't too performance sensitive.
304 * This method may only be called from the EventBase's thread. This
305 * essentially allows an event handler to schedule an additional callback to
306 * be invoked after it returns.
308 * Use runInEventBaseThread() to schedule functions from another thread.
310 void runInLoop(Func c, bool thisIteration = false);
313 * Adds the given callback to a queue of things run before destruction
314 * of current EventBase.
316 * This allows users of EventBase that run in it, but don't control it,
317 * to be notified before EventBase gets destructed.
319 * Note: will be called from the thread that invoked EventBase destructor,
320 * before the final run of loop callbacks.
322 void runOnDestruction(LoopCallback* callback);
325 * Adds the given callback to a queue of things run after the notification
326 * queue is drained before the destruction of current EventBase.
328 * Note: will be called from the thread that invoked EventBase destructor,
329 * after the final run of loop callbacks.
331 void runAfterDrain(Func cob);
334 * Adds a callback that will run immediately *before* the event loop.
335 * This is very similar to runInLoop(), but will not cause the loop to break:
336 * For example, this callback could be used to get loop times.
338 void runBeforeLoop(LoopCallback* callback);
341 * Run the specified function in the EventBase's thread.
343 * This method is thread-safe, and may be called from another thread.
345 * If runInEventBaseThread() is called when the EventBase loop is not
346 * running, the function call will be delayed until the next time the loop is
349 * If runInEventBaseThread() returns true the function has successfully been
350 * scheduled to run in the loop thread. However, if the loop is terminated
351 * (and never later restarted) before it has a chance to run the requested
352 * function, the function will be run upon the EventBase's destruction.
354 * If two calls to runInEventBaseThread() are made from the same thread, the
355 * functions will always be run in the order that they were scheduled.
356 * Ordering between functions scheduled from separate threads is not
359 * @param fn The function to run. The function must not throw any
361 * @param arg An argument to pass to the function.
363 * @return Returns true if the function was successfully scheduled, or false
364 * if there was an error scheduling the function.
366 template <typename T>
367 bool runInEventBaseThread(void (*fn)(T*), T* arg);
370 * Run the specified function in the EventBase's thread
372 * This version of runInEventBaseThread() takes a folly::Function object.
373 * Note that this may be less efficient than the version that takes a plain
374 * function pointer and void* argument, if moving the function is expensive
375 * (e.g., if it wraps a lambda which captures some values with expensive move
378 * If the loop is terminated (and never later restarted) before it has a
379 * chance to run the requested function, the function will be run upon the
380 * EventBase's destruction.
382 * The function must not throw any exceptions.
384 bool runInEventBaseThread(Func fn);
387 * Like runInEventBaseThread, but the caller waits for the callback to be
390 template <typename T>
391 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
394 * Like runInEventBaseThread, but the caller waits for the callback to be
397 bool runInEventBaseThreadAndWait(Func fn);
400 * Like runInEventBaseThreadAndWait, except if the caller is already in the
401 * event base thread, the functor is simply run inline.
403 template <typename T>
404 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg);
407 * Like runInEventBaseThreadAndWait, except if the caller is already in the
408 * event base thread, the functor is simply run inline.
410 bool runImmediatelyOrRunInEventBaseThreadAndWait(Func fn);
413 * Runs the given Cob at some time after the specified number of
414 * milliseconds. (No guarantees exactly when.)
416 * Throws a std::system_error if an error occurs.
420 uint32_t milliseconds,
421 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
424 * @see tryRunAfterDelay for more details
426 * @return true iff the cob was successfully registered.
429 bool tryRunAfterDelay(
431 uint32_t milliseconds,
432 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
435 * Set the maximum desired latency in us and provide a callback which will be
436 * called when that latency is exceeded.
437 * OBS: This functionality depends on time-measurement.
439 void setMaxLatency(int64_t maxLatency, Func maxLatencyCob) {
440 assert(enableTimeMeasurement_);
441 maxLatency_ = maxLatency;
442 maxLatencyCob_ = std::move(maxLatencyCob);
447 * Set smoothing coefficient for loop load average; # of milliseconds
448 * for exp(-1) (1/2.71828...) decay.
450 void setLoadAvgMsec(uint32_t ms);
453 * reset the load average to a desired value
455 void resetLoadAvg(double value = 0.0);
458 * Get the average loop time in microseconds (an exponentially-smoothed ave)
460 double getAvgLoopTime() const {
461 assert(enableTimeMeasurement_);
462 return avgLoopTime_.get();
466 * check if the event base loop is running.
468 bool isRunning() const {
469 return loopThread_.load(std::memory_order_relaxed) != 0;
473 * wait until the event loop starts (after starting the event loop thread).
475 void waitUntilRunning();
477 int getNotificationQueueSize() const;
479 void setMaxReadAtOnce(uint32_t maxAtOnce);
482 * Verify that current thread is the EventBase thread, if the EventBase is
485 bool isInEventBaseThread() const {
486 auto tid = loopThread_.load(std::memory_order_relaxed);
487 return tid == 0 || pthread_equal(tid, pthread_self());
490 bool inRunningEventBaseThread() const {
491 return pthread_equal(
492 loopThread_.load(std::memory_order_relaxed), pthread_self());
495 // --------- interface to underlying libevent base ------------
496 // Avoid using these functions if possible. These functions are not
497 // guaranteed to always be present if we ever provide alternative EventBase
498 // implementations that do not use libevent internally.
499 event_base* getLibeventBase() const { return evb_; }
500 static const char* getLibeventVersion();
501 static const char* getLibeventMethod();
504 * only EventHandler/AsyncTimeout subclasses and ourselves should
507 * This is used to mark the beginning of a new loop cycle by the
508 * first handler fired within that cycle.
511 void bumpHandlingTime() override final;
513 class SmoothLoopTime {
515 explicit SmoothLoopTime(uint64_t timeInterval)
516 : expCoeff_(-1.0/timeInterval)
518 , oldBusyLeftover_(0) {
519 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
522 void setTimeInterval(uint64_t timeInterval);
523 void reset(double value = 0.0);
525 void addSample(int64_t idle, int64_t busy);
531 void dampen(double factor) {
538 int64_t oldBusyLeftover_;
541 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
542 assert(enableTimeMeasurement_);
543 observer_ = observer;
546 const std::shared_ptr<EventBaseObserver>& getObserver() {
551 * Setup execution observation/instrumentation for every EventHandler
552 * executed in this EventBase.
554 * @param executionObserver EventHandle's execution observer.
556 void setExecutionObserver(ExecutionObserver* observer) {
557 executionObserver_ = observer;
561 * Gets the execution observer associated with this EventBase.
563 ExecutionObserver* getExecutionObserver() {
564 return executionObserver_;
568 * Set the name of the thread that runs this event base.
570 void setName(const std::string& name);
573 * Returns the name of the thread that runs this event base.
575 const std::string& getName();
577 /// Implements the Executor interface
578 void add(Cob fn) override {
579 // runInEventBaseThread() takes a const&,
580 // so no point in doing std::move here.
581 runInEventBaseThread(std::move(fn));
584 /// Implements the DrivableExecutor interface
585 void drive() override {
589 using LoopKeepAlive = std::shared_ptr<void>;
591 /// Returns you a handle which make loop() behave like loopForever() until
592 /// destroyed. loop() will return to its original behavior only when all
593 /// loop keep-alives are released. Loop holder is safe to release only from
594 /// EventBase thread.
596 /// May return no op LoopKeepAlive if loopForever() is already running.
597 LoopKeepAlive loopKeepAlive() {
598 if (loopForeverActive_) {
601 return loopKeepAlive_;
607 void attachTimeoutManager(AsyncTimeout* obj,
608 TimeoutManager::InternalEnum internal) override;
610 void detachTimeoutManager(AsyncTimeout* obj) override;
612 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
615 void cancelTimeout(AsyncTimeout* obj) override;
617 bool isInTimeoutManagerThread() override final {
618 return isInEventBaseThread();
621 void applyLoopKeepAlive();
624 * Helper function that tells us whether we have already handled
625 * some event/timeout/callback in this loop iteration.
627 bool nothingHandledYet() const noexcept;
629 // small object used as a callback arg with enough info to execute the
630 // appropriate client-provided Cob
631 class CobTimeout : public AsyncTimeout {
633 CobTimeout(EventBase* b, Func c, TimeoutManager::InternalEnum in)
634 : AsyncTimeout(b, in), cob_(std::move(c)) {}
636 virtual void timeoutExpired() noexcept;
642 typedef boost::intrusive::list_member_hook<
643 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
647 typedef boost::intrusive::list<
649 boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
650 boost::intrusive::constant_time_size<false> > List;
653 typedef LoopCallback::List LoopCallbackList;
654 class FunctionRunner;
656 bool loopBody(int flags = 0);
658 // executes any callbacks queued by runInLoop(); returns false if none found
659 bool runLoopCallbacks(bool setContext = true);
661 void initNotificationQueue();
663 CobTimeout::List pendingCobTimeouts_;
665 LoopCallbackList loopCallbacks_;
666 LoopCallbackList runBeforeLoopCallbacks_;
667 LoopCallbackList onDestructionCallbacks_;
668 LoopCallbackList runAfterDrainCallbacks_;
670 // This will be null most of the time, but point to currentCallbacks
671 // if we are in the middle of running loop callbacks, such that
672 // runInLoop(..., true) will always run in the current loop
674 LoopCallbackList* runOnceCallbacks_;
676 // stop_ is set by terminateLoopSoon() and is used by the main loop
677 // to determine if it should exit
678 std::atomic<bool> stop_;
680 // The ID of the thread running the main loop.
681 // 0 if loop is not running.
682 // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
683 // even that atomic<pthread_t> is valid), but that's how it is
684 // everywhere (at least on Linux, FreeBSD, and OSX).
685 std::atomic<pthread_t> loopThread_;
687 // pointer to underlying event_base class doing the heavy lifting
690 // A notification queue for runInEventBaseThread() to use
691 // to send function requests to the EventBase thread.
692 std::unique_ptr<NotificationQueue<Func>> queue_;
693 std::unique_ptr<FunctionRunner> fnRunner_;
694 LoopKeepAlive loopKeepAlive_{std::make_shared<int>(42)};
695 bool loopKeepAliveActive_{false};
696 std::atomic<bool> loopForeverActive_{false};
698 // limit for latency in microseconds (0 disables)
701 // exponentially-smoothed average loop time for latency-limiting
702 SmoothLoopTime avgLoopTime_;
704 // smoothed loop time used to invoke latency callbacks; differs from
705 // avgLoopTime_ in that it's scaled down after triggering a callback
706 // to reduce spamminess
707 SmoothLoopTime maxLatencyLoopTime_;
709 // callback called when latency limit is exceeded
712 // Enables/disables time measurements in loopBody(). if disabled, the
713 // following functionality that relies on time-measurement, will not
714 // be supported: avg loop time, observer and max latency.
715 const bool enableTimeMeasurement_;
717 // we'll wait this long before running deferred callbacks if the event
719 static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
721 // Wrap-around loop counter to detect beginning of each loop
722 uint64_t nextLoopCnt_;
723 uint64_t latestLoopCnt_;
726 // Observer to export counters
727 std::shared_ptr<EventBaseObserver> observer_;
728 uint32_t observerSampleCount_;
730 // EventHandler's execution observer.
731 ExecutionObserver* executionObserver_;
733 // Name of the thread running this EventBase
736 // allow runOnDestruction() to be called from any threads
737 std::mutex onDestructionCallbacksMutex_;
739 // allow runAfterDrain() to be called from any threads
740 std::mutex runAfterDrainCallbacksMutex_;
742 // see EventBaseLocal
743 friend class detail::EventBaseLocalBase;
744 template <typename T> friend class EventBaseLocal;
745 std::mutex localStorageMutex_;
746 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
747 std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
750 template <typename T>
751 bool EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) {
752 return runInEventBaseThread([=] { fn(arg); });
755 template <typename T>
756 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
757 return runInEventBaseThreadAndWait([=] { fn(arg); });
760 template <typename T>
761 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
764 return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });