2 * Copyright 2014 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"
29 #include <boost/intrusive/list.hpp>
30 #include <boost/utility.hpp>
32 #include <event.h> // libevent
39 typedef std::function<void()> Cob;
40 template <typename MessageT>
41 class NotificationQueue;
43 class EventBaseObserver {
45 virtual ~EventBaseObserver() {}
47 virtual uint32_t getSampleRate() const = 0;
49 virtual void loopSample(
50 int64_t busyTime, int64_t idleTime) = 0;
54 * This class is a wrapper for all asynchronous I/O processing functionality
56 * EventBase provides a main loop that notifies EventHandler callback objects
57 * when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
58 * when a specified timeout has expired. More complex, higher-level callback
59 * mechanisms can then be built on top of EventHandler and AsyncTimeout.
61 * A EventBase object can only drive an event loop for a single thread. To
62 * take advantage of multiple CPU cores, most asynchronous I/O servers have one
63 * thread per CPU, and use a separate EventBase for each thread.
65 * In general, most EventBase methods may only be called from the thread
66 * running the EventBase's loop. There are a few exceptions to this rule, for
67 * methods that are explicitly intended to allow communication with a
68 * EventBase from other threads. When it is safe to call a method from
69 * another thread it is explicitly listed in the method comments.
71 class EventBase : private boost::noncopyable, public TimeoutManager {
74 * A callback interface to use with runInLoop()
76 * Derive from this class if you need to delay some code execution until the
77 * next iteration of the event loop. This allows you to schedule code to be
78 * invoked from the top-level of the loop, after your immediate callers have
81 * If a LoopCallback object is destroyed while it is scheduled to be run in
82 * the next loop iteration, it will automatically be cancelled.
86 virtual ~LoopCallback() {}
88 virtual void runLoopCallback() noexcept = 0;
89 void cancelLoopCallback() {
93 bool isLoopCallbackScheduled() const {
94 return hook_.is_linked();
98 typedef boost::intrusive::list_member_hook<
99 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
103 typedef boost::intrusive::list<
105 boost::intrusive::member_hook<LoopCallback, ListHook,
106 &LoopCallback::hook_>,
107 boost::intrusive::constant_time_size<false> > List;
109 // EventBase needs access to LoopCallbackList (and therefore to hook_)
110 friend class EventBase;
111 std::shared_ptr<RequestContext> context_;
115 * Create a new EventBase object.
120 * Create a new EventBase object that will use the specified libevent
121 * event_base object to drive the event loop.
123 * The EventBase will take ownership of this event_base, and will call
124 * event_base_free(evb) when the EventBase is destroyed.
126 explicit EventBase(event_base* evb);
130 * Runs the event loop.
132 * loop() will loop waiting for I/O or timeouts and invoking EventHandler
133 * and AsyncTimeout callbacks as their events become ready. loop() will
134 * only return when there are no more events remaining to process, or after
135 * terminateLoopSoon() has been called.
137 * loop() may be called again to restart event processing after a previous
138 * call to loop() or loopForever() has returned.
140 * Returns true if the loop completed normally (if it processed all
141 * outstanding requests, or if terminateLoopSoon() was called). If an error
142 * occurs waiting for events, false will be returned.
147 * Wait for some events to become active, run them, then return.
149 * When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
150 * are not any events to process.
152 * This is useful for callers that want to run the loop manually.
154 * Returns the same result as loop().
156 bool loopOnce(int flags = 0);
159 * Runs the event loop.
161 * loopForever() behaves like loop(), except that it keeps running even if
162 * when there are no more user-supplied EventHandlers or AsyncTimeouts
163 * registered. It will only return after terminateLoopSoon() has been
166 * This is useful for callers that want to wait for other threads to call
167 * runInEventBaseThread(), even when there are no other scheduled events.
169 * loopForever() may be called again to restart event processing after a
170 * previous call to loop() or loopForever() has returned.
172 * Throws a std::system_error if an error occurs.
177 * Causes the event loop to exit soon.
179 * This will cause an existing call to loop() or loopForever() to stop event
180 * processing and return, even if there are still events remaining to be
183 * It is safe to call terminateLoopSoon() from another thread to cause loop()
184 * to wake up and return in the EventBase loop thread. terminateLoopSoon()
185 * may also be called from the loop thread itself (for example, a
186 * EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
187 * cause the loop to exit after the callback returns.)
189 * Note that the caller is responsible for ensuring that cleanup of all event
190 * callbacks occurs properly. Since terminateLoopSoon() causes the loop to
191 * exit even when there are pending events present, there may be remaining
192 * callbacks present waiting to be invoked. If the loop is later restarted
193 * pending events will continue to be processed normally, however if the
194 * EventBase is destroyed after calling terminateLoopSoon() it is the
195 * caller's responsibility to ensure that cleanup happens properly even if
196 * some outstanding events are never processed.
198 void terminateLoopSoon();
201 * Adds the given callback to a queue of things run after the current pass
202 * through the event loop completes. Note that if this callback calls
203 * runInLoop() the new callback won't be called until the main event loop
204 * has gone through a cycle.
206 * This method may only be called from the EventBase's thread. This
207 * essentially allows an event handler to schedule an additional callback to
208 * be invoked after it returns.
210 * Use runInEventBaseThread() to schedule functions from another thread.
212 * The thisIteration parameter makes this callback run in this loop
213 * iteration, instead of the next one, even if called from a
214 * runInLoop callback (normal io callbacks that call runInLoop will
215 * always run in this iteration). This was originally added to
216 * support detachEventBase, as a user callback may have called
217 * terminateLoopSoon(), but we want to make sure we detach. Also,
218 * detachEventBase almost always must be called from the base event
219 * loop to ensure the stack is unwound, since most users of
220 * EventBase are not thread safe.
222 * Ideally we would not need thisIteration, and instead just use
223 * runInLoop with loop() (instead of terminateLoopSoon).
225 void runInLoop(LoopCallback* callback, bool thisIteration = false);
228 * Convenience function to call runInLoop() with a std::function.
230 * This creates a LoopCallback object to wrap the std::function, and invoke
231 * the std::function when the loop callback fires. This is slightly more
232 * expensive than defining your own LoopCallback, but more convenient in
233 * areas that aren't performance sensitive where you just want to use
234 * std::bind. (std::bind is fairly slow on even by itself.)
236 * This method may only be called from the EventBase's thread. This
237 * essentially allows an event handler to schedule an additional callback to
238 * be invoked after it returns.
240 * Use runInEventBaseThread() to schedule functions from another thread.
242 void runInLoop(const Cob& c, bool thisIteration = false);
244 void runInLoop(Cob&& c, bool thisIteration = false);
247 * Adds the given callback to a queue of things run before destruction
248 * of current EventBase.
250 * This allows users of EventBase that run in it, but don't control it,
251 * to be notified before EventBase gets destructed.
253 * Note: will be called from the thread that invoked EventBase destructor,
254 * before the final run of loop callbacks.
256 void runOnDestruction(LoopCallback* callback);
259 * Run the specified function in the EventBase's thread.
261 * This method is thread-safe, and may be called from another thread.
263 * If runInEventBaseThread() is called when the EventBase loop is not
264 * running, the function call will be delayed until the next time the loop is
267 * If runInEventBaseThread() returns true the function has successfully been
268 * scheduled to run in the loop thread. However, if the loop is terminated
269 * (and never later restarted) before it has a chance to run the requested
270 * function, the function may never be run at all. The caller is responsible
271 * for handling this situation correctly if they may terminate the loop with
272 * outstanding runInEventBaseThread() calls pending.
274 * If two calls to runInEventBaseThread() are made from the same thread, the
275 * functions will always be run in the order that they were scheduled.
276 * Ordering between functions scheduled from separate threads is not
279 * @param fn The function to run. The function must not throw any
281 * @param arg An argument to pass to the function.
283 * @return Returns true if the function was successfully scheduled, or false
284 * if there was an error scheduling the function.
287 bool runInEventBaseThread(void (*fn)(T*), T* arg) {
288 return runInEventBaseThread(reinterpret_cast<void (*)(void*)>(fn),
289 reinterpret_cast<void*>(arg));
292 bool runInEventBaseThread(void (*fn)(void*), void* arg);
295 * Run the specified function in the EventBase's thread
297 * This version of runInEventBaseThread() takes a std::function object.
298 * Note that this is less efficient than the version that takes a plain
299 * function pointer and void* argument, as it has to allocate memory to copy
300 * the std::function object.
302 * If the EventBase loop is terminated before it has a chance to run this
303 * function, the allocated memory will be leaked. The caller is responsible
304 * for ensuring that the EventBase loop is not terminated before this
307 * The function must not throw any exceptions.
309 bool runInEventBaseThread(const Cob& fn);
312 * Runs the given Cob at some time after the specified number of
313 * milliseconds. (No guarantees exactly when.)
315 * @return true iff the cob was successfully registered.
320 TimeoutManager::InternalEnum = TimeoutManager::InternalEnum::NORMAL);
323 * Set the maximum desired latency in us and provide a callback which will be
324 * called when that latency is exceeded.
326 void setMaxLatency(int64_t maxLatency, const Cob& maxLatencyCob) {
327 maxLatency_ = maxLatency;
328 maxLatencyCob_ = maxLatencyCob;
332 * Set smoothing coefficient for loop load average; # of milliseconds
333 * for exp(-1) (1/2.71828...) decay.
335 void setLoadAvgMsec(uint32_t ms);
338 * reset the load average to a desired value
340 void resetLoadAvg(double value = 0.0);
343 * Get the average loop time in microseconds (an exponentially-smoothed ave)
345 double getAvgLoopTime() const {
346 return avgLoopTime_.get();
350 * check if the event base loop is running.
352 bool isRunning() const {
353 return loopThread_.load(std::memory_order_relaxed) != 0;
357 * wait until the event loop starts (after starting the event loop thread).
359 void waitUntilRunning();
361 int getNotificationQueueSize() const;
363 void setMaxReadAtOnce(uint32_t maxAtOnce);
366 * Verify that current thread is the EventBase thread, if the EventBase is
369 bool isInEventBaseThread() const {
370 auto tid = loopThread_.load(std::memory_order_relaxed);
371 return tid == 0 || pthread_equal(tid, pthread_self());
374 bool inRunningEventBaseThread() const {
375 return pthread_equal(
376 loopThread_.load(std::memory_order_relaxed), pthread_self());
379 // --------- interface to underlying libevent base ------------
380 // Avoid using these functions if possible. These functions are not
381 // guaranteed to always be present if we ever provide alternative EventBase
382 // implementations that do not use libevent internally.
383 event_base* getLibeventBase() const { return evb_; }
384 static const char* getLibeventVersion() { return event_get_version(); }
385 static const char* getLibeventMethod() { return event_get_method(); }
388 * only EventHandler/AsyncTimeout subclasses and ourselves should
391 * This is used to mark the beginning of a new loop cycle by the
392 * first handler fired within that cycle.
395 bool bumpHandlingTime();
397 class SmoothLoopTime {
399 explicit SmoothLoopTime(uint64_t timeInterval)
400 : expCoeff_(-1.0/timeInterval)
402 , oldBusyLeftover_(0) {
403 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
406 void setTimeInterval(uint64_t timeInterval);
407 void reset(double value = 0.0);
409 void addSample(int64_t idle, int64_t busy);
415 void dampen(double factor) {
422 int64_t oldBusyLeftover_;
426 const std::shared_ptr<EventBaseObserver>& observer) {
427 observer_ = observer;
430 const std::shared_ptr<EventBaseObserver>& getObserver() {
435 * Set the name of the thread that runs this event base.
437 void setName(const std::string& name);
440 * Returns the name of the thread that runs this event base.
442 const std::string& getName();
447 void attachTimeoutManager(AsyncTimeout* obj,
448 TimeoutManager::InternalEnum internal);
450 void detachTimeoutManager(AsyncTimeout* obj);
452 bool scheduleTimeout(AsyncTimeout* obj, std::chrono::milliseconds timeout);
454 void cancelTimeout(AsyncTimeout* obj);
456 bool isInTimeoutManagerThread() {
457 return isInEventBaseThread();
460 // Helper class used to short circuit runInEventBaseThread
461 class RunInLoopCallback : public LoopCallback {
463 RunInLoopCallback(void (*fn)(void*), void* arg);
464 void runLoopCallback() noexcept;
472 * Helper function that tells us whether we have already handled
473 * some event/timeout/callback in this loop iteration.
475 bool nothingHandledYet();
477 // --------- libevent callbacks (not for client use) ------------
479 static void runFunctionPtr(std::function<void()>* fn);
481 // small object used as a callback arg with enough info to execute the
482 // appropriate client-provided Cob
483 class CobTimeout : public AsyncTimeout {
485 CobTimeout(EventBase* b, const Cob& c, TimeoutManager::InternalEnum in)
486 : AsyncTimeout(b, in), cob_(c) {}
488 virtual void timeoutExpired() noexcept;
494 typedef boost::intrusive::list_member_hook<
495 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
499 typedef boost::intrusive::list<
501 boost::intrusive::member_hook<CobTimeout, ListHook, &CobTimeout::hook>,
502 boost::intrusive::constant_time_size<false> > List;
505 typedef LoopCallback::List LoopCallbackList;
506 class FunctionRunner;
508 bool loopBody(int flags = 0);
510 // executes any callbacks queued by runInLoop(); returns false if none found
511 bool runLoopCallbacks(bool setContext = true);
513 void initNotificationQueue();
515 CobTimeout::List pendingCobTimeouts_;
517 LoopCallbackList loopCallbacks_;
518 LoopCallbackList onDestructionCallbacks_;
520 // This will be null most of the time, but point to currentCallbacks
521 // if we are in the middle of running loop callbacks, such that
522 // runInLoop(..., true) will always run in the current loop
524 LoopCallbackList* runOnceCallbacks_;
526 // stop_ is set by terminateLoopSoon() and is used by the main loop
527 // to determine if it should exit
530 // The ID of the thread running the main loop.
531 // 0 if loop is not running.
532 // Note: POSIX doesn't guarantee that 0 is an invalid pthread_t (or
533 // even that atomic<pthread_t> is valid), but that's how it is
534 // everywhere (at least on Linux, FreeBSD, and OSX).
535 std::atomic<pthread_t> loopThread_;
537 // pointer to underlying event_base class doing the heavy lifting
540 // A notification queue for runInEventBaseThread() to use
541 // to send function requests to the EventBase thread.
542 std::unique_ptr<NotificationQueue<std::pair<void (*)(void*), void*>>> queue_;
543 std::unique_ptr<FunctionRunner> fnRunner_;
545 // limit for latency in microseconds (0 disables)
548 // exponentially-smoothed average loop time for latency-limiting
549 SmoothLoopTime avgLoopTime_;
551 // smoothed loop time used to invoke latency callbacks; differs from
552 // avgLoopTime_ in that it's scaled down after triggering a callback
553 // to reduce spamminess
554 SmoothLoopTime maxLatencyLoopTime_;
556 // callback called when latency limit is exceeded
559 // we'll wait this long before running deferred callbacks if the event
561 static const int kDEFAULT_IDLE_WAIT_USEC = 20000; // 20ms
563 // Wrap-around loop counter to detect beginning of each loop
564 uint64_t nextLoopCnt_;
565 uint64_t latestLoopCnt_;
568 // Observer to export counters
569 std::shared_ptr<EventBaseObserver> observer_;
570 uint32_t observerSampleCount_;
572 // Name of the thread running this EventBase