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>
32 #include <unordered_set>
33 #include <unordered_map>
36 #include <boost/intrusive/list.hpp>
37 #include <boost/utility.hpp>
39 #include <event.h> // libevent
46 typedef std::function<void()> Cob;
47 template <typename MessageT>
48 class NotificationQueue;
50 #if !defined(ANDROID) && !defined(__ANDROID__) && !defined(__APPLE__)
52 class EventBaseLocalBase;
58 class EventBaseObserver {
60 virtual ~EventBaseObserver() = default;
62 virtual uint32_t getSampleRate() const = 0;
64 virtual void loopSample(
65 int64_t busyTime, int64_t idleTime) = 0;
68 // Helper class that sets and retrieves the EventBase associated with a given
69 // request via RequestContext. See Request.h for that mechanism.
70 class RequestEventBase : public RequestData {
72 static EventBase* get() {
73 auto data = dynamic_cast<RequestEventBase*>(
74 RequestContext::get()->getContextData(kContextDataName));
81 static void set(EventBase* eb) {
82 RequestContext::get()->setContextData(
84 std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
88 explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
90 static constexpr const char* kContextDataName{"EventBase"};
94 * This class is a wrapper for all asynchronous I/O processing functionality
96 * EventBase provides a main loop that notifies EventHandler callback objects
97 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
98 * when a specified timeout has expired. More complex, higher-level callback
99 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
101 * A EventBase object can only drive an event loop for a single thread. To
102 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
103 * thread per CPU, and use a separate EventBase for each thread.
105 * In general, most EventBase methods may only be called from the thread
106 * running the EventBase's loop. There are a few exceptions to this rule, for
107 * methods that are explicitly intended to allow communication with a
108 * EventBase from other threads. When it is safe to call a method from
109 * another thread it is explicitly listed in the method comments.
111 class EventBase : private boost::noncopyable,
112 public TimeoutManager,
113 public DrivableExecutor {
116 * A callback interface to use with runInLoop()
118 * Derive from this class if you need to delay some code execution until the
119 * next iteration of the event loop. This allows you to schedule code to be
120 * invoked from the top-level of the loop, after your immediate callers have
123 * If a LoopCallback object is destroyed while it is scheduled to be run in
124 * the next loop iteration, it will automatically be cancelled.
128 virtual ~LoopCallback() = default;
130 virtual void runLoopCallback() noexcept = 0;
131 void cancelLoopCallback() {
135 bool isLoopCallbackScheduled() const {
136 return hook_.is_linked();
140 typedef boost::intrusive::list_member_hook<
141 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
145 typedef boost::intrusive::list<
147 boost::intrusive::member_hook<LoopCallback, ListHook,
148 &LoopCallback::hook_>,
149 boost::intrusive::constant_time_size<false> > List;
151 // EventBase needs access to LoopCallbackList (and therefore to hook_)
152 friend class EventBase;
153 std::shared_ptr<RequestContext> context_;
157 * Create a new EventBase object.
159 * @param enableTimeMeasurement Informs whether this event base should measure
160 * time. Disabling it would likely improve
161 * performance, but will disable some features
162 * that relies on time-measurement, including:
163 * observer, max latency and avg loop time.
165 explicit EventBase(bool enableTimeMeasurement = true);
168 * Create a new EventBase object that will use the specified libevent
169 * event_base object to drive the event loop.
171 * The EventBase will take ownership of this event_base, and will call
172 * event_base_free(evb) when the EventBase is destroyed.
174 * @param enableTimeMeasurement Informs whether this event base should measure
175 * time. Disabling it would likely improve
176 * performance, but will disable some features
177 * that relies on time-measurement, including:
178 * observer, max latency and avg loop time.
180 explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
184 * Runs the event loop.
186 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
187 * and AsyncTimeout callbacks as their events become ready. loop() will
188 * only return when there are no more events remaining to process, or after
189 * terminateLoopSoon() has been called.
191 * loop() may be called again to restart event processing after a previous
192 * call to loop() or loopForever() has returned.
194 * Returns true if the loop completed normally (if it processed all
195 * outstanding requests, or if terminateLoopSoon() was called). If an error
196 * occurs waiting for events, false will be returned.
201 * Wait for some events to become active, run them, then return.
203 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
204 * are not any events to process.
206 * This is useful for callers that want to run the loop manually.
208 * Returns the same result as loop().
210 bool loopOnce(int flags = 0);
213 * Runs the event loop.
215 * loopForever() behaves like loop(), except that it keeps running even if
216 * when there are no more user-supplied EventHandlers or AsyncTimeouts
217 * registered. It will only return after terminateLoopSoon() has been
220 * This is useful for callers that want to wait for other threads to call
221 * runInEventBaseThread(), even when there are no other scheduled events.
223 * loopForever() may be called again to restart event processing after a
224 * previous call to loop() or loopForever() has returned.
226 * Throws a std::system_error if an error occurs.
231 * Causes the event loop to exit soon.
233 * This will cause an existing call to loop() or loopForever() to stop event
234 * processing and return, even if there are still events remaining to be
237 * It is safe to call terminateLoopSoon() from another thread to cause loop()
238 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
239 * may also be called from the loop thread itself (for example, a
240 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
241 * cause the loop to exit after the callback returns.) If the loop is not
242 * running, this will cause the next call to loop to terminate soon after
243 * starting. If a loop runs out of work (and so terminates on its own)
244 * concurrently with a call to terminateLoopSoon(), this may cause a race
247 * Note that the caller is responsible for ensuring that cleanup of all event
248 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
249 * exit even when there are pending events present, there may be remaining
250 * callbacks present waiting to be invoked. If the loop is later restarted
251 * pending events will continue to be processed normally, however if the
252 * EventBase is destroyed after calling terminateLoopSoon() it is the
253 * caller's responsibility to ensure that cleanup happens properly even if
254 * some outstanding events are never processed.
256 void terminateLoopSoon();
259 * Adds the given callback to a queue of things run after the current pass
260 * through the event loop completes. Note that if this callback calls
261 * runInLoop() the new callback won't be called until the main event loop
262 * has gone through a cycle.
264 * This method may only be called from the EventBase's thread. This
265 * essentially allows an event handler to schedule an additional callback to
266 * be invoked after it returns.
268 * Use runInEventBaseThread() to schedule functions from another thread.
270 * The thisIteration parameter makes this callback run in this loop
271 * iteration, instead of the next one, even if called from a
272 * runInLoop callback (normal io callbacks that call runInLoop will
273 * always run in this iteration). This was originally added to
274 * support detachEventBase, as a user callback may have called
275 * terminateLoopSoon(), but we want to make sure we detach. Also,
276 * detachEventBase almost always must be called from the base event
277 * loop to ensure the stack is unwound, since most users of
278 * EventBase are not thread safe.
280 * Ideally we would not need thisIteration, and instead just use
281 * runInLoop with loop() (instead of terminateLoopSoon).
283 void runInLoop(LoopCallback* callback, bool thisIteration = false);
286 * Convenience function to call runInLoop() with a std::function.
288 * This creates a LoopCallback object to wrap the std::function, and invoke
289 * the std::function when the loop callback fires. This is slightly more
290 * expensive than defining your own LoopCallback, but more convenient in
291 * areas that aren't performance sensitive where you just want to use
292 * std::bind. (std::bind is fairly slow on even by itself.)
294 * This method may only be called from the EventBase's thread. This
295 * essentially allows an event handler to schedule an additional callback to
296 * be invoked after it returns.
298 * Use runInEventBaseThread() to schedule functions from another thread.
300 void runInLoop(const Cob& c, bool thisIteration = false);
302 void runInLoop(Cob&& c, bool thisIteration = false);
305 * Adds the given callback to a queue of things run before destruction
306 * of current EventBase.
308 * This allows users of EventBase that run in it, but don't control it,
309 * to be notified before EventBase gets destructed.
311 * Note: will be called from the thread that invoked EventBase destructor,
312 * before the final run of loop callbacks.
314 void runOnDestruction(LoopCallback* callback);
317 * Adds a callback that will run immediately *before* the event loop.
318 * This is very similar to runInLoop(), but will not cause the loop to break:
319 * For example, this callback could be used to get loop times.
321 void runBeforeLoop(LoopCallback* callback);
324 * Run the specified function in the EventBase's thread.
326 * This method is thread-safe, and may be called from another thread.
328 * If runInEventBaseThread() is called when the EventBase loop is not
329 * running, the function call will be delayed until the next time the loop is
332 * If runInEventBaseThread() returns true the function has successfully been
333 * scheduled to run in the loop thread. However, if the loop is terminated
334 * (and never later restarted) before it has a chance to run the requested
335 * function, the function will be run upon the EventBase's destruction.
337 * If two calls to runInEventBaseThread() are made from the same thread, the
338 * functions will always be run in the order that they were scheduled.
339 * Ordering between functions scheduled from separate threads is not
342 * @param fn The function to run. The function must not throw any
344 * @param arg An argument to pass to the function.
346 * @return Returns true if the function was successfully scheduled, or false
347 * if there was an error scheduling the function.
350 bool runInEventBaseThread(void (*fn)(T*), T* arg) {
351 return runInEventBaseThread(reinterpret_cast<void (*)(void*)>(fn),
352 reinterpret_cast<void*>(arg));
355 bool runInEventBaseThread(void (*fn)(void*), void* arg);
358 * Run the specified function in the EventBase's thread
360 * This version of runInEventBaseThread() takes a std::function object.
361 * Note that this is less efficient than the version that takes a plain
362 * function pointer and void* argument, as it has to allocate memory to copy
363 * the std::function object.
365 * If the loop is terminated (and never later restarted) before it has a
366 * chance to run the requested function, the function will be run upon the
367 * EventBase's destruction.
369 * The function must not throw any exceptions.
371 bool runInEventBaseThread(const Cob& fn);
374 * Like runInEventBaseThread, but the caller waits for the callback to be
378 bool runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
379 return runInEventBaseThreadAndWait(reinterpret_cast<void (*)(void*)>(fn),
380 reinterpret_cast<void*>(arg));
384 * Like runInEventBaseThread, but the caller waits for the callback to be
387 bool runInEventBaseThreadAndWait(void (*fn)(void*), void* arg) {
388 return runInEventBaseThreadAndWait(std::bind(fn, arg));
392 * Like runInEventBaseThread, but the caller waits for the callback to be
395 bool runInEventBaseThreadAndWait(const Cob& fn);
398 * Like runInEventBaseThreadAndWait, except if the caller is already in the
399 * event base thread, the functor is simply run inline.
402 bool runImmediatelyOrRunInEventBaseThreadAndWait(void (*fn)(T*), T* arg) {
403 return runImmediatelyOrRunInEventBaseThreadAndWait(
404 reinterpret_cast<void (*)(void*)>(fn), reinterpret_cast<void*>(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(
412 void (*fn)(void*), void* arg) {
413 return runImmediatelyOrRunInEventBaseThreadAndWait(std::bind(fn, arg));
417 * Like runInEventBaseThreadAndWait, except if the caller is already in the
418 * event base thread, the functor is simply run inline.
420 bool runImmediatelyOrRunInEventBaseThreadAndWait(const Cob& fn);
423 * Runs the given Cob at some time after the specified number of
424 * milliseconds. (No guarantees exactly when.)
426 * Throws a std::system_error if an error occurs.
431 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
434 * @see tryRunAfterDelay for more details
436 * @return true iff the cob was successfully registered.
439 bool tryRunAfterDelay(
442 TimeoutManager::InternalEnum in = TimeoutManager::InternalEnum::NORMAL);
445 * Set the maximum desired latency in us and provide a callback which will be
446 * called when that latency is exceeded.
447 * OBS: This functionality depends on time-measurement.
449 void setMaxLatency(int64_t maxLatency, const Cob& maxLatencyCob) {
450 assert(enableTimeMeasurement_);
451 maxLatency_ = maxLatency;
452 maxLatencyCob_ = maxLatencyCob;
457 * Set smoothing coefficient for loop load average; # of milliseconds
458 * for exp(-1) (1/2.71828...) decay.
460 void setLoadAvgMsec(uint32_t ms);
463 * reset the load average to a desired value
465 void resetLoadAvg(double value = 0.0);
468 * Get the average loop time in microseconds (an exponentially-smoothed ave)
470 double getAvgLoopTime() const {
471 assert(enableTimeMeasurement_);
472 return avgLoopTime_.get();
476 * check if the event base loop is running.
478 bool isRunning() const {
479 return loopThread_.load(std::memory_order_relaxed) != 0;
483 * wait until the event loop starts (after starting the event loop thread).
485 void waitUntilRunning();
487 int getNotificationQueueSize() const;
489 void setMaxReadAtOnce(uint32_t maxAtOnce);
492 * Verify that current thread is the EventBase thread, if the EventBase is
495 bool isInEventBaseThread() const {
496 auto tid = loopThread_.load(std::memory_order_relaxed);
497 return tid == 0 || pthread_equal(tid, pthread_self());
500 bool inRunningEventBaseThread() const {
501 return pthread_equal(
502 loopThread_.load(std::memory_order_relaxed), pthread_self());
505 // --------- interface to underlying libevent base ------------
506 // Avoid using these functions if possible. These functions are not
507 // guaranteed to always be present if we ever provide alternative EventBase
508 // implementations that do not use libevent internally.
509 event_base* getLibeventBase() const { return evb_; }
510 static const char* getLibeventVersion();
511 static const char* getLibeventMethod();
514 * only EventHandler/AsyncTimeout subclasses and ourselves should
517 * This is used to mark the beginning of a new loop cycle by the
518 * first handler fired within that cycle.
521 bool bumpHandlingTime() override;
523 class SmoothLoopTime {
525 explicit SmoothLoopTime(uint64_t timeInterval)
526 : expCoeff_(-1.0/timeInterval)
528 , oldBusyLeftover_(0) {
529 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
532 void setTimeInterval(uint64_t timeInterval);
533 void reset(double value = 0.0);
535 void addSample(int64_t idle, int64_t busy);
541 void dampen(double factor) {
548 int64_t oldBusyLeftover_;
551 void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
552 assert(enableTimeMeasurement_);
553 observer_ = observer;
556 const std::shared_ptr<EventBaseObserver>& getObserver() {
561 * Setup execution observation/instrumentation for every EventHandler
562 * executed in this EventBase.
564 * @param executionObserver EventHandle's execution observer.
566 void setExecutionObserver(ExecutionObserver* observer) {
567 executionObserver_ = observer;
571 * Gets the execution observer associated with this EventBase.
573 ExecutionObserver* getExecutionObserver() {
574 return executionObserver_;
578 * Set the name of the thread that runs this event base.
580 void setName(const std::string& name);
583 * Returns the name of the thread that runs this event base.
585 const std::string& getName();
587 /// Implements the Executor interface
588 void add(Cob fn) override {
589 // runInEventBaseThread() takes a const&,
590 // so no point in doing std::move here.
591 runInEventBaseThread(fn);
594 /// Implements the DrivableExecutor interface
595 void drive() override {
602 void attachTimeoutManager(AsyncTimeout* obj,
603 TimeoutManager::InternalEnum internal) override;
605 void detachTimeoutManager(AsyncTimeout* obj) override;
607 bool scheduleTimeout(AsyncTimeout* obj, TimeoutManager::timeout_type timeout)
610 void cancelTimeout(AsyncTimeout* obj) override;
612 bool isInTimeoutManagerThread() override {
613 return isInEventBaseThread();
616 // Helper class used to short circuit runInEventBaseThread
617 class RunInLoopCallback : public LoopCallback {
619 RunInLoopCallback(void (*fn)(void*), void* arg);
620 void runLoopCallback() noexcept;
628 * Helper function that tells us whether we have already handled
629 * some event/timeout/callback in this loop iteration.
631 bool nothingHandledYet();
633 // --------- libevent callbacks (not for client use) ------------
635 static void runFunctionPtr(std::function<void()>* fn);
637 // small object used as a callback arg with enough info to execute the
638 // appropriate client-provided Cob
639 class CobTimeout : public AsyncTimeout {
641 CobTimeout(EventBase* b, const Cob& c, TimeoutManager::InternalEnum in)
642 : AsyncTimeout(b, in), cob_(c) {}
644 virtual void timeoutExpired() noexcept;
650 typedef boost::intrusive::list_member_hook<
651 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
655 typedef boost::intrusive::list<
657 boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
658 boost::intrusive::constant_time_size<false> > List;
661 typedef LoopCallback::List LoopCallbackList;
662 class FunctionRunner;
664 bool loopBody(int flags = 0);
666 // executes any callbacks queued by runInLoop(); returns false if none found
667 bool runLoopCallbacks(bool setContext = true);
669 void initNotificationQueue();
671 CobTimeout::List pendingCobTimeouts_;
673 LoopCallbackList loopCallbacks_;
674 LoopCallbackList runBeforeLoopCallbacks_;
675 LoopCallbackList onDestructionCallbacks_;
677 // This will be null most of the time, but point to currentCallbacks
678 // if we are in the middle of running loop callbacks, such that
679 // runInLoop(..., true) will always run in the current loop
681 LoopCallbackList* runOnceCallbacks_;
683 // stop_ is set by terminateLoopSoon() and is used by the main loop
684 // to determine if it should exit
685 std::atomic<bool> stop_;
687 // The ID of the thread running the main loop.
688 // 0 if loop is not running.
689 // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
690 // even that atomic<pthread_t> is valid), but that's how it is
691 // everywhere (at least on Linux, FreeBSD, and OSX).
692 std::atomic<pthread_t> loopThread_;
694 // pointer to underlying event_base class doing the heavy lifting
697 // A notification queue for runInEventBaseThread() to use
698 // to send function requests to the EventBase thread.
699 std::unique_ptr<NotificationQueue<std::pair<void (*)(void*), void*>>> queue_;
700 std::unique_ptr<FunctionRunner> fnRunner_;
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_;
730 // Observer to export counters
731 std::shared_ptr<EventBaseObserver> observer_;
732 uint32_t observerSampleCount_;
734 // EventHandler's execution observer.
735 ExecutionObserver* executionObserver_;
737 // Name of the thread running this EventBase
740 // allow runOnDestruction() to be called from any threads
741 std::mutex onDestructionCallbacksMutex_;
743 #if !defined(ANDROID) && !defined(__ANDROID__) && !defined(__APPLE__)
744 // see EventBaseLocal
745 friend class detail::EventBaseLocalBase;
746 template <typename T> friend class EventBaseLocal;
747 std::mutex localStorageMutex_;
748 std::unordered_map<uint64_t, std::shared_ptr<void>> localStorage_;
749 std::unordered_set<detail::EventBaseLocalBase*> localStorageToDtor_;