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)) {
324 // Run the before loop callbacks
325 LoopCallbackList callbacks;
326 callbacks.swap(runBeforeLoopCallbacks_);
328 while(!callbacks.empty()) {
329 auto* item = &callbacks.front();
330 callbacks.pop_front();
331 item->runLoopCallback();
334 // nobody can add loop callbacks from within this thread if
335 // we don't have to handle anything to start with...
336 if (blocking && loopCallbacks_.empty()) {
337 res = event_base_loop(evb_, EVLOOP_ONCE);
339 res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
342 ranLoopCallbacks = runLoopCallbacks();
344 if (enableTimeMeasurement_) {
345 busy = std::chrono::duration_cast<std::chrono::microseconds>(
346 std::chrono::steady_clock::now().time_since_epoch()).count() -
348 idle = startWork_ - idleStart;
350 avgLoopTime_.addSample(idle, busy);
351 maxLatencyLoopTime_.addSample(idle, busy);
354 if (observerSampleCount_++ == observer_->getSampleRate()) {
355 observerSampleCount_ = 0;
356 observer_->loopSample(busy, idle);
360 VLOG(11) << "EventBase " << this << " did not timeout "
361 " loop time guess: " << busy + idle <<
362 " idle time: " << idle <<
363 " busy time: " << busy <<
364 " avgLoopTime: " << avgLoopTime_.get() <<
365 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
366 " maxLatency_: " << maxLatency_ <<
367 " notificationQueueSize: " << getNotificationQueueSize() <<
368 " nothingHandledYet(): "<< nothingHandledYet();
370 // see if our average loop time has exceeded our limit
371 if ((maxLatency_ > 0) &&
372 (maxLatencyLoopTime_.get() > double(maxLatency_))) {
374 // back off temporarily -- don't keep spamming maxLatencyCob_
375 // if we're only a bit over the limit
376 maxLatencyLoopTime_.dampen(0.9);
379 // Our loop run did real work; reset the idle timer
380 idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
381 std::chrono::steady_clock::now().time_since_epoch()).count();
383 VLOG(11) << "EventBase " << this << " did not timeout";
386 // If the event loop indicate that there were no more events, and
387 // we also didn't have any loop callbacks to run, there is nothing left to
389 if (res != 0 && !ranLoopCallbacks) {
390 // Since Notification Queue is marked 'internal' some events may not have
391 // run. Run them manually if so, and continue looping.
393 if (getNotificationQueueSize() > 0) {
394 fnRunner_->handlerReady(0);
400 if (enableTimeMeasurement_) {
401 VLOG(5) << "EventBase " << this << " loop time: " <<
402 getTimeDelta(&prev).count();
409 // Reset stop_ so loop() can be called again
413 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
415 } else if (res == 1) {
416 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
417 } else if (res > 1) {
418 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
422 loopThread_.store({}, std::memory_order_release);
424 VLOG(5) << "EventBase(): Done with loop.";
428 void EventBase::loopForever() {
429 // Update the notification queue event to treat it as a normal (non-internal)
430 // event. The notification queue event always remains installed, and the main
431 // loop won't exit with it installed.
432 fnRunner_->stopConsuming();
433 fnRunner_->startConsuming(this, queue_.get());
437 // Restore the notification queue internal flag
438 fnRunner_->stopConsuming();
439 fnRunner_->startConsumingInternal(this, queue_.get());
442 folly::throwSystemError("error in EventBase::loopForever()");
446 void EventBase::bumpHandlingTime() {
447 if (!enableTimeMeasurement_) {
451 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
452 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
453 if (nothingHandledYet()) {
454 latestLoopCnt_ = nextLoopCnt_;
456 startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
457 std::chrono::steady_clock::now().time_since_epoch())
460 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
461 << " (loop) startWork_ " << startWork_;
465 void EventBase::terminateLoopSoon() {
466 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
468 // Set stop to true, so the event loop will know to exit.
469 // TODO: We should really use an atomic operation here with a release
473 // Call event_base_loopbreak() so that libevent will exit the next time
475 event_base_loopbreak(evb_);
477 // If terminateLoopSoon() is called from another thread,
478 // the EventBase thread might be stuck waiting for events.
479 // In this case, it won't wake up and notice that stop_ is set until it
480 // receives another event. Send an empty frame to the notification queue
481 // so that the event loop will wake up even if there are no other events.
483 // We don't care about the return value of trySendFrame(). If it fails
484 // this likely means the EventBase already has lots of events waiting
487 queue_->putMessage(nullptr);
489 // We don't care if putMessage() fails. This likely means
490 // the EventBase already has lots of events waiting anyway.
494 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
495 DCHECK(isInEventBaseThread());
496 callback->cancelLoopCallback();
497 callback->context_ = RequestContext::saveContext();
498 if (runOnceCallbacks_ != nullptr && thisIteration) {
499 runOnceCallbacks_->push_back(*callback);
501 loopCallbacks_.push_back(*callback);
505 void EventBase::runInLoop(Func cob, bool thisIteration) {
506 DCHECK(isInEventBaseThread());
507 auto wrapper = new FunctionLoopCallback(std::move(cob));
508 wrapper->context_ = RequestContext::saveContext();
509 if (runOnceCallbacks_ != nullptr && thisIteration) {
510 runOnceCallbacks_->push_back(*wrapper);
512 loopCallbacks_.push_back(*wrapper);
516 void EventBase::runAfterDrain(Func cob) {
517 auto callback = new FunctionLoopCallback(std::move(cob));
518 std::lock_guard<std::mutex> lg(runAfterDrainCallbacksMutex_);
519 callback->cancelLoopCallback();
520 runAfterDrainCallbacks_.push_back(*callback);
523 void EventBase::runOnDestruction(LoopCallback* callback) {
524 std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
525 callback->cancelLoopCallback();
526 onDestructionCallbacks_.push_back(*callback);
529 void EventBase::runBeforeLoop(LoopCallback* callback) {
530 DCHECK(isInEventBaseThread());
531 callback->cancelLoopCallback();
532 runBeforeLoopCallbacks_.push_back(*callback);
535 bool EventBase::runInEventBaseThread(Func fn) {
537 // It will be received by the FunctionRunner in the EventBase's thread.
539 // We try not to schedule nullptr callbacks
541 LOG(ERROR) << "EventBase " << this
542 << ": Scheduling nullptr callbacks is not allowed";
546 // Short-circuit if we are already in our event base
547 if (inRunningEventBaseThread()) {
548 runInLoop(std::move(fn));
554 queue_->putMessage(std::move(fn));
555 } catch (const std::exception& ex) {
556 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
557 << "for EventBase thread: " << ex.what();
564 bool EventBase::runInEventBaseThreadAndWait(Func fn) {
565 if (inRunningEventBaseThread()) {
566 LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
573 std::condition_variable cv;
574 runInEventBaseThread([&] {
576 std::unique_lock<std::mutex> l(m);
579 // We cannot release the lock before notify_one, because a spurious
580 // wakeup in the waiting thread may lead to cv and m going out of scope
585 std::unique_lock<std::mutex> l(m);
586 cv.wait(l, [&] { return ready; });
591 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(Func fn) {
592 if (isInEventBaseThread()) {
596 return runInEventBaseThreadAndWait(std::move(fn));
600 void EventBase::runAfterDelay(
602 uint32_t milliseconds,
603 TimeoutManager::InternalEnum in) {
604 if (!tryRunAfterDelay(std::move(cob), milliseconds, in)) {
605 folly::throwSystemError(
606 "error in EventBase::runAfterDelay(), failed to schedule timeout");
610 bool EventBase::tryRunAfterDelay(
612 uint32_t milliseconds,
613 TimeoutManager::InternalEnum in) {
614 CobTimeout* timeout = new CobTimeout(this, std::move(cob), in);
615 if (!timeout->scheduleTimeout(milliseconds)) {
619 pendingCobTimeouts_.push_back(*timeout);
623 bool EventBase::runLoopCallbacks(bool setContext) {
624 if (!loopCallbacks_.empty()) {
626 // Swap the loopCallbacks_ list with a temporary list on our stack.
627 // This way we will only run callbacks scheduled at the time
628 // runLoopCallbacks() was invoked.
630 // If any of these callbacks in turn call runInLoop() to schedule more
631 // callbacks, those new callbacks won't be run until the next iteration
632 // around the event loop. This prevents runInLoop() callbacks from being
633 // able to start file descriptor and timeout based events.
634 LoopCallbackList currentCallbacks;
635 currentCallbacks.swap(loopCallbacks_);
636 runOnceCallbacks_ = ¤tCallbacks;
638 while (!currentCallbacks.empty()) {
639 LoopCallback* callback = ¤tCallbacks.front();
640 currentCallbacks.pop_front();
642 RequestContext::setContext(callback->context_);
644 callback->runLoopCallback();
647 runOnceCallbacks_ = nullptr;
653 void EventBase::initNotificationQueue() {
654 // Infinite size queue
655 queue_.reset(new NotificationQueue<Func>());
657 // We allocate fnRunner_ separately, rather than declaring it directly
658 // as a member of EventBase solely so that we don't need to include
659 // NotificationQueue.h from EventBase.h
660 fnRunner_.reset(new FunctionRunner());
662 // Mark this as an internal event, so event_base_loop() will return if
663 // there are no other events besides this one installed.
665 // Most callers don't care about the internal notification queue used by
666 // EventBase. The queue is always installed, so if we did count the queue as
667 // an active event, loop() would never exit with no more events to process.
668 // Users can use loopForever() if they do care about the notification queue.
669 // (This is useful for EventBase threads that do nothing but process
670 // runInEventBaseThread() notifications.)
671 fnRunner_->startConsumingInternal(this, queue_.get());
674 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
675 expCoeff_ = -1.0/timeInterval;
676 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
679 void EventBase::SmoothLoopTime::reset(double value) {
683 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
685 * Position at which the busy sample is considered to be taken.
686 * (Allows to quickly skew our average without editing much code)
688 enum BusySamplePosition {
689 RIGHT = 0, // busy sample placed at the end of the iteration
690 CENTER = 1, // busy sample placed at the middle point of the iteration
691 LEFT = 2, // busy sample placed at the beginning of the iteration
694 // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
695 // and D676020 for more info on this calculation.
696 VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
697 " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
698 " busy " << busy << " " << __PRETTY_FUNCTION__;
699 idle += oldBusyLeftover_ + busy;
700 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
701 idle -= oldBusyLeftover_;
703 double coeff = exp(idle * expCoeff_);
705 value_ += (1.0 - coeff) * busy;
708 bool EventBase::nothingHandledYet() const noexcept {
709 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
710 return (nextLoopCnt_ != latestLoopCnt_);
713 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
714 InternalEnum internal) {
716 struct event* ev = obj->getEvent();
717 assert(ev->ev_base == nullptr);
719 event_base_set(getLibeventBase(), ev);
720 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
721 // Set the EVLIST_INTERNAL flag
722 event_ref_flags(ev) |= EVLIST_INTERNAL;
726 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
728 struct event* ev = obj->getEvent();
729 ev->ev_base = nullptr;
732 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
733 TimeoutManager::timeout_type timeout) {
734 assert(isInEventBaseThread());
735 // Set up the timeval and add the event
737 tv.tv_sec = timeout.count() / 1000LL;
738 tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
740 struct event* ev = obj->getEvent();
741 if (event_add(ev, &tv) < 0) {
742 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
749 void EventBase::cancelTimeout(AsyncTimeout* obj) {
750 assert(isInEventBaseThread());
751 struct event* ev = obj->getEvent();
752 if (EventUtil::isEventRegistered(ev)) {
757 void EventBase::setName(const std::string& name) {
758 assert(isInEventBaseThread());
762 setThreadName(loopThread_.load(std::memory_order_relaxed),
767 const std::string& EventBase::getName() {
768 assert(isInEventBaseThread());
772 const char* EventBase::getLibeventVersion() { return event_get_version(); }
773 const char* EventBase::getLibeventMethod() { return event_get_method(); }