2 * Copyright 2017 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.
17 #ifndef __STDC_FORMAT_MACROS
18 #define __STDC_FORMAT_MACROS
21 #include <folly/io/async/EventBase.h>
22 #include <folly/io/async/VirtualEventBase.h>
24 #include <folly/Memory.h>
25 #include <folly/ThreadName.h>
26 #include <folly/io/async/NotificationQueue.h>
27 #include <folly/portability/Unistd.h>
29 #include <condition_variable>
37 * EventBase::FunctionRunner
40 class EventBase::FunctionRunner
41 : public NotificationQueue<EventBase::Func>::Consumer {
43 void messageAvailable(Func&& msg) noexcept override {
44 // In libevent2, internal events do not break the loop.
45 // Most users would expect loop(), followed by runInEventBaseThread(),
46 // to break the loop and check if it should exit or not.
47 // To have similar bejaviour to libevent1.4, tell the loop to break here.
48 // Note that loop() may still continue to loop, but it will also check the
49 // stop_ flag as well as runInLoop callbacks, etc.
50 event_base_loopbreak(getEventBase()->evb_);
53 // terminateLoopSoon() sends a null message just to
54 // wake up the loop. We can ignore these messages.
61 // The interface used to libevent is not thread-safe. Calls to
62 // event_init() and event_base_free() directly modify an internal
63 // global 'current_base', so a mutex is required to protect this.
65 // event_init() should only ever be called once. Subsequent calls
66 // should be made to event_base_new(). We can recognise that
67 // event_init() has already been called by simply inspecting current_base.
68 static std::mutex libevent_mutex_;
74 EventBase::EventBase(bool enableTimeMeasurement)
75 : runOnceCallbacks_(nullptr)
81 , avgLoopTime_(std::chrono::seconds(2))
82 , maxLatencyLoopTime_(avgLoopTime_)
83 , enableTimeMeasurement_(enableTimeMeasurement)
84 , nextLoopCnt_(uint64_t(-40)) // Early wrap-around so bugs will manifest soon
85 , latestLoopCnt_(nextLoopCnt_)
88 , observerSampleCount_(0)
89 , executionObserver_(nullptr) {
92 std::lock_guard<std::mutex> lock(libevent_mutex_);
94 // The value 'current_base' (libevent 1) or
95 // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
96 // allowing examination of its value without an explicit reference here.
97 // If ev.ev_base is NULL, then event_init() must be called, otherwise
98 // call event_base_new().
99 event_set(&ev, 0, 0, nullptr, nullptr);
106 evb_ = event_base_new();
109 if (UNLIKELY(evb_ == nullptr)) {
110 LOG(ERROR) << "EventBase(): Failed to init event base.";
111 folly::throwSystemError("error in EventBase::EventBase()");
113 VLOG(5) << "EventBase(): Created.";
114 initNotificationQueue();
115 RequestContext::saveContext();
118 // takes ownership of the event_base
119 EventBase::EventBase(event_base* evb, bool enableTimeMeasurement)
120 : runOnceCallbacks_(nullptr)
127 , avgLoopTime_(std::chrono::seconds(2))
128 , maxLatencyLoopTime_(avgLoopTime_)
129 , enableTimeMeasurement_(enableTimeMeasurement)
130 , nextLoopCnt_(uint64_t(-40)) // Early wrap-around so bugs will manifest soon
131 , latestLoopCnt_(nextLoopCnt_)
134 , observerSampleCount_(0)
135 , executionObserver_(nullptr) {
136 if (UNLIKELY(evb_ == nullptr)) {
137 LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
138 throw std::invalid_argument("EventBase(): event base cannot be nullptr");
140 initNotificationQueue();
141 RequestContext::saveContext();
144 EventBase::~EventBase() {
145 std::future<void> virtualEventBaseDestroyFuture;
146 if (virtualEventBase_) {
147 virtualEventBaseDestroyFuture = virtualEventBase_->destroy();
150 // Keep looping until all keep-alive handles are released. Each keep-alive
151 // handle signals that some external code will still schedule some work on
152 // this EventBase (so it's not safe to destroy it).
153 while (loopKeepAliveCount() > 0) {
154 applyLoopKeepAlive();
158 if (virtualEventBaseDestroyFuture.valid()) {
159 virtualEventBaseDestroyFuture.get();
162 // Call all destruction callbacks, before we start cleaning up our state.
163 while (!onDestructionCallbacks_.empty()) {
164 LoopCallback* callback = &onDestructionCallbacks_.front();
165 onDestructionCallbacks_.pop_front();
166 callback->runLoopCallback();
171 DCHECK_EQ(0u, runBeforeLoopCallbacks_.size());
173 (void)runLoopCallbacks();
175 if (!fnRunner_->consumeUntilDrained()) {
176 LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
179 // Stop consumer before deleting NotificationQueue
180 fnRunner_->stopConsuming();
182 std::lock_guard<std::mutex> lock(libevent_mutex_);
183 event_base_free(evb_);
186 for (auto storage : localStorageToDtor_) {
187 storage->onEventBaseDestruction(*this);
190 VLOG(5) << "EventBase(): Destroyed.";
193 size_t EventBase::getNotificationQueueSize() const {
194 return queue_->size();
197 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
198 fnRunner_->setMaxReadAtOnce(maxAtOnce);
201 // Set smoothing coefficient for loop load average; input is # of milliseconds
202 // for exp(-1) decay.
203 void EventBase::setLoadAvgMsec(std::chrono::milliseconds ms) {
204 assert(enableTimeMeasurement_);
205 std::chrono::microseconds us = std::chrono::milliseconds(ms);
206 if (ms > std::chrono::milliseconds::zero()) {
207 maxLatencyLoopTime_.setTimeInterval(us);
208 avgLoopTime_.setTimeInterval(us);
210 LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
214 void EventBase::resetLoadAvg(double value) {
215 assert(enableTimeMeasurement_);
216 avgLoopTime_.reset(value);
217 maxLatencyLoopTime_.reset(value);
220 static std::chrono::milliseconds
221 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
222 auto result = std::chrono::steady_clock::now() - *prev;
223 *prev = std::chrono::steady_clock::now();
225 return std::chrono::duration_cast<std::chrono::milliseconds>(result);
228 void EventBase::waitUntilRunning() {
229 while (!isRunning()) {
230 std::this_thread::yield();
234 // enters the event_base loop -- will only exit when forced to
235 bool EventBase::loop() {
239 bool EventBase::loopOnce(int flags) {
240 return loopBody(flags | EVLOOP_ONCE);
243 bool EventBase::loopBody(int flags) {
244 VLOG(5) << "EventBase(): Starting loop.";
246 DCHECK(!invokingLoop_)
247 << "Your code just tried to loop over an event base from inside another "
248 << "event base loop. Since libevent is not reentrant, this leads to "
249 << "undefined behavior in opt builds. Please fix immediately. For the "
250 << "common case of an inner function that needs to do some synchronous "
251 << "computation on an event-base, replace getEventBase() by a new, "
252 << "stack-allocated EvenBase.";
253 invokingLoop_ = true;
255 invokingLoop_ = false;
259 bool ranLoopCallbacks;
260 bool blocking = !(flags & EVLOOP_NONBLOCK);
261 bool once = (flags & EVLOOP_ONCE);
263 // time-measurement variables.
264 std::chrono::steady_clock::time_point prev;
265 std::chrono::steady_clock::time_point idleStart = {};
266 std::chrono::microseconds busy;
267 std::chrono::microseconds idle;
269 loopThread_.store(std::this_thread::get_id(), std::memory_order_release);
271 if (!name_.empty()) {
272 setThreadName(name_);
275 if (enableTimeMeasurement_) {
276 prev = std::chrono::steady_clock::now();
277 idleStart = std::chrono::steady_clock::now();
280 while (!stop_.load(std::memory_order_acquire)) {
281 applyLoopKeepAlive();
284 // Run the before loop callbacks
285 LoopCallbackList callbacks;
286 callbacks.swap(runBeforeLoopCallbacks_);
288 while(!callbacks.empty()) {
289 auto* item = &callbacks.front();
290 callbacks.pop_front();
291 item->runLoopCallback();
294 // nobody can add loop callbacks from within this thread if
295 // we don't have to handle anything to start with...
296 if (blocking && loopCallbacks_.empty()) {
297 res = event_base_loop(evb_, EVLOOP_ONCE);
299 res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
302 ranLoopCallbacks = runLoopCallbacks();
304 if (enableTimeMeasurement_) {
305 busy = std::chrono::duration_cast<std::chrono::microseconds>(
306 std::chrono::steady_clock::now() - startWork_);
307 idle = std::chrono::duration_cast<std::chrono::microseconds>(
308 startWork_ - idleStart);
310 avgLoopTime_.addSample(std::chrono::microseconds(idle),
311 std::chrono::microseconds(busy));
312 maxLatencyLoopTime_.addSample(std::chrono::microseconds(idle),
313 std::chrono::microseconds(busy));
316 if (observerSampleCount_++ == observer_->getSampleRate()) {
317 observerSampleCount_ = 0;
318 observer_->loopSample(busy.count(), idle.count());
322 VLOG(11) << "EventBase " << this << " did not timeout " <<
323 " loop time guess: " << (busy + idle).count() <<
324 " idle time: " << idle.count() <<
325 " busy time: " << busy.count() <<
326 " avgLoopTime: " << avgLoopTime_.get() <<
327 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
328 " maxLatency_: " << maxLatency_.count() << "us" <<
329 " notificationQueueSize: " << getNotificationQueueSize() <<
330 " nothingHandledYet(): " << nothingHandledYet();
332 // see if our average loop time has exceeded our limit
333 if ((maxLatency_ > std::chrono::microseconds::zero()) &&
334 (maxLatencyLoopTime_.get() > double(maxLatency_.count()))) {
336 // back off temporarily -- don't keep spamming maxLatencyCob_
337 // if we're only a bit over the limit
338 maxLatencyLoopTime_.dampen(0.9);
341 // Our loop run did real work; reset the idle timer
342 idleStart = std::chrono::steady_clock::now();
344 VLOG(11) << "EventBase " << this << " did not timeout";
347 // If the event loop indicate that there were no more events, and
348 // we also didn't have any loop callbacks to run, there is nothing left to
350 if (res != 0 && !ranLoopCallbacks) {
351 // Since Notification Queue is marked 'internal' some events may not have
352 // run. Run them manually if so, and continue looping.
354 if (getNotificationQueueSize() > 0) {
355 fnRunner_->handlerReady(0);
361 if (enableTimeMeasurement_) {
362 VLOG(11) << "EventBase " << this << " loop time: " <<
363 getTimeDelta(&prev).count();
370 // Reset stop_ so loop() can be called again
374 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
376 } else if (res == 1) {
377 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
378 } else if (res > 1) {
379 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
383 loopThread_.store({}, std::memory_order_release);
385 VLOG(5) << "EventBase(): Done with loop.";
389 ssize_t EventBase::loopKeepAliveCount() {
390 if (loopKeepAliveCountAtomic_.load(std::memory_order_relaxed)) {
391 loopKeepAliveCount_ +=
392 loopKeepAliveCountAtomic_.exchange(0, std::memory_order_relaxed);
394 DCHECK_GE(loopKeepAliveCount_, 0);
396 return loopKeepAliveCount_;
399 void EventBase::applyLoopKeepAlive() {
400 auto keepAliveCount = loopKeepAliveCount();
401 // Make sure default VirtualEventBase won't hold EventBase::loop() forever.
402 if (virtualEventBase_ && virtualEventBase_->keepAliveCount() == 1) {
406 if (loopKeepAliveActive_ && keepAliveCount == 0) {
407 // Restore the notification queue internal flag
408 fnRunner_->stopConsuming();
409 fnRunner_->startConsumingInternal(this, queue_.get());
410 loopKeepAliveActive_ = false;
411 } else if (!loopKeepAliveActive_ && keepAliveCount > 0) {
412 // Update the notification queue event to treat it as a normal
413 // (non-internal) event. The notification queue event always remains
414 // installed, and the main loop won't exit with it installed.
415 fnRunner_->stopConsuming();
416 fnRunner_->startConsuming(this, queue_.get());
417 loopKeepAliveActive_ = true;
421 void EventBase::loopForever() {
425 applyLoopKeepAlive();
427 // Make sure notification queue events are treated as normal events.
428 // We can't use loopKeepAlive() here since LoopKeepAlive token can only be
429 // released inside a loop.
430 ++loopKeepAliveCount_;
432 --loopKeepAliveCount_;
438 folly::throwSystemError("error in EventBase::loopForever()");
442 void EventBase::bumpHandlingTime() {
443 if (!enableTimeMeasurement_) {
447 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
448 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
449 if (nothingHandledYet()) {
450 latestLoopCnt_ = nextLoopCnt_;
452 startWork_ = std::chrono::steady_clock::now();
454 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
455 << " (loop) startWork_ " << startWork_.time_since_epoch().count();
459 void EventBase::terminateLoopSoon() {
460 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
462 // Set stop to true, so the event loop will know to exit.
463 // TODO: We should really use an atomic operation here with a release
467 // Call event_base_loopbreak() so that libevent will exit the next time
469 event_base_loopbreak(evb_);
471 // If terminateLoopSoon() is called from another thread,
472 // the EventBase thread might be stuck waiting for events.
473 // In this case, it won't wake up and notice that stop_ is set until it
474 // receives another event. Send an empty frame to the notification queue
475 // so that the event loop will wake up even if there are no other events.
477 // We don't care about the return value of trySendFrame(). If it fails
478 // this likely means the EventBase already has lots of events waiting
481 queue_->putMessage(nullptr);
483 // We don't care if putMessage() fails. This likely means
484 // the EventBase already has lots of events waiting anyway.
488 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
489 DCHECK(isInEventBaseThread());
490 callback->cancelLoopCallback();
491 callback->context_ = RequestContext::saveContext();
492 if (runOnceCallbacks_ != nullptr && thisIteration) {
493 runOnceCallbacks_->push_back(*callback);
495 loopCallbacks_.push_back(*callback);
499 void EventBase::runInLoop(Func cob, bool thisIteration) {
500 DCHECK(isInEventBaseThread());
501 auto wrapper = new FunctionLoopCallback(std::move(cob));
502 wrapper->context_ = RequestContext::saveContext();
503 if (runOnceCallbacks_ != nullptr && thisIteration) {
504 runOnceCallbacks_->push_back(*wrapper);
506 loopCallbacks_.push_back(*wrapper);
510 void EventBase::runOnDestruction(LoopCallback* callback) {
511 std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
512 callback->cancelLoopCallback();
513 onDestructionCallbacks_.push_back(*callback);
516 void EventBase::runBeforeLoop(LoopCallback* callback) {
517 DCHECK(isInEventBaseThread());
518 callback->cancelLoopCallback();
519 runBeforeLoopCallbacks_.push_back(*callback);
522 bool EventBase::runInEventBaseThread(Func fn) {
524 // It will be received by the FunctionRunner in the EventBase's thread.
526 // We try not to schedule nullptr callbacks
528 LOG(ERROR) << "EventBase " << this
529 << ": Scheduling nullptr callbacks is not allowed";
533 // Short-circuit if we are already in our event base
534 if (inRunningEventBaseThread()) {
535 runInLoop(std::move(fn));
541 queue_->putMessage(std::move(fn));
542 } catch (const std::exception& ex) {
543 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
544 << "for EventBase thread: " << ex.what();
551 bool EventBase::runInEventBaseThreadAndWait(FuncRef fn) {
552 if (inRunningEventBaseThread()) {
553 LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
560 std::condition_variable cv;
561 runInEventBaseThread([&] {
563 std::unique_lock<std::mutex> l(m);
566 // We cannot release the lock before notify_one, because a spurious
567 // wakeup in the waiting thread may lead to cv and m going out of scope
572 std::unique_lock<std::mutex> l(m);
573 cv.wait(l, [&] { return ready; });
578 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(FuncRef fn) {
579 if (isInEventBaseThread()) {
583 return runInEventBaseThreadAndWait(std::move(fn));
587 bool EventBase::runLoopCallbacks() {
588 if (!loopCallbacks_.empty()) {
590 // Swap the loopCallbacks_ list with a temporary list on our stack.
591 // This way we will only run callbacks scheduled at the time
592 // runLoopCallbacks() was invoked.
594 // If any of these callbacks in turn call runInLoop() to schedule more
595 // callbacks, those new callbacks won't be run until the next iteration
596 // around the event loop. This prevents runInLoop() callbacks from being
597 // able to start file descriptor and timeout based events.
598 LoopCallbackList currentCallbacks;
599 currentCallbacks.swap(loopCallbacks_);
600 runOnceCallbacks_ = ¤tCallbacks;
602 while (!currentCallbacks.empty()) {
603 LoopCallback* callback = ¤tCallbacks.front();
604 currentCallbacks.pop_front();
605 folly::RequestContextScopeGuard rctx(callback->context_);
606 callback->runLoopCallback();
609 runOnceCallbacks_ = nullptr;
615 void EventBase::initNotificationQueue() {
616 // Infinite size queue
617 queue_.reset(new NotificationQueue<Func>());
619 // We allocate fnRunner_ separately, rather than declaring it directly
620 // as a member of EventBase solely so that we don't need to include
621 // NotificationQueue.h from EventBase.h
622 fnRunner_.reset(new FunctionRunner());
624 // Mark this as an internal event, so event_base_loop() will return if
625 // there are no other events besides this one installed.
627 // Most callers don't care about the internal notification queue used by
628 // EventBase. The queue is always installed, so if we did count the queue as
629 // an active event, loop() would never exit with no more events to process.
630 // Users can use loopForever() if they do care about the notification queue.
631 // (This is useful for EventBase threads that do nothing but process
632 // runInEventBaseThread() notifications.)
633 fnRunner_->startConsumingInternal(this, queue_.get());
636 void EventBase::SmoothLoopTime::setTimeInterval(
637 std::chrono::microseconds timeInterval) {
638 expCoeff_ = -1.0 / timeInterval.count();
639 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
642 void EventBase::SmoothLoopTime::reset(double value) {
646 void EventBase::SmoothLoopTime::addSample(
647 std::chrono::microseconds idle,
648 std::chrono::microseconds busy) {
650 * Position at which the busy sample is considered to be taken.
651 * (Allows to quickly skew our average without editing much code)
653 enum BusySamplePosition {
654 RIGHT = 0, // busy sample placed at the end of the iteration
655 CENTER = 1, // busy sample placed at the middle point of the iteration
656 LEFT = 2, // busy sample placed at the beginning of the iteration
659 // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
660 // and D676020 for more info on this calculation.
661 VLOG(11) << "idle " << idle.count() << " oldBusyLeftover_ "
662 << oldBusyLeftover_.count() << " idle + oldBusyLeftover_ "
663 << (idle + oldBusyLeftover_).count() << " busy " << busy.count()
664 << " " << __PRETTY_FUNCTION__;
665 idle += oldBusyLeftover_ + busy;
666 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
667 idle -= oldBusyLeftover_;
669 double coeff = exp(idle.count() * expCoeff_);
671 value_ += (1.0 - coeff) * busy.count();
674 bool EventBase::nothingHandledYet() const noexcept {
675 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
676 return (nextLoopCnt_ != latestLoopCnt_);
679 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
680 InternalEnum internal) {
682 struct event* ev = obj->getEvent();
683 assert(ev->ev_base == nullptr);
685 event_base_set(getLibeventBase(), ev);
686 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
687 // Set the EVLIST_INTERNAL flag
688 event_ref_flags(ev) |= EVLIST_INTERNAL;
692 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
694 struct event* ev = obj->getEvent();
695 ev->ev_base = nullptr;
698 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
699 TimeoutManager::timeout_type timeout) {
700 assert(isInEventBaseThread());
701 // Set up the timeval and add the event
703 tv.tv_sec = long(timeout.count() / 1000LL);
704 tv.tv_usec = long((timeout.count() % 1000LL) * 1000LL);
706 struct event* ev = obj->getEvent();
707 if (event_add(ev, &tv) < 0) {
708 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
715 void EventBase::cancelTimeout(AsyncTimeout* obj) {
716 assert(isInEventBaseThread());
717 struct event* ev = obj->getEvent();
718 if (EventUtil::isEventRegistered(ev)) {
723 void EventBase::setName(const std::string& name) {
724 assert(isInEventBaseThread());
728 setThreadName(loopThread_.load(std::memory_order_relaxed),
733 const std::string& EventBase::getName() {
734 assert(isInEventBaseThread());
738 const char* EventBase::getLibeventVersion() { return event_get_version(); }
739 const char* EventBase::getLibeventMethod() { return event_get_method(); }
741 VirtualEventBase& EventBase::getVirtualEventBase() {
742 folly::call_once(virtualEventBaseInitFlag_, [&] {
743 virtualEventBase_ = folly::make_unique<VirtualEventBase>(*this);
746 return *virtualEventBase_;