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>
34 using folly::EventBase;
36 template <typename Callback>
37 class FunctionLoopCallback : public EventBase::LoopCallback {
39 explicit FunctionLoopCallback(Cob&& function)
40 : function_(std::move(function)) {}
42 explicit FunctionLoopCallback(const Cob& function)
43 : function_(function) {}
45 virtual void runLoopCallback() noexcept {
61 * EventBase::FunctionRunner
64 class EventBase::FunctionRunner
65 : public NotificationQueue<std::pair<void (*)(void*), void*>>::Consumer {
67 void messageAvailable(std::pair<void (*)(void*), void*>&& msg) {
69 // In libevent2, internal events do not break the loop.
70 // Most users would expect loop(), followed by runInEventBaseThread(),
71 // to break the loop and check if it should exit or not.
72 // To have similar bejaviour to libevent1.4, tell the loop to break here.
73 // Note that loop() may still continue to loop, but it will also check the
74 // stop_ flag as well as runInLoop callbacks, etc.
75 event_base_loopbreak(getEventBase()->evb_);
77 if (msg.first == nullptr && msg.second == nullptr) {
78 // terminateLoopSoon() sends a null message just to
79 // wake up the loop. We can ignore these messages.
83 // If function is nullptr, just log and move on
85 LOG(ERROR) << "nullptr callback registered to be run in "
86 << "event base thread";
90 // The function should never throw an exception, because we have no
91 // way of knowing what sort of error handling to perform.
93 // If it does throw, log a message and abort the program.
95 msg.first(msg.second);
96 } catch (const std::exception& ex) {
97 LOG(ERROR) << "runInEventBaseThread() function threw a "
98 << typeid(ex).name() << " exception: " << ex.what();
101 LOG(ERROR) << "runInEventBaseThread() function threw an exception";
108 * EventBase::CobTimeout methods
111 void EventBase::CobTimeout::timeoutExpired() noexcept {
112 // For now, we just swallow any exceptions that the callback threw.
115 } catch (const std::exception& ex) {
116 LOG(ERROR) << "EventBase::runAfterDelay() callback threw "
117 << typeid(ex).name() << " exception: " << ex.what();
119 LOG(ERROR) << "EventBase::runAfterDelay() callback threw non-exception "
123 // The CobTimeout object was allocated on the heap by runAfterDelay(),
124 // so delete it now that the it has fired.
129 // The interface used to libevent is not thread-safe. Calls to
130 // event_init() and event_base_free() directly modify an internal
131 // global 'current_base', so a mutex is required to protect this.
133 // event_init() should only ever be called once. Subsequent calls
134 // should be made to event_base_new(). We can recognise that
135 // event_init() has already been called by simply inspecting current_base.
136 static std::mutex libevent_mutex_;
142 EventBase::EventBase()
143 : runOnceCallbacks_(nullptr)
149 , avgLoopTime_(2000000)
150 , maxLatencyLoopTime_(avgLoopTime_)
151 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
152 , latestLoopCnt_(nextLoopCnt_)
155 , observerSampleCount_(0) {
157 std::lock_guard<std::mutex> lock(libevent_mutex_);
159 // The value 'current_base' (libevent 1) or
160 // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
161 // allowing examination of its value without an explicit reference here.
162 // If ev.ev_base is NULL, then event_init() must be called, otherwise
163 // call event_base_new().
165 event_set(&ev, 0, 0, nullptr, nullptr);
166 evb_ = (ev.ev_base) ? event_base_new() : event_init();
168 if (UNLIKELY(evb_ == nullptr)) {
169 LOG(ERROR) << "EventBase(): Failed to init event base.";
170 folly::throwSystemError("error in EventBase::EventBase()");
172 VLOG(5) << "EventBase(): Created.";
173 initNotificationQueue();
174 RequestContext::getStaticContext();
177 // takes ownership of the event_base
178 EventBase::EventBase(event_base* evb)
179 : runOnceCallbacks_(nullptr)
186 , avgLoopTime_(2000000)
187 , maxLatencyLoopTime_(avgLoopTime_)
188 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
189 , latestLoopCnt_(nextLoopCnt_)
192 , observerSampleCount_(0) {
193 if (UNLIKELY(evb_ == nullptr)) {
194 LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
195 throw std::invalid_argument("EventBase(): event base cannot be nullptr");
197 initNotificationQueue();
198 RequestContext::getStaticContext();
201 EventBase::~EventBase() {
202 // Call all destruction callbacks, before we start cleaning up our state.
203 while (!onDestructionCallbacks_.empty()) {
204 LoopCallback* callback = &onDestructionCallbacks_.front();
205 onDestructionCallbacks_.pop_front();
206 callback->runLoopCallback();
209 // Delete any unfired callback objects, so that we don't leak memory
210 // (Note that we don't fire them. The caller is responsible for cleaning up
211 // its own data structures if it destroys the EventBase with unfired events
213 while (!pendingCobTimeouts_.empty()) {
214 CobTimeout* timeout = &pendingCobTimeouts_.front();
218 while (!runBeforeLoopCallbacks_.empty()) {
219 delete &runBeforeLoopCallbacks_.front();
222 (void) runLoopCallbacks(false);
224 if (!fnRunner_->consumeUntilDrained()) {
225 LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
228 // Stop consumer before deleting NotificationQueue
229 fnRunner_->stopConsuming();
231 std::lock_guard<std::mutex> lock(libevent_mutex_);
232 event_base_free(evb_);
234 VLOG(5) << "EventBase(): Destroyed.";
237 int EventBase::getNotificationQueueSize() const {
238 return queue_->size();
241 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
242 fnRunner_->setMaxReadAtOnce(maxAtOnce);
245 // Set smoothing coefficient for loop load average; input is # of milliseconds
246 // for exp(-1) decay.
247 void EventBase::setLoadAvgMsec(uint32_t ms) {
248 uint64_t us = 1000 * ms;
250 maxLatencyLoopTime_.setTimeInterval(us);
251 avgLoopTime_.setTimeInterval(us);
253 LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
257 void EventBase::resetLoadAvg(double value) {
258 avgLoopTime_.reset(value);
259 maxLatencyLoopTime_.reset(value);
262 static std::chrono::milliseconds
263 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
264 auto result = std::chrono::steady_clock::now() - *prev;
265 *prev = std::chrono::steady_clock::now();
267 return std::chrono::duration_cast<std::chrono::milliseconds>(result);
270 void EventBase::waitUntilRunning() {
271 while (!isRunning()) {
276 // enters the event_base loop -- will only exit when forced to
277 bool EventBase::loop() {
281 bool EventBase::loopOnce(int flags) {
282 return loopBody(flags | EVLOOP_ONCE);
285 bool EventBase::loopBody(int flags) {
286 VLOG(5) << "EventBase(): Starting loop.";
288 bool ranLoopCallbacks;
289 bool blocking = !(flags & EVLOOP_NONBLOCK);
290 bool once = (flags & EVLOOP_ONCE);
292 loopThread_.store(pthread_self(), std::memory_order_release);
294 if (!name_.empty()) {
295 setThreadName(name_);
298 auto prev = std::chrono::steady_clock::now();
299 int64_t idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
300 std::chrono::steady_clock::now().time_since_epoch()).count();
302 // TODO: Read stop_ atomically with an acquire barrier.
306 // Run the before loop callbacks
307 LoopCallbackList callbacks;
308 callbacks.swap(runBeforeLoopCallbacks_);
310 while(!callbacks.empty()) {
311 auto* item = &callbacks.front();
312 callbacks.pop_front();
313 item->runLoopCallback();
316 // nobody can add loop callbacks from within this thread if
317 // we don't have to handle anything to start with...
318 if (blocking && loopCallbacks_.empty()) {
319 res = event_base_loop(evb_, EVLOOP_ONCE);
321 res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
324 ranLoopCallbacks = runLoopCallbacks();
326 int64_t busy = std::chrono::duration_cast<std::chrono::microseconds>(
327 std::chrono::steady_clock::now().time_since_epoch()).count() - startWork_;
328 int64_t idle = startWork_ - idleStart;
330 avgLoopTime_.addSample(idle, busy);
331 maxLatencyLoopTime_.addSample(idle, busy);
334 if (observerSampleCount_++ == observer_->getSampleRate()) {
335 observerSampleCount_ = 0;
336 observer_->loopSample(busy, idle);
340 VLOG(11) << "EventBase " << this << " did not timeout "
341 " loop time guess: " << busy + idle <<
342 " idle time: " << idle <<
343 " busy time: " << busy <<
344 " avgLoopTime: " << avgLoopTime_.get() <<
345 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
346 " maxLatency_: " << maxLatency_ <<
347 " nothingHandledYet(): "<< nothingHandledYet();
349 // see if our average loop time has exceeded our limit
350 if ((maxLatency_ > 0) &&
351 (maxLatencyLoopTime_.get() > double(maxLatency_))) {
353 // back off temporarily -- don't keep spamming maxLatencyCob_
354 // if we're only a bit over the limit
355 maxLatencyLoopTime_.dampen(0.9);
358 // Our loop run did real work; reset the idle timer
359 idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
360 std::chrono::steady_clock::now().time_since_epoch()).count();
362 // If the event loop indicate that there were no more events, and
363 // we also didn't have any loop callbacks to run, there is nothing left to
365 if (res != 0 && !ranLoopCallbacks) {
366 // Since Notification Queue is marked 'internal' some events may not have
367 // run. Run them manually if so, and continue looping.
369 if (getNotificationQueueSize() > 0) {
370 fnRunner_->handlerReady(0);
376 VLOG(5) << "EventBase " << this << " loop time: " <<
377 getTimeDelta(&prev).count();
383 // Reset stop_ so loop() can be called again
387 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
389 } else if (res == 1) {
390 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
391 } else if (res > 1) {
392 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
396 loopThread_.store(0, std::memory_order_release);
398 VLOG(5) << "EventBase(): Done with loop.";
402 void EventBase::loopForever() {
403 // Update the notification queue event to treat it as a normal (non-internal)
404 // event. The notification queue event always remains installed, and the main
405 // loop won't exit with it installed.
406 fnRunner_->stopConsuming();
407 fnRunner_->startConsuming(this, queue_.get());
411 // Restore the notification queue internal flag
412 fnRunner_->stopConsuming();
413 fnRunner_->startConsumingInternal(this, queue_.get());
416 folly::throwSystemError("error in EventBase::loopForever()");
420 bool EventBase::bumpHandlingTime() {
421 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
422 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
423 if(nothingHandledYet()) {
424 latestLoopCnt_ = nextLoopCnt_;
426 startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
427 std::chrono::steady_clock::now().time_since_epoch()).count();
429 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
430 " (loop) startWork_ " << startWork_;
436 void EventBase::terminateLoopSoon() {
437 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
439 // Set stop to true, so the event loop will know to exit.
440 // TODO: We should really use an atomic operation here with a release
444 // Call event_base_loopbreak() so that libevent will exit the next time
446 event_base_loopbreak(evb_);
448 // If terminateLoopSoon() is called from another thread,
449 // the EventBase thread might be stuck waiting for events.
450 // In this case, it won't wake up and notice that stop_ is set until it
451 // receives another event. Send an empty frame to the notification queue
452 // so that the event loop will wake up even if there are no other events.
454 // We don't care about the return value of trySendFrame(). If it fails
455 // this likely means the EventBase already has lots of events waiting
458 queue_->putMessage(std::make_pair(nullptr, nullptr));
460 // We don't care if putMessage() fails. This likely means
461 // the EventBase already has lots of events waiting anyway.
465 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
466 DCHECK(isInEventBaseThread());
467 callback->cancelLoopCallback();
468 callback->context_ = RequestContext::saveContext();
469 if (runOnceCallbacks_ != nullptr && thisIteration) {
470 runOnceCallbacks_->push_back(*callback);
472 loopCallbacks_.push_back(*callback);
476 void EventBase::runInLoop(const Cob& cob, bool thisIteration) {
477 DCHECK(isInEventBaseThread());
478 auto wrapper = new FunctionLoopCallback<Cob>(cob);
479 wrapper->context_ = RequestContext::saveContext();
480 if (runOnceCallbacks_ != nullptr && thisIteration) {
481 runOnceCallbacks_->push_back(*wrapper);
483 loopCallbacks_.push_back(*wrapper);
487 void EventBase::runInLoop(Cob&& cob, bool thisIteration) {
488 DCHECK(isInEventBaseThread());
489 auto wrapper = new FunctionLoopCallback<Cob>(std::move(cob));
490 wrapper->context_ = RequestContext::saveContext();
491 if (runOnceCallbacks_ != nullptr && thisIteration) {
492 runOnceCallbacks_->push_back(*wrapper);
494 loopCallbacks_.push_back(*wrapper);
498 void EventBase::runOnDestruction(LoopCallback* callback) {
499 DCHECK(isInEventBaseThread());
500 callback->cancelLoopCallback();
501 onDestructionCallbacks_.push_back(*callback);
504 void EventBase::runBeforeLoop(LoopCallback* callback) {
505 DCHECK(isInEventBaseThread());
506 callback->cancelLoopCallback();
507 runBeforeLoopCallbacks_.push_back(*callback);
510 bool EventBase::runInEventBaseThread(void (*fn)(void*), void* arg) {
512 // It will be received by the FunctionRunner in the EventBase's thread.
514 // We try not to schedule nullptr callbacks
516 LOG(ERROR) << "EventBase " << this
517 << ": Scheduling nullptr callbacks is not allowed";
521 // Short-circuit if we are already in our event base
522 if (inRunningEventBaseThread()) {
523 runInLoop(new RunInLoopCallback(fn, arg));
529 queue_->putMessage(std::make_pair(fn, arg));
530 } catch (const std::exception& ex) {
531 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
532 << fn << "for EventBase thread: " << ex.what();
539 bool EventBase::runInEventBaseThread(const Cob& fn) {
540 // Short-circuit if we are already in our event base
541 if (inRunningEventBaseThread()) {
547 // Allocate a copy of the function so we can pass it to the other thread
548 // The other thread will delete this copy once the function has been run
550 fnCopy = new Cob(fn);
551 } catch (const std::bad_alloc& ex) {
552 LOG(ERROR) << "failed to allocate tr::function copy "
553 << "for runInEventBaseThread()";
557 if (!runInEventBaseThread(&EventBase::runFunctionPtr, fnCopy)) {
565 bool EventBase::runAfterDelay(const Cob& cob,
567 TimeoutManager::InternalEnum in) {
568 CobTimeout* timeout = new CobTimeout(this, cob, in);
569 if (!timeout->scheduleTimeout(milliseconds)) {
574 pendingCobTimeouts_.push_back(*timeout);
578 bool EventBase::runLoopCallbacks(bool setContext) {
579 if (!loopCallbacks_.empty()) {
581 // Swap the loopCallbacks_ list with a temporary list on our stack.
582 // This way we will only run callbacks scheduled at the time
583 // runLoopCallbacks() was invoked.
585 // If any of these callbacks in turn call runInLoop() to schedule more
586 // callbacks, those new callbacks won't be run until the next iteration
587 // around the event loop. This prevents runInLoop() callbacks from being
588 // able to start file descriptor and timeout based events.
589 LoopCallbackList currentCallbacks;
590 currentCallbacks.swap(loopCallbacks_);
591 runOnceCallbacks_ = ¤tCallbacks;
593 while (!currentCallbacks.empty()) {
594 LoopCallback* callback = ¤tCallbacks.front();
595 currentCallbacks.pop_front();
597 RequestContext::setContext(callback->context_);
599 callback->runLoopCallback();
602 runOnceCallbacks_ = nullptr;
608 void EventBase::initNotificationQueue() {
609 // Infinite size queue
610 queue_.reset(new NotificationQueue<std::pair<void (*)(void*), void*>>());
612 // We allocate fnRunner_ separately, rather than declaring it directly
613 // as a member of EventBase solely so that we don't need to include
614 // NotificationQueue.h from EventBase.h
615 fnRunner_.reset(new FunctionRunner());
617 // Mark this as an internal event, so event_base_loop() will return if
618 // there are no other events besides this one installed.
620 // Most callers don't care about the internal notification queue used by
621 // EventBase. The queue is always installed, so if we did count the queue as
622 // an active event, loop() would never exit with no more events to process.
623 // Users can use loopForever() if they do care about the notification queue.
624 // (This is useful for EventBase threads that do nothing but process
625 // runInEventBaseThread() notifications.)
626 fnRunner_->startConsumingInternal(this, queue_.get());
629 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
630 expCoeff_ = -1.0/timeInterval;
631 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
634 void EventBase::SmoothLoopTime::reset(double value) {
638 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
640 * Position at which the busy sample is considered to be taken.
641 * (Allows to quickly skew our average without editing much code)
643 enum BusySamplePosition {
644 RIGHT = 0, // busy sample placed at the end of the iteration
645 CENTER = 1, // busy sample placed at the middle point of the iteration
646 LEFT = 2, // busy sample placed at the beginning of the iteration
649 VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
650 " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
651 " busy " << busy << " " << __PRETTY_FUNCTION__;
652 idle += oldBusyLeftover_ + busy;
653 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
654 idle -= oldBusyLeftover_;
656 double coeff = exp(idle * expCoeff_);
658 value_ += (1.0 - coeff) * busy;
661 bool EventBase::nothingHandledYet() {
662 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
663 return (nextLoopCnt_ != latestLoopCnt_);
667 void EventBase::runFunctionPtr(Cob* fn) {
668 // The function should never throw an exception, because we have no
669 // way of knowing what sort of error handling to perform.
671 // If it does throw, log a message and abort the program.
674 } catch (const std::exception &ex) {
675 LOG(ERROR) << "runInEventBaseThread() std::function threw a "
676 << typeid(ex).name() << " exception: " << ex.what();
679 LOG(ERROR) << "runInEventBaseThread() std::function threw an exception";
683 // The function object was allocated by runInEventBaseThread().
684 // Delete it once it has been run.
688 EventBase::RunInLoopCallback::RunInLoopCallback(void (*fn)(void*), void* arg)
692 void EventBase::RunInLoopCallback::runLoopCallback() noexcept {
697 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
698 InternalEnum internal) {
700 struct event* ev = obj->getEvent();
701 assert(ev->ev_base == nullptr);
703 event_base_set(getLibeventBase(), ev);
704 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
705 // Set the EVLIST_INTERNAL flag
706 ev->ev_flags |= EVLIST_INTERNAL;
710 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
712 struct event* ev = obj->getEvent();
713 ev->ev_base = nullptr;
716 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
717 std::chrono::milliseconds timeout) {
718 assert(isInEventBaseThread());
719 // Set up the timeval and add the event
721 tv.tv_sec = timeout.count() / 1000LL;
722 tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
724 struct event* ev = obj->getEvent();
725 if (event_add(ev, &tv) < 0) {
726 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
733 void EventBase::cancelTimeout(AsyncTimeout* obj) {
734 assert(isInEventBaseThread());
735 struct event* ev = obj->getEvent();
736 if (EventUtil::isEventRegistered(ev)) {
741 void EventBase::setName(const std::string& name) {
742 assert(isInEventBaseThread());
746 setThreadName(loopThread_.load(std::memory_order_relaxed),
751 const std::string& EventBase::getName() {
752 assert(isInEventBaseThread());
756 const char* EventBase::getLibeventVersion() { return event_get_version(); }
757 const char* EventBase::getLibeventMethod() { return event_get_method(); }