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.
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 <boost/static_assert.hpp>
27 #include <condition_variable>
36 using folly::EventBase;
38 template <typename Callback>
39 class FunctionLoopCallback : public EventBase::LoopCallback {
41 explicit FunctionLoopCallback(Cob&& function)
42 : function_(std::move(function)) {}
44 explicit FunctionLoopCallback(const Cob& function)
45 : function_(function) {}
47 virtual void runLoopCallback() noexcept {
63 * EventBase::FunctionRunner
66 class EventBase::FunctionRunner
67 : public NotificationQueue<std::pair<void (*)(void*), void*>>::Consumer {
69 void messageAvailable(std::pair<void (*)(void*), void*>&& msg) {
71 // In libevent2, internal events do not break the loop.
72 // Most users would expect loop(), followed by runInEventBaseThread(),
73 // to break the loop and check if it should exit or not.
74 // To have similar bejaviour to libevent1.4, tell the loop to break here.
75 // Note that loop() may still continue to loop, but it will also check the
76 // stop_ flag as well as runInLoop callbacks, etc.
77 event_base_loopbreak(getEventBase()->evb_);
79 if (msg.first == nullptr && msg.second == nullptr) {
80 // terminateLoopSoon() sends a null message just to
81 // wake up the loop. We can ignore these messages.
85 // If function is nullptr, just log and move on
87 LOG(ERROR) << "nullptr callback registered to be run in "
88 << "event base thread";
92 // The function should never throw an exception, because we have no
93 // way of knowing what sort of error handling to perform.
95 // If it does throw, log a message and abort the program.
97 msg.first(msg.second);
98 } catch (const std::exception& ex) {
99 LOG(ERROR) << "runInEventBaseThread() function threw a "
100 << typeid(ex).name() << " exception: " << ex.what();
103 LOG(ERROR) << "runInEventBaseThread() function threw an exception";
110 * EventBase::CobTimeout methods
113 void EventBase::CobTimeout::timeoutExpired() noexcept {
114 // For now, we just swallow any exceptions that the callback threw.
117 } catch (const std::exception& ex) {
118 LOG(ERROR) << "EventBase::runAfterDelay() callback threw "
119 << typeid(ex).name() << " exception: " << ex.what();
121 LOG(ERROR) << "EventBase::runAfterDelay() callback threw non-exception "
125 // The CobTimeout object was allocated on the heap by runAfterDelay(),
126 // so delete it now that the it has fired.
131 // The interface used to libevent is not thread-safe. Calls to
132 // event_init() and event_base_free() directly modify an internal
133 // global 'current_base', so a mutex is required to protect this.
135 // event_init() should only ever be called once. Subsequent calls
136 // should be made to event_base_new(). We can recognise that
137 // event_init() has already been called by simply inspecting current_base.
138 static std::mutex libevent_mutex_;
144 EventBase::EventBase()
145 : runOnceCallbacks_(nullptr)
151 , avgLoopTime_(2000000)
152 , maxLatencyLoopTime_(avgLoopTime_)
153 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
154 , latestLoopCnt_(nextLoopCnt_)
157 , observerSampleCount_(0) {
159 std::lock_guard<std::mutex> lock(libevent_mutex_);
161 // The value 'current_base' (libevent 1) or
162 // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
163 // allowing examination of its value without an explicit reference here.
164 // If ev.ev_base is NULL, then event_init() must be called, otherwise
165 // call event_base_new().
167 event_set(&ev, 0, 0, nullptr, nullptr);
168 evb_ = (ev.ev_base) ? event_base_new() : event_init();
170 if (UNLIKELY(evb_ == nullptr)) {
171 LOG(ERROR) << "EventBase(): Failed to init event base.";
172 folly::throwSystemError("error in EventBase::EventBase()");
174 VLOG(5) << "EventBase(): Created.";
175 initNotificationQueue();
176 RequestContext::getStaticContext();
179 // takes ownership of the event_base
180 EventBase::EventBase(event_base* evb)
181 : runOnceCallbacks_(nullptr)
188 , avgLoopTime_(2000000)
189 , maxLatencyLoopTime_(avgLoopTime_)
190 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
191 , latestLoopCnt_(nextLoopCnt_)
194 , observerSampleCount_(0) {
195 if (UNLIKELY(evb_ == nullptr)) {
196 LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
197 throw std::invalid_argument("EventBase(): event base cannot be nullptr");
199 initNotificationQueue();
200 RequestContext::getStaticContext();
203 EventBase::~EventBase() {
204 // Call all destruction callbacks, before we start cleaning up our state.
205 while (!onDestructionCallbacks_.empty()) {
206 LoopCallback* callback = &onDestructionCallbacks_.front();
207 onDestructionCallbacks_.pop_front();
208 callback->runLoopCallback();
211 // Delete any unfired callback objects, so that we don't leak memory
212 // (Note that we don't fire them. The caller is responsible for cleaning up
213 // its own data structures if it destroys the EventBase with unfired events
215 while (!pendingCobTimeouts_.empty()) {
216 CobTimeout* timeout = &pendingCobTimeouts_.front();
220 while (!runBeforeLoopCallbacks_.empty()) {
221 delete &runBeforeLoopCallbacks_.front();
224 (void) runLoopCallbacks(false);
226 if (!fnRunner_->consumeUntilDrained()) {
227 LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
230 // Stop consumer before deleting NotificationQueue
231 fnRunner_->stopConsuming();
233 std::lock_guard<std::mutex> lock(libevent_mutex_);
234 event_base_free(evb_);
236 VLOG(5) << "EventBase(): Destroyed.";
239 int EventBase::getNotificationQueueSize() const {
240 return queue_->size();
243 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
244 fnRunner_->setMaxReadAtOnce(maxAtOnce);
247 // Set smoothing coefficient for loop load average; input is # of milliseconds
248 // for exp(-1) decay.
249 void EventBase::setLoadAvgMsec(uint32_t ms) {
250 uint64_t us = 1000 * ms;
252 maxLatencyLoopTime_.setTimeInterval(us);
253 avgLoopTime_.setTimeInterval(us);
255 LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
259 void EventBase::resetLoadAvg(double value) {
260 avgLoopTime_.reset(value);
261 maxLatencyLoopTime_.reset(value);
264 static std::chrono::milliseconds
265 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
266 auto result = std::chrono::steady_clock::now() - *prev;
267 *prev = std::chrono::steady_clock::now();
269 return std::chrono::duration_cast<std::chrono::milliseconds>(result);
272 void EventBase::waitUntilRunning() {
273 while (!isRunning()) {
278 // enters the event_base loop -- will only exit when forced to
279 bool EventBase::loop() {
283 bool EventBase::loopOnce(int flags) {
284 return loopBody(flags | EVLOOP_ONCE);
287 bool EventBase::loopBody(int flags) {
288 VLOG(5) << "EventBase(): Starting loop.";
290 bool ranLoopCallbacks;
291 bool blocking = !(flags & EVLOOP_NONBLOCK);
292 bool once = (flags & EVLOOP_ONCE);
294 loopThread_.store(pthread_self(), std::memory_order_release);
296 if (!name_.empty()) {
297 setThreadName(name_);
300 auto prev = std::chrono::steady_clock::now();
301 int64_t idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
302 std::chrono::steady_clock::now().time_since_epoch()).count();
304 // TODO: Read stop_ atomically with an acquire barrier.
308 // Run the before loop callbacks
309 LoopCallbackList callbacks;
310 callbacks.swap(runBeforeLoopCallbacks_);
312 while(!callbacks.empty()) {
313 auto* item = &callbacks.front();
314 callbacks.pop_front();
315 item->runLoopCallback();
318 // nobody can add loop callbacks from within this thread if
319 // we don't have to handle anything to start with...
320 if (blocking && loopCallbacks_.empty()) {
321 res = event_base_loop(evb_, EVLOOP_ONCE);
323 res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
326 ranLoopCallbacks = runLoopCallbacks();
328 int64_t busy = std::chrono::duration_cast<std::chrono::microseconds>(
329 std::chrono::steady_clock::now().time_since_epoch()).count() - startWork_;
330 int64_t idle = startWork_ - idleStart;
332 avgLoopTime_.addSample(idle, busy);
333 maxLatencyLoopTime_.addSample(idle, busy);
336 if (observerSampleCount_++ == observer_->getSampleRate()) {
337 observerSampleCount_ = 0;
338 observer_->loopSample(busy, idle);
342 VLOG(11) << "EventBase " << this << " did not timeout "
343 " loop time guess: " << busy + idle <<
344 " idle time: " << idle <<
345 " busy time: " << busy <<
346 " avgLoopTime: " << avgLoopTime_.get() <<
347 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
348 " maxLatency_: " << maxLatency_ <<
349 " nothingHandledYet(): "<< nothingHandledYet();
351 // see if our average loop time has exceeded our limit
352 if ((maxLatency_ > 0) &&
353 (maxLatencyLoopTime_.get() > double(maxLatency_))) {
355 // back off temporarily -- don't keep spamming maxLatencyCob_
356 // if we're only a bit over the limit
357 maxLatencyLoopTime_.dampen(0.9);
360 // Our loop run did real work; reset the idle timer
361 idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
362 std::chrono::steady_clock::now().time_since_epoch()).count();
364 // If the event loop indicate that there were no more events, and
365 // we also didn't have any loop callbacks to run, there is nothing left to
367 if (res != 0 && !ranLoopCallbacks) {
368 // Since Notification Queue is marked 'internal' some events may not have
369 // run. Run them manually if so, and continue looping.
371 if (getNotificationQueueSize() > 0) {
372 fnRunner_->handlerReady(0);
378 VLOG(5) << "EventBase " << this << " loop time: " <<
379 getTimeDelta(&prev).count();
385 // Reset stop_ so loop() can be called again
389 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
391 } else if (res == 1) {
392 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
393 } else if (res > 1) {
394 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
398 loopThread_.store(0, std::memory_order_release);
400 VLOG(5) << "EventBase(): Done with loop.";
404 void EventBase::loopForever() {
405 // Update the notification queue event to treat it as a normal (non-internal)
406 // event. The notification queue event always remains installed, and the main
407 // loop won't exit with it installed.
408 fnRunner_->stopConsuming();
409 fnRunner_->startConsuming(this, queue_.get());
413 // Restore the notification queue internal flag
414 fnRunner_->stopConsuming();
415 fnRunner_->startConsumingInternal(this, queue_.get());
418 folly::throwSystemError("error in EventBase::loopForever()");
422 bool EventBase::bumpHandlingTime() {
423 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
424 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
425 if(nothingHandledYet()) {
426 latestLoopCnt_ = nextLoopCnt_;
428 startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
429 std::chrono::steady_clock::now().time_since_epoch()).count();
431 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
432 " (loop) startWork_ " << startWork_;
438 void EventBase::terminateLoopSoon() {
439 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
441 // Set stop to true, so the event loop will know to exit.
442 // TODO: We should really use an atomic operation here with a release
446 // Call event_base_loopbreak() so that libevent will exit the next time
448 event_base_loopbreak(evb_);
450 // If terminateLoopSoon() is called from another thread,
451 // the EventBase thread might be stuck waiting for events.
452 // In this case, it won't wake up and notice that stop_ is set until it
453 // receives another event. Send an empty frame to the notification queue
454 // so that the event loop will wake up even if there are no other events.
456 // We don't care about the return value of trySendFrame(). If it fails
457 // this likely means the EventBase already has lots of events waiting
460 queue_->putMessage(std::make_pair(nullptr, nullptr));
462 // We don't care if putMessage() fails. This likely means
463 // the EventBase already has lots of events waiting anyway.
467 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
468 DCHECK(isInEventBaseThread());
469 callback->cancelLoopCallback();
470 callback->context_ = RequestContext::saveContext();
471 if (runOnceCallbacks_ != nullptr && thisIteration) {
472 runOnceCallbacks_->push_back(*callback);
474 loopCallbacks_.push_back(*callback);
478 void EventBase::runInLoop(const Cob& cob, bool thisIteration) {
479 DCHECK(isInEventBaseThread());
480 auto wrapper = new FunctionLoopCallback<Cob>(cob);
481 wrapper->context_ = RequestContext::saveContext();
482 if (runOnceCallbacks_ != nullptr && thisIteration) {
483 runOnceCallbacks_->push_back(*wrapper);
485 loopCallbacks_.push_back(*wrapper);
489 void EventBase::runInLoop(Cob&& cob, bool thisIteration) {
490 DCHECK(isInEventBaseThread());
491 auto wrapper = new FunctionLoopCallback<Cob>(std::move(cob));
492 wrapper->context_ = RequestContext::saveContext();
493 if (runOnceCallbacks_ != nullptr && thisIteration) {
494 runOnceCallbacks_->push_back(*wrapper);
496 loopCallbacks_.push_back(*wrapper);
500 void EventBase::runOnDestruction(LoopCallback* callback) {
501 DCHECK(isInEventBaseThread());
502 callback->cancelLoopCallback();
503 onDestructionCallbacks_.push_back(*callback);
506 void EventBase::runBeforeLoop(LoopCallback* callback) {
507 DCHECK(isInEventBaseThread());
508 callback->cancelLoopCallback();
509 runBeforeLoopCallbacks_.push_back(*callback);
512 bool EventBase::runInEventBaseThread(void (*fn)(void*), void* arg) {
514 // It will be received by the FunctionRunner in the EventBase's thread.
516 // We try not to schedule nullptr callbacks
518 LOG(ERROR) << "EventBase " << this
519 << ": Scheduling nullptr callbacks is not allowed";
523 // Short-circuit if we are already in our event base
524 if (inRunningEventBaseThread()) {
525 runInLoop(new RunInLoopCallback(fn, arg));
531 queue_->putMessage(std::make_pair(fn, arg));
532 } catch (const std::exception& ex) {
533 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
534 << fn << "for EventBase thread: " << ex.what();
541 bool EventBase::runInEventBaseThread(const Cob& fn) {
542 // Short-circuit if we are already in our event base
543 if (inRunningEventBaseThread()) {
549 // Allocate a copy of the function so we can pass it to the other thread
550 // The other thread will delete this copy once the function has been run
552 fnCopy = new Cob(fn);
553 } catch (const std::bad_alloc& ex) {
554 LOG(ERROR) << "failed to allocate tr::function copy "
555 << "for runInEventBaseThread()";
559 if (!runInEventBaseThread(&EventBase::runFunctionPtr, fnCopy)) {
567 bool EventBase::runInEventBaseThreadAndWait(void (*fn)(void*), void* arg) {
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);
586 std::unique_lock<std::mutex> l(m);
587 cv.wait(l, [&] { return ready; });
592 bool EventBase::runInEventBaseThreadAndWait(const Cob& fn) {
593 if (inRunningEventBaseThread()) {
594 LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
601 std::condition_variable cv;
602 runInEventBaseThread([&] {
604 std::unique_lock<std::mutex> l(m);
611 std::unique_lock<std::mutex> l(m);
612 cv.wait(l, [&] { return ready; });
617 bool EventBase::runAfterDelay(const Cob& cob,
619 TimeoutManager::InternalEnum in) {
620 CobTimeout* timeout = new CobTimeout(this, cob, in);
621 if (!timeout->scheduleTimeout(milliseconds)) {
626 pendingCobTimeouts_.push_back(*timeout);
630 bool EventBase::runLoopCallbacks(bool setContext) {
631 if (!loopCallbacks_.empty()) {
633 // Swap the loopCallbacks_ list with a temporary list on our stack.
634 // This way we will only run callbacks scheduled at the time
635 // runLoopCallbacks() was invoked.
637 // If any of these callbacks in turn call runInLoop() to schedule more
638 // callbacks, those new callbacks won't be run until the next iteration
639 // around the event loop. This prevents runInLoop() callbacks from being
640 // able to start file descriptor and timeout based events.
641 LoopCallbackList currentCallbacks;
642 currentCallbacks.swap(loopCallbacks_);
643 runOnceCallbacks_ = ¤tCallbacks;
645 while (!currentCallbacks.empty()) {
646 LoopCallback* callback = ¤tCallbacks.front();
647 currentCallbacks.pop_front();
649 RequestContext::setContext(callback->context_);
651 callback->runLoopCallback();
654 runOnceCallbacks_ = nullptr;
660 void EventBase::initNotificationQueue() {
661 // Infinite size queue
662 queue_.reset(new NotificationQueue<std::pair<void (*)(void*), void*>>());
664 // We allocate fnRunner_ separately, rather than declaring it directly
665 // as a member of EventBase solely so that we don't need to include
666 // NotificationQueue.h from EventBase.h
667 fnRunner_.reset(new FunctionRunner());
669 // Mark this as an internal event, so event_base_loop() will return if
670 // there are no other events besides this one installed.
672 // Most callers don't care about the internal notification queue used by
673 // EventBase. The queue is always installed, so if we did count the queue as
674 // an active event, loop() would never exit with no more events to process.
675 // Users can use loopForever() if they do care about the notification queue.
676 // (This is useful for EventBase threads that do nothing but process
677 // runInEventBaseThread() notifications.)
678 fnRunner_->startConsumingInternal(this, queue_.get());
681 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
682 expCoeff_ = -1.0/timeInterval;
683 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
686 void EventBase::SmoothLoopTime::reset(double value) {
690 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
692 * Position at which the busy sample is considered to be taken.
693 * (Allows to quickly skew our average without editing much code)
695 enum BusySamplePosition {
696 RIGHT = 0, // busy sample placed at the end of the iteration
697 CENTER = 1, // busy sample placed at the middle point of the iteration
698 LEFT = 2, // busy sample placed at the beginning of the iteration
701 // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
702 // and D676020 for more info on this calculation.
703 VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
704 " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
705 " busy " << busy << " " << __PRETTY_FUNCTION__;
706 idle += oldBusyLeftover_ + busy;
707 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
708 idle -= oldBusyLeftover_;
710 double coeff = exp(idle * expCoeff_);
712 value_ += (1.0 - coeff) * busy;
715 bool EventBase::nothingHandledYet() {
716 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
717 return (nextLoopCnt_ != latestLoopCnt_);
721 void EventBase::runFunctionPtr(Cob* fn) {
722 // The function should never throw an exception, because we have no
723 // way of knowing what sort of error handling to perform.
725 // If it does throw, log a message and abort the program.
728 } catch (const std::exception &ex) {
729 LOG(ERROR) << "runInEventBaseThread() std::function threw a "
730 << typeid(ex).name() << " exception: " << ex.what();
733 LOG(ERROR) << "runInEventBaseThread() std::function threw an exception";
737 // The function object was allocated by runInEventBaseThread().
738 // Delete it once it has been run.
742 EventBase::RunInLoopCallback::RunInLoopCallback(void (*fn)(void*), void* arg)
746 void EventBase::RunInLoopCallback::runLoopCallback() noexcept {
751 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
752 InternalEnum internal) {
754 struct event* ev = obj->getEvent();
755 assert(ev->ev_base == nullptr);
757 event_base_set(getLibeventBase(), ev);
758 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
759 // Set the EVLIST_INTERNAL flag
760 ev->ev_flags |= EVLIST_INTERNAL;
764 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
766 struct event* ev = obj->getEvent();
767 ev->ev_base = nullptr;
770 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
771 std::chrono::milliseconds timeout) {
772 assert(isInEventBaseThread());
773 // Set up the timeval and add the event
775 tv.tv_sec = timeout.count() / 1000LL;
776 tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
778 struct event* ev = obj->getEvent();
779 if (event_add(ev, &tv) < 0) {
780 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
787 void EventBase::cancelTimeout(AsyncTimeout* obj) {
788 assert(isInEventBaseThread());
789 struct event* ev = obj->getEvent();
790 if (EventUtil::isEventRegistered(ev)) {
795 void EventBase::setName(const std::string& name) {
796 assert(isInEventBaseThread());
800 setThreadName(loopThread_.load(std::memory_order_relaxed),
805 const std::string& EventBase::getName() {
806 assert(isInEventBaseThread());
810 const char* EventBase::getLibeventVersion() { return event_get_version(); }
811 const char* EventBase::getLibeventMethod() { return event_get_method(); }