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.
132 EventBase::EventBase()
133 : runOnceCallbacks_(nullptr)
136 , evb_(static_cast<event_base*>(event_init()))
140 , avgLoopTime_(2000000)
141 , maxLatencyLoopTime_(avgLoopTime_)
142 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
143 , latestLoopCnt_(nextLoopCnt_)
146 , observerSampleCount_(0) {
147 VLOG(5) << "EventBase(): Created.";
148 initNotificationQueue();
149 RequestContext::getStaticContext();
152 // takes ownership of the event_base
153 EventBase::EventBase(event_base* evb)
154 : runOnceCallbacks_(nullptr)
161 , avgLoopTime_(2000000)
162 , maxLatencyLoopTime_(avgLoopTime_)
163 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
164 , latestLoopCnt_(nextLoopCnt_)
167 , observerSampleCount_(0) {
168 initNotificationQueue();
169 RequestContext::getStaticContext();
172 EventBase::~EventBase() {
173 // Delete any unfired CobTimeout objects, so that we don't leak memory
174 // (Note that we don't fire them. The caller is responsible for cleaning up
175 // its own data structures if it destroys the EventBase with unfired events
177 while (!pendingCobTimeouts_.empty()) {
178 CobTimeout* timeout = &pendingCobTimeouts_.front();
182 (void) runLoopCallbacks(false);
184 // Stop consumer before deleting NotificationQueue
185 fnRunner_->stopConsuming();
186 event_base_free(evb_);
187 VLOG(5) << "EventBase(): Destroyed.";
190 int EventBase::getNotificationQueueSize() const {
191 return queue_->size();
194 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
195 fnRunner_->setMaxReadAtOnce(maxAtOnce);
198 // Set smoothing coefficient for loop load average; input is # of milliseconds
199 // for exp(-1) decay.
200 void EventBase::setLoadAvgMsec(uint32_t ms) {
201 uint64_t us = 1000 * ms;
203 maxLatencyLoopTime_.setTimeInterval(us);
204 avgLoopTime_.setTimeInterval(us);
206 LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
210 void EventBase::resetLoadAvg(double value) {
211 avgLoopTime_.reset(value);
212 maxLatencyLoopTime_.reset(value);
215 static std::chrono::milliseconds
216 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
217 auto result = std::chrono::steady_clock::now() - *prev;
218 *prev = std::chrono::steady_clock::now();
220 return std::chrono::duration_cast<std::chrono::milliseconds>(result);
223 void EventBase::waitUntilRunning() {
224 while (!isRunning()) {
229 // enters the event_base loop -- will only exit when forced to
230 bool EventBase::loop() {
234 bool EventBase::loopOnce() {
235 return loopBody(true);
238 bool EventBase::loopBody(bool once) {
239 VLOG(5) << "EventBase(): Starting loop.";
241 bool ranLoopCallbacks;
244 loopThread_.store(pthread_self(), std::memory_order_release);
246 if (!name_.empty()) {
247 setThreadName(name_);
250 auto prev = std::chrono::steady_clock::now();
251 int64_t idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
252 std::chrono::steady_clock::now().time_since_epoch()).count();
254 // TODO: Read stop_ atomically with an acquire barrier.
258 // nobody can add loop callbacks from within this thread if
259 // we don't have to handle anything to start with...
260 nonBlocking = (loopCallbacks_.empty() ? 0 : EVLOOP_NONBLOCK);
261 res = event_base_loop(evb_, EVLOOP_ONCE | nonBlocking);
262 ranLoopCallbacks = runLoopCallbacks();
264 int64_t busy = std::chrono::duration_cast<std::chrono::microseconds>(
265 std::chrono::steady_clock::now().time_since_epoch()).count() - startWork_;
266 int64_t idle = startWork_ - idleStart;
268 avgLoopTime_.addSample(idle, busy);
269 maxLatencyLoopTime_.addSample(idle, busy);
272 if (observerSampleCount_++ == observer_->getSampleRate()) {
273 observerSampleCount_ = 0;
274 observer_->loopSample(busy, idle);
278 VLOG(11) << "EventBase " << this << " did not timeout "
279 " loop time guess: " << busy + idle <<
280 " idle time: " << idle <<
281 " busy time: " << busy <<
282 " avgLoopTime: " << avgLoopTime_.get() <<
283 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
284 " maxLatency_: " << maxLatency_ <<
285 " nothingHandledYet(): "<< nothingHandledYet();
287 // see if our average loop time has exceeded our limit
288 if ((maxLatency_ > 0) &&
289 (maxLatencyLoopTime_.get() > double(maxLatency_))) {
291 // back off temporarily -- don't keep spamming maxLatencyCob_
292 // if we're only a bit over the limit
293 maxLatencyLoopTime_.dampen(0.9);
296 // Our loop run did real work; reset the idle timer
297 idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
298 std::chrono::steady_clock::now().time_since_epoch()).count();
300 // If the event loop indicate that there were no more events, and
301 // we also didn't have any loop callbacks to run, there is nothing left to
303 if (res != 0 && !ranLoopCallbacks) {
304 // Since Notification Queue is marked 'internal' some events may not have
305 // run. Run them manually if so, and continue looping.
307 if (getNotificationQueueSize() > 0) {
308 fnRunner_->handlerReady(0);
314 VLOG(5) << "EventBase " << this << " loop time: " <<
315 getTimeDelta(&prev).count();
321 // Reset stop_ so loop() can be called again
325 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
327 } else if (res == 1) {
328 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
329 } else if (res > 1) {
330 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
334 loopThread_.store(0, std::memory_order_release);
336 VLOG(5) << "EventBase(): Done with loop.";
340 void EventBase::loopForever() {
341 // Update the notification queue event to treat it as a normal (non-internal)
342 // event. The notification queue event always remains installed, and the main
343 // loop won't exit with it installed.
344 fnRunner_->stopConsuming();
345 fnRunner_->startConsuming(this, queue_.get());
349 // Restore the notification queue internal flag
350 fnRunner_->stopConsuming();
351 fnRunner_->startConsumingInternal(this, queue_.get());
354 folly::throwSystemError("error in EventBase::loopForever()");
358 bool EventBase::bumpHandlingTime() {
359 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
360 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
361 if(nothingHandledYet()) {
362 latestLoopCnt_ = nextLoopCnt_;
364 startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
365 std::chrono::steady_clock::now().time_since_epoch()).count();
367 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
368 " (loop) startWork_ " << startWork_;
374 void EventBase::terminateLoopSoon() {
375 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
381 // Set stop to true, so the event loop will know to exit.
382 // TODO: We should really use an atomic operation here with a release
386 // Call event_base_loopbreak() so that libevent will exit the next time
388 event_base_loopbreak(evb_);
390 // If terminateLoopSoon() is called from another thread,
391 // the EventBase thread might be stuck waiting for events.
392 // In this case, it won't wake up and notice that stop_ is set until it
393 // receives another event. Send an empty frame to the notification queue
394 // so that the event loop will wake up even if there are no other events.
396 // We don't care about the return value of trySendFrame(). If it fails
397 // this likely means the EventBase already has lots of events waiting
400 queue_->putMessage(std::make_pair(nullptr, nullptr));
402 // We don't care if putMessage() fails. This likely means
403 // the EventBase already has lots of events waiting anyway.
407 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
408 DCHECK(isInEventBaseThread());
409 callback->cancelLoopCallback();
410 callback->context_ = RequestContext::saveContext();
411 if (runOnceCallbacks_ != nullptr && thisIteration) {
412 runOnceCallbacks_->push_back(*callback);
414 loopCallbacks_.push_back(*callback);
418 void EventBase::runInLoop(const Cob& cob, bool thisIteration) {
419 DCHECK(isInEventBaseThread());
420 auto wrapper = new FunctionLoopCallback<Cob>(cob);
421 wrapper->context_ = RequestContext::saveContext();
422 if (runOnceCallbacks_ != nullptr && thisIteration) {
423 runOnceCallbacks_->push_back(*wrapper);
425 loopCallbacks_.push_back(*wrapper);
429 void EventBase::runInLoop(Cob&& cob, bool thisIteration) {
430 DCHECK(isInEventBaseThread());
431 auto wrapper = new FunctionLoopCallback<Cob>(std::move(cob));
432 wrapper->context_ = RequestContext::saveContext();
433 if (runOnceCallbacks_ != nullptr && thisIteration) {
434 runOnceCallbacks_->push_back(*wrapper);
436 loopCallbacks_.push_back(*wrapper);
440 bool EventBase::runInEventBaseThread(void (*fn)(void*), void* arg) {
442 // It will be received by the FunctionRunner in the EventBase's thread.
444 // We try not to schedule nullptr callbacks
446 LOG(ERROR) << "EventBase " << this
447 << ": Scheduling nullptr callbacks is not allowed";
451 // Short-circuit if we are already in our event base
452 if (inRunningEventBaseThread()) {
453 runInLoop(new RunInLoopCallback(fn, arg));
459 queue_->putMessage(std::make_pair(fn, arg));
460 } catch (const std::exception& ex) {
461 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
462 << fn << "for EventBase thread: " << ex.what();
469 bool EventBase::runInEventBaseThread(const Cob& fn) {
470 // Short-circuit if we are already in our event base
471 if (inRunningEventBaseThread()) {
477 // Allocate a copy of the function so we can pass it to the other thread
478 // The other thread will delete this copy once the function has been run
480 fnCopy = new Cob(fn);
481 } catch (const std::bad_alloc& ex) {
482 LOG(ERROR) << "failed to allocate tr::function copy "
483 << "for runInEventBaseThread()";
487 if (!runInEventBaseThread(&EventBase::runFunctionPtr, fnCopy)) {
495 bool EventBase::runAfterDelay(const Cob& cob,
497 TimeoutManager::InternalEnum in) {
498 CobTimeout* timeout = new CobTimeout(this, cob, in);
499 if (!timeout->scheduleTimeout(milliseconds)) {
504 pendingCobTimeouts_.push_back(*timeout);
508 bool EventBase::runLoopCallbacks(bool setContext) {
509 if (!loopCallbacks_.empty()) {
511 // Swap the loopCallbacks_ list with a temporary list on our stack.
512 // This way we will only run callbacks scheduled at the time
513 // runLoopCallbacks() was invoked.
515 // If any of these callbacks in turn call runInLoop() to schedule more
516 // callbacks, those new callbacks won't be run until the next iteration
517 // around the event loop. This prevents runInLoop() callbacks from being
518 // able to start file descriptor and timeout based events.
519 LoopCallbackList currentCallbacks;
520 currentCallbacks.swap(loopCallbacks_);
521 runOnceCallbacks_ = ¤tCallbacks;
523 while (!currentCallbacks.empty()) {
524 LoopCallback* callback = ¤tCallbacks.front();
525 currentCallbacks.pop_front();
527 RequestContext::setContext(callback->context_);
529 callback->runLoopCallback();
532 runOnceCallbacks_ = nullptr;
538 void EventBase::initNotificationQueue() {
539 // Infinite size queue
540 queue_.reset(new NotificationQueue<std::pair<void (*)(void*), void*>>());
542 // We allocate fnRunner_ separately, rather than declaring it directly
543 // as a member of EventBase solely so that we don't need to include
544 // NotificationQueue.h from EventBase.h
545 fnRunner_.reset(new FunctionRunner());
547 // Mark this as an internal event, so event_base_loop() will return if
548 // there are no other events besides this one installed.
550 // Most callers don't care about the internal notification queue used by
551 // EventBase. The queue is always installed, so if we did count the queue as
552 // an active event, loop() would never exit with no more events to process.
553 // Users can use loopForever() if they do care about the notification queue.
554 // (This is useful for EventBase threads that do nothing but process
555 // runInEventBaseThread() notifications.)
556 fnRunner_->startConsumingInternal(this, queue_.get());
559 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
560 expCoeff_ = -1.0/timeInterval;
561 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
564 void EventBase::SmoothLoopTime::reset(double value) {
568 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
570 * Position at which the busy sample is considered to be taken.
571 * (Allows to quickly skew our average without editing much code)
573 enum BusySamplePosition {
574 RIGHT = 0, // busy sample placed at the end of the iteration
575 CENTER = 1, // busy sample placed at the middle point of the iteration
576 LEFT = 2, // busy sample placed at the beginning of the iteration
579 VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
580 " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
581 " busy " << busy << " " << __PRETTY_FUNCTION__;
582 idle += oldBusyLeftover_ + busy;
583 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
584 idle -= oldBusyLeftover_;
586 double coeff = exp(idle * expCoeff_);
588 value_ += (1.0 - coeff) * busy;
591 bool EventBase::nothingHandledYet() {
592 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
593 return (nextLoopCnt_ != latestLoopCnt_);
597 void EventBase::runFunctionPtr(Cob* fn) {
598 // The function should never throw an exception, because we have no
599 // way of knowing what sort of error handling to perform.
601 // If it does throw, log a message and abort the program.
604 } catch (const std::exception &ex) {
605 LOG(ERROR) << "runInEventBaseThread() std::function threw a "
606 << typeid(ex).name() << " exception: " << ex.what();
609 LOG(ERROR) << "runInEventBaseThread() std::function threw an exception";
613 // The function object was allocated by runInEventBaseThread().
614 // Delete it once it has been run.
618 EventBase::RunInLoopCallback::RunInLoopCallback(void (*fn)(void*), void* arg)
622 void EventBase::RunInLoopCallback::runLoopCallback() noexcept {
627 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
628 InternalEnum internal) {
630 struct event* ev = obj->getEvent();
631 assert(ev->ev_base == nullptr);
633 event_base_set(getLibeventBase(), ev);
634 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
635 // Set the EVLIST_INTERNAL flag
636 ev->ev_flags |= EVLIST_INTERNAL;
640 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
642 struct event* ev = obj->getEvent();
643 ev->ev_base = nullptr;
646 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
647 std::chrono::milliseconds timeout) {
648 assert(isInEventBaseThread());
649 // Set up the timeval and add the event
651 tv.tv_sec = timeout.count() / 1000LL;
652 tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
654 struct event* ev = obj->getEvent();
655 if (event_add(ev, &tv) < 0) {
656 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
663 void EventBase::cancelTimeout(AsyncTimeout* obj) {
664 assert(isInEventBaseThread());
665 struct event* ev = obj->getEvent();
666 if (EventUtil::isEventRegistered(ev)) {
671 void EventBase::setName(const std::string& name) {
672 assert(isInEventBaseThread());
676 setThreadName(loopThread_.load(std::memory_order_relaxed),
681 const std::string& EventBase::getName() {
682 assert(isInEventBaseThread());