2 * Copyright 2015 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.
19 #include <glog/logging.h>
20 #include <folly/io/async/AsyncTimeout.h>
21 #include <folly/io/async/TimeoutManager.h>
22 #include <folly/io/async/Request.h>
23 #include <folly/Executor.h>
24 #include <folly/experimental/ExecutionObserver.h>
25 #include <folly/futures/DrivableExecutor.h>
33 #include <boost/intrusive/list.hpp>
34 #include <boost/utility.hpp>
36 #include <event.h> // libevent
43 typedef std::function<void()> Cob;
44 template <typename MessageT>
45 class NotificationQueue;
47 class EventBaseObserver {
49 virtual ~EventBaseObserver() = default;
51 virtual uint32_t getSampleRate() const = 0;
53 virtual void loopSample(
54 int64_t busyTime, int64_t idleTime) = 0;
57 // Helper class that sets and retrieves the EventBase associated with a given
58 // request via RequestContext. See Request.h for that mechanism.
59 class RequestEventBase : public RequestData {
61 static EventBase* get() {
62 auto data = dynamic_cast<RequestEventBase*>(
63 RequestContext::get()->getContextData(kContextDataName));
70 static void set(EventBase* eb) {
71 RequestContext::get()->setContextData(
73 std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
77 explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
79 static constexpr const char* kContextDataName{"EventBase"};
83 * This class is a wrapper for all asynchronous I/O processing functionality
85 * EventBase provides a main loop that notifies EventHandler callback objects
86 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
87 * when a specified timeout has expired. More complex, higher-level callback
88 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
90 * A EventBase object can only drive an event loop for a single thread. To
91 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
92 * thread per CPU, and use a separate EventBase for each thread.
94 * In general, most EventBase methods may only be called from the thread
95 * running the EventBase's loop. There are a few exceptions to this rule, for
96 * methods that are explicitly intended to allow communication with a
97 * EventBase from other threads. When it is safe to call a method from
98 * another thread it is explicitly listed in the method comments.
100 class EventBase : private boost::noncopyable,
101 public TimeoutManager,
102 public DrivableExecutor {
105 * A callback interface to use with runInLoop()
107 * Derive from this class if you need to delay some code execution until the
108 * next iteration of the event loop. This allows you to schedule code to be
109 * invoked from the top-level of the loop, after your immediate callers have
112 * If a LoopCallback object is destroyed while it is scheduled to be run in
113 * the next loop iteration, it will automatically be cancelled.
117 virtual ~LoopCallback() = default;
119 virtual void runLoopCallback() noexcept = 0;
120 void cancelLoopCallback() {
124 bool isLoopCallbackScheduled() const {
125 return hook_.is_linked();
129 typedef boost::intrusive::list_member_hook<
130 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
134 typedef boost::intrusive::list<
136 boost::intrusive::member_hook<LoopCallback, ListHook,
137 &LoopCallback::hook_>,
138 boost::intrusive::constant_time_size<false> > List;
140 // EventBase needs access to LoopCallbackList (and therefore to hook_)
141 friend class EventBase;
142 std::shared_ptr<RequestContext> context_;
146 * Create a new EventBase object.
148 * @param enableTimeMeasurement Informs whether this event base should measure
149 * time. Disabling it would likely improve
150 * performance, but will disable some features
151 * that relies on time-measurement, including:
152 * observer, max latency and avg loop time.
154 explicit EventBase(bool enableTimeMeasurement = true);
157 * Create a new EventBase object that will use the specified libevent
158 * event_base object to drive the event loop.
160 * The EventBase will take ownership of this event_base, and will call
161 * event_base_free(evb) when the EventBase is destroyed.
163 * @param enableTimeMeasurement Informs whether this event base should measure
164 * time. Disabling it would likely improve
165 * performance, but will disable some features
166 * that relies on time-measurement, including:
167 * observer, max latency and avg loop time.
169 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
173 * Runs the event loop.
175 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
176 * and AsyncTimeout callbacks as their events become ready. loop() will
177 * only return when there are no more events remaining to process, or after
178 * terminateLoopSoon() has been called.
180 * loop() may be called again to restart event processing after a previous
181 * call to loop() or loopForever() has returned.
183 * Returns true if the loop completed normally (if it processed all
184 * outstanding requests, or if terminateLoopSoon() was called). If an error
185 * occurs waiting for events, false will be returned.
190 * Wait for some events to become active, run them, then return.
192 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
193 * are not any events to process.
195 * This is useful for callers that want to run the loop manually.
197 * Returns the same result as loop().
199 bool loopOnce(int flags = 0);
202 * Runs the event loop.
204 * loopForever() behaves like loop(), except that it keeps running even if
205 * when there are no more user-supplied EventHandlers or AsyncTimeouts
206 * registered. It will only return after terminateLoopSoon() has been
209 * This is useful for callers that want to wait for other threads to call
210 * runInEventBaseThread(), even when there are no other scheduled events.
212 * loopForever() may be called again to restart event processing after a
213 * previous call to loop() or loopForever() has returned.
215 * Throws a std::system_error if an error occurs.
220 * Causes the event loop to exit soon.
222 * This will cause an existing call to loop() or loopForever() to stop event
223 * processing and return, even if there are still events remaining to be
226 * It is safe to call terminateLoopSoon() from another thread to cause loop()
227 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
228 * may also be called from the loop thread itself (for example, a
229 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
230 * cause the loop to exit after the callback returns.) If the loop is not
231 * running, this will cause the next call to loop to terminate soon after
232 * starting. If a loop runs out of work (and so terminates on its own)
233 * concurrently with a call to terminateLoopSoon(), this may cause a race
236 * Note that the caller is responsible for ensuring that cleanup of all event
237 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
238 * exit even when there are pending events present, there may be remaining
239 * callbacks present waiting to be invoked. If the loop is later restarted
240 * pending events will continue to be processed normally, however if the
241 * EventBase is destroyed after calling terminateLoopSoon() it is the
242 * caller's responsibility to ensure that cleanup happens properly even if
243 * some outstanding events are never processed.
245 void terminateLoopSoon();
248 * Adds the given callback to a queue of things run after the current pass
249 * through the event loop completes. Note that if this callback calls
250 * runInLoop() the new callback won't be called until the main event loop
251 * has gone through a cycle.
253 * This method may only be called from the EventBase's thread. This
254 * essentially allows an event handler to schedule an additional callback to
255 * be invoked after it returns.
257 * Use runInEventBaseThread() to schedule functions from another thread.
259 * The thisIteration parameter makes this callback run in this loop
260 * iteration, instead of the next one, even if called from a
261 * runInLoop callback (normal io callbacks that call runInLoop will
262 * always run in this iteration). This was originally added to
263 * support detachEventBase, as a user callback may have called
264 * terminateLoopSoon(), but we want to make sure we detach. Also,
265 * detachEventBase almost always must be called from the base event
266 * loop to ensure the stack is unwound, since most users of
267 * EventBase are not thread safe.
269 * Ideally we would not need thisIteration, and instead just use
270 * runInLoop with loop() (instead of terminateLoopSoon).
272 void runInLoop(LoopCallback* callback, bool thisIteration = false);
275 * Convenience function to call runInLoop() with a std::function.
277 * This creates a LoopCallback object to wrap the std::function, and invoke
278 * the std::function when the loop callback fires. This is slightly more
279 * expensive than defining your own LoopCallback, but more convenient in
280 * areas that aren't performance sensitive where you just want to use
281 * std::bind. (std::bind is fairly slow on even by itself.)
283 * This method may only be called from the EventBase's thread. This
284 * essentially allows an event handler to schedule an additional callback to
285 * be invoked after it returns.
287 * Use runInEventBaseThread() to schedule functions from another thread.
289 void runInLoop(const Cob& c, bool thisIteration = false);
291 void runInLoop(Cob&& c, bool thisIteration = false);
294 * Adds the given callback to a queue of things run before destruction
295 * of current EventBase.
297 * This allows users of EventBase that run in it, but don't control it,
298 * to be notified before EventBase gets destructed.
300 * Note: will be called from the thread that invoked EventBase destructor,
301 * before the final run of loop callbacks.
303 void runOnDestruction(LoopCallback* callback);
306 * Adds a callback that will run immediately *before* the event loop.
307 * This is very similar to runInLoop(), but will not cause the loop to break:
308 * For example, this callback could be used to get loop times.
310 void runBeforeLoop(LoopCallback* callback);
313 * Run the specified function in the EventBase's thread.
315 * This method is thread-safe, and may be called from another thread.
317 * If runInEventBaseThread() is called when the EventBase loop is not
318 * running, the function call will be delayed until the next time the loop is
321 * If runInEventBaseThread() returns true the function has successfully been
322 * scheduled to run in the loop thread. However, if the loop is terminated
323 * (and never later restarted) before it has a chance to run the requested
324 * function, the function will be run upon the EventBase's destruction.
326 * If two calls to runInEventBaseThread() are made from the same thread, the
327 * functions will always be run in the order that they were scheduled.
328 * Ordering between functions scheduled from separate threads is not
331 * @param fn The function to run. The function must not throw any
333 * @param arg An argument to pass to the function.
335 * @return Returns true if the function was successfully scheduled, or false
336 * if there was an error scheduling the function.
339 bool runInEventBaseThread(void (*fn)(T*), T* arg) {
340 return runInEventBaseThread(reinterpret_cast<void (*)(void*)>(fn),
341 reinterpret_cast<void*>(arg));
344 bool runInEventBaseThread(void (*fn)(void*), void* arg);
347 * Run the specified function in the EventBase's thread
349 * This version of runInEventBaseThread() takes a std::function object.
350 * Note that this is less efficient than the version that takes a plain
351 * function pointer and void* argument, as it has to allocate memory to copy
352 * the std::function object.
354 * If the loop is terminated (and never later restarted) before it has a
355 * chance to run the requested function, the function will be run upon the
356 * EventBase's destruction.
358 * The function must not throw any exceptions.
360 bool runInEventBaseThread(const Cob& fn);
363 * Like runInEventBaseThread, but the caller waits for the callback to be
367 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
368 return runInEventBaseThreadAndWait(reinterpret_cast<void (*)(void*)>(fn),
369 reinterpret_cast<void*>(arg));
373 * Like runInEventBaseThread, but the caller waits for the callback to be
376 bool runInEventBaseThreadAndWait(void (*fn)(void*), void* arg) {
377 return runInEventBaseThreadAndWait(std::bind(fn, arg));
381 * Like runInEventBaseThread, but the caller waits for the callback to be
384 bool runInEventBaseThreadAndWait(const Cob& fn);
387 * Like runInEventBaseThreadAndWait, except if the caller is already in the
388 * event base thread, the functor is simply run inline.
391 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
392 return runImmediatelyOrRunInEventBaseThreadAndWait(
393 reinterpret_cast<void (*)(void*)>(fn), reinterpret_cast<void*>(arg));
397 * Like runInEventBaseThreadAndWait, except if the caller is already in the
398 * event base thread, the functor is simply run inline.
400 bool runImmediatelyOrRunInEventBaseThreadAndWait(
401 void (*fn)(void*), void* arg) {
402 return runImmediatelyOrRunInEventBaseThreadAndWait(std::bind(fn, arg));
406 * Like runInEventBaseThreadAndWait, except if the caller is already in the
407 * event base thread, the functor is simply run inline.
409 bool runImmediatelyOrRunInEventBaseThreadAndWait(const Cob& fn);
412 * Runs the given Cob at some time after the specified number of
413 * milliseconds. (No guarantees exactly when.)
415 * Throws a std::system_error if an error occurs.
420 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
423 * @see tryRunAfterDelay for more details
425 * @return true iff the cob was successfully registered.
428 bool tryRunAfterDelay(
431 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
434 * Set the maximum desired latency in us and provide a callback which will be
435 * called when that latency is exceeded.
436 * OBS: This functionality depends on time-measurement.
438 void setMaxLatency(int64_t maxLatency, const Cob& maxLatencyCob) {
439 assert(enableTimeMeasurement_);
440 maxLatency_ = maxLatency;
441 maxLatencyCob_ = maxLatencyCob;
446 * Set smoothing coefficient for loop load average; # of milliseconds
447 * for exp(-1) (1/2.71828...) decay.
449 void setLoadAvgMsec(uint32_t ms);
452 * reset the load average to a desired value
454 void resetLoadAvg(double value = 0.0);
457 * Get the average loop time in microseconds (an exponentially-smoothed ave)
459 double getAvgLoopTime() const {
460 assert(enableTimeMeasurement_);
461 return avgLoopTime_.get();
465 * check if the event base loop is running.
467 bool isRunning() const {
468 return loopThread_.load(std::memory_order_relaxed) != 0;
472 * wait until the event loop starts (after starting the event loop thread).
474 void waitUntilRunning();
476 int getNotificationQueueSize() const;
478 void setMaxReadAtOnce(uint32_t maxAtOnce);
481 * Verify that current thread is the EventBase thread, if the EventBase is
484 bool isInEventBaseThread() const {
485 auto tid = loopThread_.load(std::memory_order_relaxed);
486 return tid == 0 || pthread_equal(tid, pthread_self());
489 bool inRunningEventBaseThread() const {
490 return pthread_equal(
491 loopThread_.load(std::memory_order_relaxed), pthread_self());
494 // --------- interface to underlying libevent base ------------
495 // Avoid using these functions if possible. These functions are not
496 // guaranteed to always be present if we ever provide alternative EventBase
497 // implementations that do not use libevent internally.
498 event_base* getLibeventBase() const { return evb_; }
499 static const char* getLibeventVersion();
500 static const char* getLibeventMethod();
503 * only EventHandler/AsyncTimeout subclasses and ourselves should
506 * This is used to mark the beginning of a new loop cycle by the
507 * first handler fired within that cycle.
510 bool bumpHandlingTime() override;
512 class SmoothLoopTime {
514 explicit SmoothLoopTime(uint64_t timeInterval)
515 : expCoeff_(-1.0/timeInterval)
517 , oldBusyLeftover_(0) {
518 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
521 void setTimeInterval(uint64_t timeInterval);
522 void reset(double value = 0.0);
524 void addSample(int64_t idle, int64_t busy);
530 void dampen(double factor) {
537 int64_t oldBusyLeftover_;
540 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
541 assert(enableTimeMeasurement_);
542 observer_ = observer;
545 const std::shared_ptr<EventBaseObserver>& getObserver() {
550 * Setup execution observation/instrumentation for every EventHandler
551 * executed in this EventBase.
553 * @param executionObserver EventHandle's execution observer.
555 void setExecutionObserver(ExecutionObserver* observer) {
556 executionObserver_ = observer;
560 * Gets the execution observer associated with this EventBase.
562 ExecutionObserver* getExecutionObserver() {
563 return executionObserver_;
567 * Set the name of the thread that runs this event base.
569 void setName(const std::string& name);
572 * Returns the name of the thread that runs this event base.
574 const std::string& getName();
576 /// Implements the Executor interface
577 void add(Cob fn) override {
578 // runInEventBaseThread() takes a const&,
579 // so no point in doing std::move here.
580 runInEventBaseThread(fn);
583 /// Implements the DrivableExecutor interface
584 void drive() override {
591 void attachTimeoutManager(AsyncTimeout* obj,
592 TimeoutManager::InternalEnum internal) override;
594 void detachTimeoutManager(AsyncTimeout* obj) override;
596 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
599 void cancelTimeout(AsyncTimeout* obj) override;
601 bool isInTimeoutManagerThread() override {
602 return isInEventBaseThread();
605 // Helper class used to short circuit runInEventBaseThread
606 class RunInLoopCallback : public LoopCallback {
608 RunInLoopCallback(void (*fn)(void*), void* arg);
609 void runLoopCallback() noexcept;
617 * Helper function that tells us whether we have already handled
618 * some event/timeout/callback in this loop iteration.
620 bool nothingHandledYet();
622 // --------- libevent callbacks (not for client use) ------------
624 static void runFunctionPtr(std::function<void()>* fn);
626 // small object used as a callback arg with enough info to execute the
627 // appropriate client-provided Cob
628 class CobTimeout : public AsyncTimeout {
630 CobTimeout(EventBase* b, const Cob& c, TimeoutManager::InternalEnum in)
631 : AsyncTimeout(b, in), cob_(c) {}
633 virtual void timeoutExpired() noexcept;
639 typedef boost::intrusive::list_member_hook<
640 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
644 typedef boost::intrusive::list<
646 boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
647 boost::intrusive::constant_time_size<false> > List;
650 typedef LoopCallback::List LoopCallbackList;
651 class FunctionRunner;
653 bool loopBody(int flags = 0);
655 // executes any callbacks queued by runInLoop(); returns false if none found
656 bool runLoopCallbacks(bool setContext = true);
658 void initNotificationQueue();
660 CobTimeout::List pendingCobTimeouts_;
662 LoopCallbackList loopCallbacks_;
663 LoopCallbackList runBeforeLoopCallbacks_;
664 LoopCallbackList onDestructionCallbacks_;
666 // This will be null most of the time, but point to currentCallbacks
667 // if we are in the middle of running loop callbacks, such that
668 // runInLoop(..., true) will always run in the current loop
670 LoopCallbackList* runOnceCallbacks_;
672 // stop_ is set by terminateLoopSoon() and is used by the main loop
673 // to determine if it should exit
676 // The ID of the thread running the main loop.
677 // 0 if loop is not running.
678 // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
679 // even that atomic<pthread_t> is valid), but that's how it is
680 // everywhere (at least on Linux, FreeBSD, and OSX).
681 std::atomic<pthread_t> loopThread_;
683 // pointer to underlying event_base class doing the heavy lifting
686 // A notification queue for runInEventBaseThread() to use
687 // to send function requests to the EventBase thread.
688 std::unique_ptr<NotificationQueue<std::pair<void (*)(void*), void*>>> queue_;
689 std::unique_ptr<FunctionRunner> fnRunner_;
691 // limit for latency in microseconds (0 disables)
694 // exponentially-smoothed average loop time for latency-limiting
695 SmoothLoopTime avgLoopTime_;
697 // smoothed loop time used to invoke latency callbacks; differs from
698 // avgLoopTime_ in that it's scaled down after triggering a callback
699 // to reduce spamminess
700 SmoothLoopTime maxLatencyLoopTime_;
702 // callback called when latency limit is exceeded
705 // Enables/disables time measurements in loopBody(). if disabled, the
706 // following functionality that relies on time-measurement, will not
707 // be supported: avg loop time, observer and max latency.
708 const bool enableTimeMeasurement_;
710 // we'll wait this long before running deferred callbacks if the event
712 static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
714 // Wrap-around loop counter to detect beginning of each loop
715 uint64_t nextLoopCnt_;
716 uint64_t latestLoopCnt_;
719 // Observer to export counters
720 std::shared_ptr<EventBaseObserver> observer_;
721 uint32_t observerSampleCount_;
723 // EventHandler's execution observer.
724 ExecutionObserver* executionObserver_;
726 // Name of the thread running this EventBase
729 // allow runOnDestruction() to be called from any threads
730 std::mutex onDestructionCallbacksMutex_;