2 * Copyright 2016 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>
23 #include <folly/ThreadName.h>
24 #include <folly/io/async/NotificationQueue.h>
26 #include <condition_variable>
34 using folly::EventBase;
36 class FunctionLoopCallback : public EventBase::LoopCallback {
38 explicit FunctionLoopCallback(EventBase::Func&& function)
39 : function_(std::move(function)) {}
41 void runLoopCallback() noexcept override {
47 EventBase::Func function_;
54 * EventBase::FunctionRunner
57 class EventBase::FunctionRunner
58 : public NotificationQueue<EventBase::Func>::Consumer {
60 void messageAvailable(Func&& msg) override {
61 // In libevent2, internal events do not break the loop.
62 // Most users would expect loop(), followed by runInEventBaseThread(),
63 // to break the loop and check if it should exit or not.
64 // To have similar bejaviour to libevent1.4, tell the loop to break here.
65 // Note that loop() may still continue to loop, but it will also check the
66 // stop_ flag as well as runInLoop callbacks, etc.
67 event_base_loopbreak(getEventBase()->evb_);
70 // terminateLoopSoon() sends a null message just to
71 // wake up the loop. We can ignore these messages.
75 // The function should never throw an exception, because we have no
76 // way of knowing what sort of error handling to perform.
78 // If it does throw, log a message and abort the program.
81 } catch (const std::exception& ex) {
82 LOG(ERROR) << "runInEventBaseThread() function threw a "
83 << typeid(ex).name() << " exception: " << ex.what();
86 LOG(ERROR) << "runInEventBaseThread() function threw an exception";
93 * EventBase::CobTimeout methods
96 void EventBase::CobTimeout::timeoutExpired() noexcept {
97 // For now, we just swallow any exceptions that the callback threw.
100 } catch (const std::exception& ex) {
101 LOG(ERROR) << "EventBase::runAfterDelay() callback threw "
102 << typeid(ex).name() << " exception: " << ex.what();
104 LOG(ERROR) << "EventBase::runAfterDelay() callback threw non-exception "
108 // The CobTimeout object was allocated on the heap by runAfterDelay(),
109 // so delete it now that the it has fired.
114 // The interface used to libevent is not thread-safe. Calls to
115 // event_init() and event_base_free() directly modify an internal
116 // global 'current_base', so a mutex is required to protect this.
118 // event_init() should only ever be called once. Subsequent calls
119 // should be made to event_base_new(). We can recognise that
120 // event_init() has already been called by simply inspecting current_base.
121 static std::mutex libevent_mutex_;
127 EventBase::EventBase(bool enableTimeMeasurement)
128 : runOnceCallbacks_(nullptr)
134 , avgLoopTime_(2000000)
135 , maxLatencyLoopTime_(avgLoopTime_)
136 , enableTimeMeasurement_(enableTimeMeasurement)
137 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
138 , latestLoopCnt_(nextLoopCnt_)
141 , observerSampleCount_(0)
142 , executionObserver_(nullptr) {
145 std::lock_guard<std::mutex> lock(libevent_mutex_);
147 // The value 'current_base' (libevent 1) or
148 // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
149 // allowing examination of its value without an explicit reference here.
150 // If ev.ev_base is NULL, then event_init() must be called, otherwise
151 // call event_base_new().
152 event_set(&ev, 0, 0, nullptr, nullptr);
159 evb_ = event_base_new();
162 if (UNLIKELY(evb_ == nullptr)) {
163 LOG(ERROR) << "EventBase(): Failed to init event base.";
164 folly::throwSystemError("error in EventBase::EventBase()");
166 VLOG(5) << "EventBase(): Created.";
167 initNotificationQueue();
168 RequestContext::saveContext();
171 // takes ownership of the event_base
172 EventBase::EventBase(event_base* evb, bool enableTimeMeasurement)
173 : runOnceCallbacks_(nullptr)
180 , avgLoopTime_(2000000)
181 , maxLatencyLoopTime_(avgLoopTime_)
182 , enableTimeMeasurement_(enableTimeMeasurement)
183 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
184 , latestLoopCnt_(nextLoopCnt_)
187 , observerSampleCount_(0)
188 , executionObserver_(nullptr) {
189 if (UNLIKELY(evb_ == nullptr)) {
190 LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
191 throw std::invalid_argument("EventBase(): event base cannot be nullptr");
193 initNotificationQueue();
194 RequestContext::saveContext();
197 EventBase::~EventBase() {
198 // Call all destruction callbacks, before we start cleaning up our state.
199 while (!onDestructionCallbacks_.empty()) {
200 LoopCallback* callback = &onDestructionCallbacks_.front();
201 onDestructionCallbacks_.pop_front();
202 callback->runLoopCallback();
205 // Delete any unfired callback objects, so that we don't leak memory
206 // (Note that we don't fire them. The caller is responsible for cleaning up
207 // its own data structures if it destroys the EventBase with unfired events
209 while (!pendingCobTimeouts_.empty()) {
210 CobTimeout* timeout = &pendingCobTimeouts_.front();
214 while (!runBeforeLoopCallbacks_.empty()) {
215 delete &runBeforeLoopCallbacks_.front();
218 (void) runLoopCallbacks(false);
220 if (!fnRunner_->consumeUntilDrained()) {
221 LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
224 // Stop consumer before deleting NotificationQueue
225 fnRunner_->stopConsuming();
227 std::lock_guard<std::mutex> lock(libevent_mutex_);
228 event_base_free(evb_);
231 while (!runAfterDrainCallbacks_.empty()) {
232 LoopCallback* callback = &runAfterDrainCallbacks_.front();
233 runAfterDrainCallbacks_.pop_front();
234 callback->runLoopCallback();
238 std::lock_guard<std::mutex> lock(localStorageMutex_);
239 for (auto storage : localStorageToDtor_) {
240 storage->onEventBaseDestruction(*this);
243 VLOG(5) << "EventBase(): Destroyed.";
246 int EventBase::getNotificationQueueSize() const {
247 return queue_->size();
250 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
251 fnRunner_->setMaxReadAtOnce(maxAtOnce);
254 // Set smoothing coefficient for loop load average; input is # of milliseconds
255 // for exp(-1) decay.
256 void EventBase::setLoadAvgMsec(uint32_t ms) {
257 assert(enableTimeMeasurement_);
258 uint64_t us = 1000 * ms;
260 maxLatencyLoopTime_.setTimeInterval(us);
261 avgLoopTime_.setTimeInterval(us);
263 LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
267 void EventBase::resetLoadAvg(double value) {
268 assert(enableTimeMeasurement_);
269 avgLoopTime_.reset(value);
270 maxLatencyLoopTime_.reset(value);
273 static std::chrono::milliseconds
274 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
275 auto result = std::chrono::steady_clock::now() - *prev;
276 *prev = std::chrono::steady_clock::now();
278 return std::chrono::duration_cast<std::chrono::milliseconds>(result);
281 void EventBase::waitUntilRunning() {
282 while (!isRunning()) {
287 // enters the event_base loop -- will only exit when forced to
288 bool EventBase::loop() {
292 bool EventBase::loopOnce(int flags) {
293 return loopBody(flags | EVLOOP_ONCE);
296 bool EventBase::loopBody(int flags) {
297 VLOG(5) << "EventBase(): Starting loop.";
299 bool ranLoopCallbacks;
300 bool blocking = !(flags & EVLOOP_NONBLOCK);
301 bool once = (flags & EVLOOP_ONCE);
303 // time-measurement variables.
304 std::chrono::steady_clock::time_point prev;
305 int64_t idleStart = 0;
309 loopThread_.store(pthread_self(), std::memory_order_release);
311 if (!name_.empty()) {
312 setThreadName(name_);
315 if (enableTimeMeasurement_) {
316 prev = std::chrono::steady_clock::now();
317 idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
318 std::chrono::steady_clock::now().time_since_epoch()).count();
321 while (!stop_.load(std::memory_order_acquire)) {
322 applyLoopKeepAlive();
325 // Run the before loop callbacks
326 LoopCallbackList callbacks;
327 callbacks.swap(runBeforeLoopCallbacks_);
329 while(!callbacks.empty()) {
330 auto* item = &callbacks.front();
331 callbacks.pop_front();
332 item->runLoopCallback();
335 // nobody can add loop callbacks from within this thread if
336 // we don't have to handle anything to start with...
337 if (blocking && loopCallbacks_.empty()) {
338 res = event_base_loop(evb_, EVLOOP_ONCE);
340 res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
343 ranLoopCallbacks = runLoopCallbacks();
345 if (enableTimeMeasurement_) {
346 busy = std::chrono::duration_cast<std::chrono::microseconds>(
347 std::chrono::steady_clock::now().time_since_epoch()).count() -
349 idle = startWork_ - idleStart;
351 avgLoopTime_.addSample(idle, busy);
352 maxLatencyLoopTime_.addSample(idle, busy);
355 if (observerSampleCount_++ == observer_->getSampleRate()) {
356 observerSampleCount_ = 0;
357 observer_->loopSample(busy, idle);
361 VLOG(11) << "EventBase " << this << " did not timeout "
362 " loop time guess: " << busy + idle <<
363 " idle time: " << idle <<
364 " busy time: " << busy <<
365 " avgLoopTime: " << avgLoopTime_.get() <<
366 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
367 " maxLatency_: " << maxLatency_ <<
368 " notificationQueueSize: " << getNotificationQueueSize() <<
369 " nothingHandledYet(): "<< nothingHandledYet();
371 // see if our average loop time has exceeded our limit
372 if ((maxLatency_ > 0) &&
373 (maxLatencyLoopTime_.get() > double(maxLatency_))) {
375 // back off temporarily -- don't keep spamming maxLatencyCob_
376 // if we're only a bit over the limit
377 maxLatencyLoopTime_.dampen(0.9);
380 // Our loop run did real work; reset the idle timer
381 idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
382 std::chrono::steady_clock::now().time_since_epoch()).count();
384 VLOG(11) << "EventBase " << this << " did not timeout";
387 // If the event loop indicate that there were no more events, and
388 // we also didn't have any loop callbacks to run, there is nothing left to
390 if (res != 0 && !ranLoopCallbacks) {
391 // Since Notification Queue is marked 'internal' some events may not have
392 // run. Run them manually if so, and continue looping.
394 if (getNotificationQueueSize() > 0) {
395 fnRunner_->handlerReady(0);
401 if (enableTimeMeasurement_) {
402 VLOG(5) << "EventBase " << this << " loop time: " <<
403 getTimeDelta(&prev).count();
410 // Reset stop_ so loop() can be called again
414 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
416 } else if (res == 1) {
417 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
418 } else if (res > 1) {
419 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
423 loopThread_.store({}, std::memory_order_release);
425 VLOG(5) << "EventBase(): Done with loop.";
429 void EventBase::applyLoopKeepAlive() {
430 if (loopKeepAliveActive_ && loopKeepAlive_.unique()) {
431 // Restore the notification queue internal flag
432 fnRunner_->stopConsuming();
433 fnRunner_->startConsumingInternal(this, queue_.get());
434 loopKeepAliveActive_ = false;
435 } else if (!loopKeepAliveActive_ && !loopKeepAlive_.unique()) {
436 // Update the notification queue event to treat it as a normal
437 // (non-internal) event. The notification queue event always remains
438 // installed, and the main loop won't exit with it installed.
439 fnRunner_->stopConsuming();
440 fnRunner_->startConsuming(this, queue_.get());
441 loopKeepAliveActive_ = true;
445 void EventBase::loopForever() {
449 applyLoopKeepAlive();
450 loopForeverActive_ = false;
452 loopForeverActive_ = true;
453 // Make sure notification queue events are treated as normal events.
454 auto loopKeepAlive = loopKeepAlive_;
459 folly::throwSystemError("error in EventBase::loopForever()");
463 void EventBase::bumpHandlingTime() {
464 if (!enableTimeMeasurement_) {
468 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
469 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
470 if (nothingHandledYet()) {
471 latestLoopCnt_ = nextLoopCnt_;
473 startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
474 std::chrono::steady_clock::now().time_since_epoch())
477 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
478 << " (loop) startWork_ " << startWork_;
482 void EventBase::terminateLoopSoon() {
483 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
485 // Set stop to true, so the event loop will know to exit.
486 // TODO: We should really use an atomic operation here with a release
490 // Call event_base_loopbreak() so that libevent will exit the next time
492 event_base_loopbreak(evb_);
494 // If terminateLoopSoon() is called from another thread,
495 // the EventBase thread might be stuck waiting for events.
496 // In this case, it won't wake up and notice that stop_ is set until it
497 // receives another event. Send an empty frame to the notification queue
498 // so that the event loop will wake up even if there are no other events.
500 // We don't care about the return value of trySendFrame(). If it fails
501 // this likely means the EventBase already has lots of events waiting
504 queue_->putMessage(nullptr);
506 // We don't care if putMessage() fails. This likely means
507 // the EventBase already has lots of events waiting anyway.
511 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
512 DCHECK(isInEventBaseThread());
513 callback->cancelLoopCallback();
514 callback->context_ = RequestContext::saveContext();
515 if (runOnceCallbacks_ != nullptr && thisIteration) {
516 runOnceCallbacks_->push_back(*callback);
518 loopCallbacks_.push_back(*callback);
522 void EventBase::runInLoop(Func cob, bool thisIteration) {
523 DCHECK(isInEventBaseThread());
524 auto wrapper = new FunctionLoopCallback(std::move(cob));
525 wrapper->context_ = RequestContext::saveContext();
526 if (runOnceCallbacks_ != nullptr && thisIteration) {
527 runOnceCallbacks_->push_back(*wrapper);
529 loopCallbacks_.push_back(*wrapper);
533 void EventBase::runAfterDrain(Func cob) {
534 auto callback = new FunctionLoopCallback(std::move(cob));
535 std::lock_guard<std::mutex> lg(runAfterDrainCallbacksMutex_);
536 callback->cancelLoopCallback();
537 runAfterDrainCallbacks_.push_back(*callback);
540 void EventBase::runOnDestruction(LoopCallback* callback) {
541 std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
542 callback->cancelLoopCallback();
543 onDestructionCallbacks_.push_back(*callback);
546 void EventBase::runBeforeLoop(LoopCallback* callback) {
547 DCHECK(isInEventBaseThread());
548 callback->cancelLoopCallback();
549 runBeforeLoopCallbacks_.push_back(*callback);
552 bool EventBase::runInEventBaseThread(Func fn) {
554 // It will be received by the FunctionRunner in the EventBase's thread.
556 // We try not to schedule nullptr callbacks
558 LOG(ERROR) << "EventBase " << this
559 << ": Scheduling nullptr callbacks is not allowed";
563 // Short-circuit if we are already in our event base
564 if (inRunningEventBaseThread()) {
565 runInLoop(std::move(fn));
571 queue_->putMessage(std::move(fn));
572 } catch (const std::exception& ex) {
573 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
574 << "for EventBase thread: " << ex.what();
581 bool EventBase::runInEventBaseThreadAndWait(Func fn) {
582 if (inRunningEventBaseThread()) {
583 LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
590 std::condition_variable cv;
591 runInEventBaseThread([&] {
593 std::unique_lock<std::mutex> l(m);
596 // We cannot release the lock before notify_one, because a spurious
597 // wakeup in the waiting thread may lead to cv and m going out of scope
602 std::unique_lock<std::mutex> l(m);
603 cv.wait(l, [&] { return ready; });
608 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(Func fn) {
609 if (isInEventBaseThread()) {
613 return runInEventBaseThreadAndWait(std::move(fn));
617 void EventBase::runAfterDelay(
619 uint32_t milliseconds,
620 TimeoutManager::InternalEnum in) {
621 if (!tryRunAfterDelay(std::move(cob), milliseconds, in)) {
622 folly::throwSystemError(
623 "error in EventBase::runAfterDelay(), failed to schedule timeout");
627 bool EventBase::tryRunAfterDelay(
629 uint32_t milliseconds,
630 TimeoutManager::InternalEnum in) {
631 CobTimeout* timeout = new CobTimeout(this, std::move(cob), in);
632 if (!timeout->scheduleTimeout(milliseconds)) {
636 pendingCobTimeouts_.push_back(*timeout);
640 bool EventBase::runLoopCallbacks(bool setContext) {
641 if (!loopCallbacks_.empty()) {
643 // Swap the loopCallbacks_ list with a temporary list on our stack.
644 // This way we will only run callbacks scheduled at the time
645 // runLoopCallbacks() was invoked.
647 // If any of these callbacks in turn call runInLoop() to schedule more
648 // callbacks, those new callbacks won't be run until the next iteration
649 // around the event loop. This prevents runInLoop() callbacks from being
650 // able to start file descriptor and timeout based events.
651 LoopCallbackList currentCallbacks;
652 currentCallbacks.swap(loopCallbacks_);
653 runOnceCallbacks_ = ¤tCallbacks;
655 while (!currentCallbacks.empty()) {
656 LoopCallback* callback = ¤tCallbacks.front();
657 currentCallbacks.pop_front();
659 RequestContext::setContext(callback->context_);
661 callback->runLoopCallback();
664 runOnceCallbacks_ = nullptr;
670 void EventBase::initNotificationQueue() {
671 // Infinite size queue
672 queue_.reset(new NotificationQueue<Func>());
674 // We allocate fnRunner_ separately, rather than declaring it directly
675 // as a member of EventBase solely so that we don't need to include
676 // NotificationQueue.h from EventBase.h
677 fnRunner_.reset(new FunctionRunner());
679 // Mark this as an internal event, so event_base_loop() will return if
680 // there are no other events besides this one installed.
682 // Most callers don't care about the internal notification queue used by
683 // EventBase. The queue is always installed, so if we did count the queue as
684 // an active event, loop() would never exit with no more events to process.
685 // Users can use loopForever() if they do care about the notification queue.
686 // (This is useful for EventBase threads that do nothing but process
687 // runInEventBaseThread() notifications.)
688 fnRunner_->startConsumingInternal(this, queue_.get());
691 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
692 expCoeff_ = -1.0/timeInterval;
693 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
696 void EventBase::SmoothLoopTime::reset(double value) {
700 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
702 * Position at which the busy sample is considered to be taken.
703 * (Allows to quickly skew our average without editing much code)
705 enum BusySamplePosition {
706 RIGHT = 0, // busy sample placed at the end of the iteration
707 CENTER = 1, // busy sample placed at the middle point of the iteration
708 LEFT = 2, // busy sample placed at the beginning of the iteration
711 // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
712 // and D676020 for more info on this calculation.
713 VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
714 " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
715 " busy " << busy << " " << __PRETTY_FUNCTION__;
716 idle += oldBusyLeftover_ + busy;
717 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
718 idle -= oldBusyLeftover_;
720 double coeff = exp(idle * expCoeff_);
722 value_ += (1.0 - coeff) * busy;
725 bool EventBase::nothingHandledYet() const noexcept {
726 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
727 return (nextLoopCnt_ != latestLoopCnt_);
730 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
731 InternalEnum internal) {
733 struct event* ev = obj->getEvent();
734 assert(ev->ev_base == nullptr);
736 event_base_set(getLibeventBase(), ev);
737 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
738 // Set the EVLIST_INTERNAL flag
739 event_ref_flags(ev) |= EVLIST_INTERNAL;
743 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
745 struct event* ev = obj->getEvent();
746 ev->ev_base = nullptr;
749 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
750 TimeoutManager::timeout_type timeout) {
751 assert(isInEventBaseThread());
752 // Set up the timeval and add the event
754 tv.tv_sec = timeout.count() / 1000LL;
755 tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
757 struct event* ev = obj->getEvent();
758 if (event_add(ev, &tv) < 0) {
759 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
766 void EventBase::cancelTimeout(AsyncTimeout* obj) {
767 assert(isInEventBaseThread());
768 struct event* ev = obj->getEvent();
769 if (EventUtil::isEventRegistered(ev)) {
774 void EventBase::setName(const std::string& name) {
775 assert(isInEventBaseThread());
779 setThreadName(loopThread_.load(std::memory_order_relaxed),
784 const std::string& EventBase::getName() {
785 assert(isInEventBaseThread());
789 const char* EventBase::getLibeventVersion() { return event_get_version(); }
790 const char* EventBase::getLibeventMethod() { return event_get_method(); }