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) 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.
58 // The function should never throw an exception, because we have no
59 // way of knowing what sort of error handling to perform.
61 // If it does throw, log a message and abort the program.
64 } catch (const std::exception& ex) {
65 LOG(ERROR) << "runInEventBaseThread() function threw a "
66 << typeid(ex).name() << " exception: " << ex.what();
69 LOG(ERROR) << "runInEventBaseThread() function threw an exception";
75 // The interface used to libevent is not thread-safe. Calls to
76 // event_init() and event_base_free() directly modify an internal
77 // global 'current_base', so a mutex is required to protect this.
79 // event_init() should only ever be called once. Subsequent calls
80 // should be made to event_base_new(). We can recognise that
81 // event_init() has already been called by simply inspecting current_base.
82 static std::mutex libevent_mutex_;
88 EventBase::EventBase(bool enableTimeMeasurement)
89 : runOnceCallbacks_(nullptr)
95 , avgLoopTime_(std::chrono::seconds(2))
96 , maxLatencyLoopTime_(avgLoopTime_)
97 , enableTimeMeasurement_(enableTimeMeasurement)
98 , nextLoopCnt_(uint64_t(-40)) // Early wrap-around so bugs will manifest soon
99 , latestLoopCnt_(nextLoopCnt_)
102 , observerSampleCount_(0)
103 , executionObserver_(nullptr) {
106 std::lock_guard<std::mutex> lock(libevent_mutex_);
108 // The value 'current_base' (libevent 1) or
109 // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
110 // allowing examination of its value without an explicit reference here.
111 // If ev.ev_base is NULL, then event_init() must be called, otherwise
112 // call event_base_new().
113 event_set(&ev, 0, 0, nullptr, nullptr);
120 evb_ = event_base_new();
123 if (UNLIKELY(evb_ == nullptr)) {
124 LOG(ERROR) << "EventBase(): Failed to init event base.";
125 folly::throwSystemError("error in EventBase::EventBase()");
127 VLOG(5) << "EventBase(): Created.";
128 initNotificationQueue();
129 RequestContext::saveContext();
132 // takes ownership of the event_base
133 EventBase::EventBase(event_base* evb, bool enableTimeMeasurement)
134 : runOnceCallbacks_(nullptr)
141 , avgLoopTime_(std::chrono::seconds(2))
142 , maxLatencyLoopTime_(avgLoopTime_)
143 , enableTimeMeasurement_(enableTimeMeasurement)
144 , nextLoopCnt_(uint64_t(-40)) // Early wrap-around so bugs will manifest soon
145 , latestLoopCnt_(nextLoopCnt_)
148 , observerSampleCount_(0)
149 , executionObserver_(nullptr) {
150 if (UNLIKELY(evb_ == nullptr)) {
151 LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
152 throw std::invalid_argument("EventBase(): event base cannot be nullptr");
154 initNotificationQueue();
155 RequestContext::saveContext();
158 EventBase::~EventBase() {
159 std::future<void> virtualEventBaseDestroyFuture;
160 if (virtualEventBase_) {
161 virtualEventBaseDestroyFuture = virtualEventBase_->destroy();
164 // Keep looping until all keep-alive handles are released. Each keep-alive
165 // handle signals that some external code will still schedule some work on
166 // this EventBase (so it's not safe to destroy it).
167 while (loopKeepAliveCount() > 0) {
168 applyLoopKeepAlive();
172 if (virtualEventBaseDestroyFuture.valid()) {
173 virtualEventBaseDestroyFuture.get();
176 // Call all destruction callbacks, before we start cleaning up our state.
177 while (!onDestructionCallbacks_.empty()) {
178 LoopCallback* callback = &onDestructionCallbacks_.front();
179 onDestructionCallbacks_.pop_front();
180 callback->runLoopCallback();
185 DCHECK_EQ(0u, runBeforeLoopCallbacks_.size());
187 (void)runLoopCallbacks();
189 if (!fnRunner_->consumeUntilDrained()) {
190 LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
193 // Stop consumer before deleting NotificationQueue
194 fnRunner_->stopConsuming();
196 std::lock_guard<std::mutex> lock(libevent_mutex_);
197 event_base_free(evb_);
201 std::lock_guard<std::mutex> lock(localStorageMutex_);
202 for (auto storage : localStorageToDtor_) {
203 storage->onEventBaseDestruction(*this);
206 VLOG(5) << "EventBase(): Destroyed.";
209 size_t EventBase::getNotificationQueueSize() const {
210 return queue_->size();
213 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
214 fnRunner_->setMaxReadAtOnce(maxAtOnce);
217 // Set smoothing coefficient for loop load average; input is # of milliseconds
218 // for exp(-1) decay.
219 void EventBase::setLoadAvgMsec(std::chrono::milliseconds ms) {
220 assert(enableTimeMeasurement_);
221 std::chrono::microseconds us = std::chrono::milliseconds(ms);
222 if (ms > std::chrono::milliseconds::zero()) {
223 maxLatencyLoopTime_.setTimeInterval(us);
224 avgLoopTime_.setTimeInterval(us);
226 LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
230 void EventBase::resetLoadAvg(double value) {
231 assert(enableTimeMeasurement_);
232 avgLoopTime_.reset(value);
233 maxLatencyLoopTime_.reset(value);
236 static std::chrono::milliseconds
237 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
238 auto result = std::chrono::steady_clock::now() - *prev;
239 *prev = std::chrono::steady_clock::now();
241 return std::chrono::duration_cast<std::chrono::milliseconds>(result);
244 void EventBase::waitUntilRunning() {
245 while (!isRunning()) {
246 std::this_thread::yield();
250 // enters the event_base loop -- will only exit when forced to
251 bool EventBase::loop() {
255 bool EventBase::loopOnce(int flags) {
256 return loopBody(flags | EVLOOP_ONCE);
259 bool EventBase::loopBody(int flags) {
260 VLOG(5) << "EventBase(): Starting loop.";
262 DCHECK(!invokingLoop_)
263 << "Your code just tried to loop over an event base from inside another "
264 << "event base loop. Since libevent is not reentrant, this leads to "
265 << "undefined behavior in opt builds. Please fix immediately. For the "
266 << "common case of an inner function that needs to do some synchronous "
267 << "computation on an event-base, replace getEventBase() by a new, "
268 << "stack-allocated EvenBase.";
269 invokingLoop_ = true;
271 invokingLoop_ = false;
275 bool ranLoopCallbacks;
276 bool blocking = !(flags & EVLOOP_NONBLOCK);
277 bool once = (flags & EVLOOP_ONCE);
279 // time-measurement variables.
280 std::chrono::steady_clock::time_point prev;
281 std::chrono::steady_clock::time_point idleStart = {};
282 std::chrono::microseconds busy;
283 std::chrono::microseconds idle;
285 loopThread_.store(std::this_thread::get_id(), std::memory_order_release);
287 if (!name_.empty()) {
288 setThreadName(name_);
291 if (enableTimeMeasurement_) {
292 prev = std::chrono::steady_clock::now();
293 idleStart = std::chrono::steady_clock::now();
296 while (!stop_.load(std::memory_order_acquire)) {
297 applyLoopKeepAlive();
300 // Run the before loop callbacks
301 LoopCallbackList callbacks;
302 callbacks.swap(runBeforeLoopCallbacks_);
304 while(!callbacks.empty()) {
305 auto* item = &callbacks.front();
306 callbacks.pop_front();
307 item->runLoopCallback();
310 // nobody can add loop callbacks from within this thread if
311 // we don't have to handle anything to start with...
312 if (blocking && loopCallbacks_.empty()) {
313 res = event_base_loop(evb_, EVLOOP_ONCE);
315 res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
318 ranLoopCallbacks = runLoopCallbacks();
320 if (enableTimeMeasurement_) {
321 busy = std::chrono::duration_cast<std::chrono::microseconds>(
322 std::chrono::steady_clock::now() - startWork_);
323 idle = std::chrono::duration_cast<std::chrono::microseconds>(
324 startWork_ - idleStart);
326 avgLoopTime_.addSample(std::chrono::microseconds(idle),
327 std::chrono::microseconds(busy));
328 maxLatencyLoopTime_.addSample(std::chrono::microseconds(idle),
329 std::chrono::microseconds(busy));
332 if (observerSampleCount_++ == observer_->getSampleRate()) {
333 observerSampleCount_ = 0;
334 observer_->loopSample(busy.count(), idle.count());
338 VLOG(11) << "EventBase " << this << " did not timeout " <<
339 " loop time guess: " << (busy + idle).count() <<
340 " idle time: " << idle.count() <<
341 " busy time: " << busy.count() <<
342 " avgLoopTime: " << avgLoopTime_.get() <<
343 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
344 " maxLatency_: " << maxLatency_.count() << "us" <<
345 " notificationQueueSize: " << getNotificationQueueSize() <<
346 " nothingHandledYet(): " << nothingHandledYet();
348 // see if our average loop time has exceeded our limit
349 if ((maxLatency_ > std::chrono::microseconds::zero()) &&
350 (maxLatencyLoopTime_.get() > double(maxLatency_.count()))) {
352 // back off temporarily -- don't keep spamming maxLatencyCob_
353 // if we're only a bit over the limit
354 maxLatencyLoopTime_.dampen(0.9);
357 // Our loop run did real work; reset the idle timer
358 idleStart = std::chrono::steady_clock::now();
360 VLOG(11) << "EventBase " << this << " did not timeout";
363 // If the event loop indicate that there were no more events, and
364 // we also didn't have any loop callbacks to run, there is nothing left to
366 if (res != 0 && !ranLoopCallbacks) {
367 // Since Notification Queue is marked 'internal' some events may not have
368 // run. Run them manually if so, and continue looping.
370 if (getNotificationQueueSize() > 0) {
371 fnRunner_->handlerReady(0);
377 if (enableTimeMeasurement_) {
378 VLOG(11) << "EventBase " << this << " loop time: " <<
379 getTimeDelta(&prev).count();
386 // Reset stop_ so loop() can be called again
390 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
392 } else if (res == 1) {
393 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
394 } else if (res > 1) {
395 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
399 loopThread_.store({}, std::memory_order_release);
401 VLOG(5) << "EventBase(): Done with loop.";
405 ssize_t EventBase::loopKeepAliveCount() {
406 if (loopKeepAliveCountAtomic_.load(std::memory_order_relaxed)) {
407 loopKeepAliveCount_ +=
408 loopKeepAliveCountAtomic_.exchange(0, std::memory_order_relaxed);
410 DCHECK_GE(loopKeepAliveCount_, 0);
412 return loopKeepAliveCount_;
415 void EventBase::applyLoopKeepAlive() {
416 auto keepAliveCount = loopKeepAliveCount();
417 // Make sure default VirtualEventBase won't hold EventBase::loop() forever.
418 if (virtualEventBase_ && virtualEventBase_->keepAliveCount() == 1) {
422 if (loopKeepAliveActive_ && keepAliveCount == 0) {
423 // Restore the notification queue internal flag
424 fnRunner_->stopConsuming();
425 fnRunner_->startConsumingInternal(this, queue_.get());
426 loopKeepAliveActive_ = false;
427 } else if (!loopKeepAliveActive_ && keepAliveCount > 0) {
428 // Update the notification queue event to treat it as a normal
429 // (non-internal) event. The notification queue event always remains
430 // installed, and the main loop won't exit with it installed.
431 fnRunner_->stopConsuming();
432 fnRunner_->startConsuming(this, queue_.get());
433 loopKeepAliveActive_ = true;
437 void EventBase::loopForever() {
441 applyLoopKeepAlive();
443 // Make sure notification queue events are treated as normal events.
444 // We can't use loopKeepAlive() here since LoopKeepAlive token can only be
445 // released inside a loop.
446 ++loopKeepAliveCount_;
448 --loopKeepAliveCount_;
454 folly::throwSystemError("error in EventBase::loopForever()");
458 void EventBase::bumpHandlingTime() {
459 if (!enableTimeMeasurement_) {
463 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
464 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
465 if (nothingHandledYet()) {
466 latestLoopCnt_ = nextLoopCnt_;
468 startWork_ = std::chrono::steady_clock::now();
470 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
471 << " (loop) startWork_ " << startWork_.time_since_epoch().count();
475 void EventBase::terminateLoopSoon() {
476 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
478 // Set stop to true, so the event loop will know to exit.
479 // TODO: We should really use an atomic operation here with a release
483 // Call event_base_loopbreak() so that libevent will exit the next time
485 event_base_loopbreak(evb_);
487 // If terminateLoopSoon() is called from another thread,
488 // the EventBase thread might be stuck waiting for events.
489 // In this case, it won't wake up and notice that stop_ is set until it
490 // receives another event. Send an empty frame to the notification queue
491 // so that the event loop will wake up even if there are no other events.
493 // We don't care about the return value of trySendFrame(). If it fails
494 // this likely means the EventBase already has lots of events waiting
497 queue_->putMessage(nullptr);
499 // We don't care if putMessage() fails. This likely means
500 // the EventBase already has lots of events waiting anyway.
504 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
505 DCHECK(isInEventBaseThread());
506 callback->cancelLoopCallback();
507 callback->context_ = RequestContext::saveContext();
508 if (runOnceCallbacks_ != nullptr && thisIteration) {
509 runOnceCallbacks_->push_back(*callback);
511 loopCallbacks_.push_back(*callback);
515 void EventBase::runInLoop(Func cob, bool thisIteration) {
516 DCHECK(isInEventBaseThread());
517 auto wrapper = new FunctionLoopCallback(std::move(cob));
518 wrapper->context_ = RequestContext::saveContext();
519 if (runOnceCallbacks_ != nullptr && thisIteration) {
520 runOnceCallbacks_->push_back(*wrapper);
522 loopCallbacks_.push_back(*wrapper);
526 void EventBase::runOnDestruction(LoopCallback* callback) {
527 std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
528 callback->cancelLoopCallback();
529 onDestructionCallbacks_.push_back(*callback);
532 void EventBase::runBeforeLoop(LoopCallback* callback) {
533 DCHECK(isInEventBaseThread());
534 callback->cancelLoopCallback();
535 runBeforeLoopCallbacks_.push_back(*callback);
538 bool EventBase::runInEventBaseThread(Func fn) {
540 // It will be received by the FunctionRunner in the EventBase's thread.
542 // We try not to schedule nullptr callbacks
544 LOG(ERROR) << "EventBase " << this
545 << ": Scheduling nullptr callbacks is not allowed";
549 // Short-circuit if we are already in our event base
550 if (inRunningEventBaseThread()) {
551 runInLoop(std::move(fn));
557 queue_->putMessage(std::move(fn));
558 } catch (const std::exception& ex) {
559 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
560 << "for EventBase thread: " << ex.what();
567 bool EventBase::runInEventBaseThreadAndWait(FuncRef fn) {
568 if (inRunningEventBaseThread()) {
569 LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
576 std::condition_variable cv;
577 runInEventBaseThread([&] {
579 std::unique_lock<std::mutex> l(m);
582 // We cannot release the lock before notify_one, because a spurious
583 // wakeup in the waiting thread may lead to cv and m going out of scope
588 std::unique_lock<std::mutex> l(m);
589 cv.wait(l, [&] { return ready; });
594 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(FuncRef fn) {
595 if (isInEventBaseThread()) {
599 return runInEventBaseThreadAndWait(std::move(fn));
603 bool EventBase::runLoopCallbacks() {
604 if (!loopCallbacks_.empty()) {
606 // Swap the loopCallbacks_ list with a temporary list on our stack.
607 // This way we will only run callbacks scheduled at the time
608 // runLoopCallbacks() was invoked.
610 // If any of these callbacks in turn call runInLoop() to schedule more
611 // callbacks, those new callbacks won't be run until the next iteration
612 // around the event loop. This prevents runInLoop() callbacks from being
613 // able to start file descriptor and timeout based events.
614 LoopCallbackList currentCallbacks;
615 currentCallbacks.swap(loopCallbacks_);
616 runOnceCallbacks_ = ¤tCallbacks;
618 while (!currentCallbacks.empty()) {
619 LoopCallback* callback = ¤tCallbacks.front();
620 currentCallbacks.pop_front();
621 folly::RequestContextScopeGuard rctx(callback->context_);
622 callback->runLoopCallback();
625 runOnceCallbacks_ = nullptr;
631 void EventBase::initNotificationQueue() {
632 // Infinite size queue
633 queue_.reset(new NotificationQueue<Func>());
635 // We allocate fnRunner_ separately, rather than declaring it directly
636 // as a member of EventBase solely so that we don't need to include
637 // NotificationQueue.h from EventBase.h
638 fnRunner_.reset(new FunctionRunner());
640 // Mark this as an internal event, so event_base_loop() will return if
641 // there are no other events besides this one installed.
643 // Most callers don't care about the internal notification queue used by
644 // EventBase. The queue is always installed, so if we did count the queue as
645 // an active event, loop() would never exit with no more events to process.
646 // Users can use loopForever() if they do care about the notification queue.
647 // (This is useful for EventBase threads that do nothing but process
648 // runInEventBaseThread() notifications.)
649 fnRunner_->startConsumingInternal(this, queue_.get());
652 void EventBase::SmoothLoopTime::setTimeInterval(
653 std::chrono::microseconds timeInterval) {
654 expCoeff_ = -1.0 / timeInterval.count();
655 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
658 void EventBase::SmoothLoopTime::reset(double value) {
662 void EventBase::SmoothLoopTime::addSample(
663 std::chrono::microseconds idle,
664 std::chrono::microseconds busy) {
666 * Position at which the busy sample is considered to be taken.
667 * (Allows to quickly skew our average without editing much code)
669 enum BusySamplePosition {
670 RIGHT = 0, // busy sample placed at the end of the iteration
671 CENTER = 1, // busy sample placed at the middle point of the iteration
672 LEFT = 2, // busy sample placed at the beginning of the iteration
675 // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
676 // and D676020 for more info on this calculation.
677 VLOG(11) << "idle " << idle.count() << " oldBusyLeftover_ "
678 << oldBusyLeftover_.count() << " idle + oldBusyLeftover_ "
679 << (idle + oldBusyLeftover_).count() << " busy " << busy.count()
680 << " " << __PRETTY_FUNCTION__;
681 idle += oldBusyLeftover_ + busy;
682 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
683 idle -= oldBusyLeftover_;
685 double coeff = exp(idle.count() * expCoeff_);
687 value_ += (1.0 - coeff) * busy.count();
690 bool EventBase::nothingHandledYet() const noexcept {
691 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
692 return (nextLoopCnt_ != latestLoopCnt_);
695 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
696 InternalEnum internal) {
698 struct event* ev = obj->getEvent();
699 assert(ev->ev_base == nullptr);
701 event_base_set(getLibeventBase(), ev);
702 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
703 // Set the EVLIST_INTERNAL flag
704 event_ref_flags(ev) |= EVLIST_INTERNAL;
708 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
710 struct event* ev = obj->getEvent();
711 ev->ev_base = nullptr;
714 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
715 TimeoutManager::timeout_type timeout) {
716 assert(isInEventBaseThread());
717 // Set up the timeval and add the event
719 tv.tv_sec = long(timeout.count() / 1000LL);
720 tv.tv_usec = long((timeout.count() % 1000LL) * 1000LL);
722 struct event* ev = obj->getEvent();
723 if (event_add(ev, &tv) < 0) {
724 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
731 void EventBase::cancelTimeout(AsyncTimeout* obj) {
732 assert(isInEventBaseThread());
733 struct event* ev = obj->getEvent();
734 if (EventUtil::isEventRegistered(ev)) {
739 void EventBase::setName(const std::string& name) {
740 assert(isInEventBaseThread());
744 setThreadName(loopThread_.load(std::memory_order_relaxed),
749 const std::string& EventBase::getName() {
750 assert(isInEventBaseThread());
754 const char* EventBase::getLibeventVersion() { return event_get_version(); }
755 const char* EventBase::getLibeventMethod() { return event_get_method(); }
757 VirtualEventBase& EventBase::getVirtualEventBase() {
758 folly::call_once(virtualEventBaseInitFlag_, [&] {
759 virtualEventBase_ = folly::make_unique<VirtualEventBase>(*this);
762 return *virtualEventBase_;