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/io/async/NotificationQueue.h"
25 #include <boost/static_assert.hpp>
33 using folly::EventBase;
35 template <typename Callback>
36 class FunctionLoopCallback : public EventBase::LoopCallback {
38 explicit FunctionLoopCallback(Cob&& function)
39 : function_(std::move(function)) {}
41 explicit FunctionLoopCallback(const Cob& function)
42 : function_(function) {}
44 virtual void runLoopCallback() noexcept {
60 * EventBase::FunctionRunner
63 class EventBase::FunctionRunner
64 : public NotificationQueue<std::pair<void (*)(void*), void*>>::Consumer {
66 void messageAvailable(std::pair<void (*)(void*), void*>&& msg) {
68 // In libevent2, internal events do not break the loop.
69 // Most users would expect loop(), followed by runInEventBaseThread(),
70 // to break the loop and check if it should exit or not.
71 // To have similar bejaviour to libevent1.4, tell the loop to break here.
72 // Note that loop() may still continue to loop, but it will also check the
73 // stop_ flag as well as runInLoop callbacks, etc.
74 event_base_loopbreak(getEventBase()->evb_);
76 if (msg.first == nullptr && msg.second == nullptr) {
77 // terminateLoopSoon() sends a null message just to
78 // wake up the loop. We can ignore these messages.
82 // If function is nullptr, just log and move on
84 LOG(ERROR) << "nullptr callback registered to be run in "
85 << "event base thread";
89 // The function should never throw an exception, because we have no
90 // way of knowing what sort of error handling to perform.
92 // If it does throw, log a message and abort the program.
94 msg.first(msg.second);
95 } catch (const std::exception& ex) {
96 LOG(ERROR) << "runInEventBaseThread() function threw a "
97 << typeid(ex).name() << " exception: " << ex.what();
100 LOG(ERROR) << "runInEventBaseThread() function threw an exception";
107 * EventBase::CobTimeout methods
110 void EventBase::CobTimeout::timeoutExpired() noexcept {
111 // For now, we just swallow any exceptions that the callback threw.
114 } catch (const std::exception& ex) {
115 LOG(ERROR) << "EventBase::runAfterDelay() callback threw "
116 << typeid(ex).name() << " exception: " << ex.what();
118 LOG(ERROR) << "EventBase::runAfterDelay() callback threw non-exception "
122 // The CobTimeout object was allocated on the heap by runAfterDelay(),
123 // so delete it now that the it has fired.
131 EventBase::EventBase()
132 : runOnceCallbacks_(nullptr)
135 , evb_(static_cast<event_base*>(event_init()))
139 , avgLoopTime_(2000000)
140 , maxLatencyLoopTime_(avgLoopTime_)
141 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
142 , latestLoopCnt_(nextLoopCnt_)
145 , observerSampleCount_(0) {
146 VLOG(5) << "EventBase(): Created.";
147 initNotificationQueue();
148 RequestContext::getStaticContext();
151 // takes ownership of the event_base
152 EventBase::EventBase(event_base* evb)
153 : runOnceCallbacks_(nullptr)
160 , avgLoopTime_(2000000)
161 , maxLatencyLoopTime_(avgLoopTime_)
162 , nextLoopCnt_(-40) // Early wrap-around so bugs will manifest soon
163 , latestLoopCnt_(nextLoopCnt_)
166 , observerSampleCount_(0) {
167 initNotificationQueue();
168 RequestContext::getStaticContext();
171 EventBase::~EventBase() {
172 // Delete any unfired CobTimeout objects, so that we don't leak memory
173 // (Note that we don't fire them. The caller is responsible for cleaning up
174 // its own data structures if it destroys the EventBase with unfired events
176 while (!pendingCobTimeouts_.empty()) {
177 CobTimeout* timeout = &pendingCobTimeouts_.front();
181 (void) runLoopCallbacks(false);
183 // Stop consumer before deleting NotificationQueue
184 fnRunner_->stopConsuming();
185 event_base_free(evb_);
186 VLOG(5) << "EventBase(): Destroyed.";
189 int EventBase::getNotificationQueueSize() const {
190 return queue_->size();
193 // Set smoothing coefficient for loop load average; input is # of milliseconds
194 // for exp(-1) decay.
195 void EventBase::setLoadAvgMsec(uint32_t ms) {
196 uint64_t us = 1000 * ms;
198 maxLatencyLoopTime_.setTimeInterval(us);
199 avgLoopTime_.setTimeInterval(us);
201 LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
205 void EventBase::resetLoadAvg(double value) {
206 avgLoopTime_.reset(value);
207 maxLatencyLoopTime_.reset(value);
210 static std::chrono::milliseconds
211 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
212 auto result = std::chrono::steady_clock::now() - *prev;
213 *prev = std::chrono::steady_clock::now();
215 return std::chrono::duration_cast<std::chrono::milliseconds>(result);
218 void EventBase::waitUntilRunning() {
219 while (!isRunning()) {
224 // enters the event_base loop -- will only exit when forced to
225 bool EventBase::loop() {
229 bool EventBase::loopOnce() {
230 return loopBody(true);
233 bool EventBase::loopBody(bool once) {
234 VLOG(5) << "EventBase(): Starting loop.";
236 bool ranLoopCallbacks;
239 loopThread_.store(pthread_self(), std::memory_order_release);
241 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
242 if (!name_.empty()) {
243 pthread_setname_np(pthread_self(), name_.c_str());
247 auto prev = std::chrono::steady_clock::now();
248 int64_t idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
249 std::chrono::steady_clock::now().time_since_epoch()).count();
251 // TODO: Read stop_ atomically with an acquire barrier.
255 // nobody can add loop callbacks from within this thread if
256 // we don't have to handle anything to start with...
257 nonBlocking = (loopCallbacks_.empty() ? 0 : EVLOOP_NONBLOCK);
258 res = event_base_loop(evb_, EVLOOP_ONCE | nonBlocking);
259 ranLoopCallbacks = runLoopCallbacks();
261 int64_t busy = std::chrono::duration_cast<std::chrono::microseconds>(
262 std::chrono::steady_clock::now().time_since_epoch()).count() - startWork_;
263 int64_t idle = startWork_ - idleStart;
265 avgLoopTime_.addSample(idle, busy);
266 maxLatencyLoopTime_.addSample(idle, busy);
269 if (observerSampleCount_++ == observer_->getSampleRate()) {
270 observerSampleCount_ = 0;
271 observer_->loopSample(busy, idle);
275 VLOG(11) << "EventBase " << this << " did not timeout "
276 " loop time guess: " << busy + idle <<
277 " idle time: " << idle <<
278 " busy time: " << busy <<
279 " avgLoopTime: " << avgLoopTime_.get() <<
280 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
281 " maxLatency_: " << maxLatency_ <<
282 " nothingHandledYet(): "<< nothingHandledYet();
284 // see if our average loop time has exceeded our limit
285 if ((maxLatency_ > 0) &&
286 (maxLatencyLoopTime_.get() > double(maxLatency_))) {
288 // back off temporarily -- don't keep spamming maxLatencyCob_
289 // if we're only a bit over the limit
290 maxLatencyLoopTime_.dampen(0.9);
293 // Our loop run did real work; reset the idle timer
294 idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
295 std::chrono::steady_clock::now().time_since_epoch()).count();
297 // If the event loop indicate that there were no more events, and
298 // we also didn't have any loop callbacks to run, there is nothing left to
300 if (res != 0 && !ranLoopCallbacks) {
301 // Since Notification Queue is marked 'internal' some events may not have
302 // run. Run them manually if so, and continue looping.
304 if (getNotificationQueueSize() > 0) {
305 fnRunner_->handlerReady(0);
311 VLOG(5) << "EventBase " << this << " loop time: " <<
312 getTimeDelta(&prev).count();
318 // Reset stop_ so loop() can be called again
322 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
324 } else if (res == 1) {
325 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
326 } else if (res > 1) {
327 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
331 loopThread_.store(0, std::memory_order_release);
333 VLOG(5) << "EventBase(): Done with loop.";
337 void EventBase::loopForever() {
338 // Update the notification queue event to treat it as a normal (non-internal)
339 // event. The notification queue event always remains installed, and the main
340 // loop won't exit with it installed.
341 fnRunner_->stopConsuming();
342 fnRunner_->startConsuming(this, queue_.get());
346 // Restore the notification queue internal flag
347 fnRunner_->stopConsuming();
348 fnRunner_->startConsumingInternal(this, queue_.get());
351 folly::throwSystemError("error in EventBase::loopForever()");
355 bool EventBase::bumpHandlingTime() {
356 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
357 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
358 if(nothingHandledYet()) {
359 latestLoopCnt_ = nextLoopCnt_;
361 startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
362 std::chrono::steady_clock::now().time_since_epoch()).count();
364 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
365 " (loop) startWork_ " << startWork_;
371 void EventBase::terminateLoopSoon() {
372 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
378 // Set stop to true, so the event loop will know to exit.
379 // TODO: We should really use an atomic operation here with a release
383 // Call event_base_loopbreak() so that libevent will exit the next time
385 event_base_loopbreak(evb_);
387 // If terminateLoopSoon() is called from another thread,
388 // the EventBase thread might be stuck waiting for events.
389 // In this case, it won't wake up and notice that stop_ is set until it
390 // receives another event. Send an empty frame to the notification queue
391 // so that the event loop will wake up even if there are no other events.
393 // We don't care about the return value of trySendFrame(). If it fails
394 // this likely means the EventBase already has lots of events waiting
397 queue_->putMessage(std::make_pair(nullptr, nullptr));
399 // We don't care if putMessage() fails. This likely means
400 // the EventBase already has lots of events waiting anyway.
404 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
405 DCHECK(isInEventBaseThread());
406 callback->cancelLoopCallback();
407 callback->context_ = RequestContext::saveContext();
408 if (runOnceCallbacks_ != nullptr && thisIteration) {
409 runOnceCallbacks_->push_back(*callback);
411 loopCallbacks_.push_back(*callback);
415 void EventBase::runInLoop(const Cob& cob, bool thisIteration) {
416 DCHECK(isInEventBaseThread());
417 auto wrapper = new FunctionLoopCallback<Cob>(cob);
418 wrapper->context_ = RequestContext::saveContext();
419 if (runOnceCallbacks_ != nullptr && thisIteration) {
420 runOnceCallbacks_->push_back(*wrapper);
422 loopCallbacks_.push_back(*wrapper);
426 void EventBase::runInLoop(Cob&& cob, bool thisIteration) {
427 DCHECK(isInEventBaseThread());
428 auto wrapper = new FunctionLoopCallback<Cob>(std::move(cob));
429 wrapper->context_ = RequestContext::saveContext();
430 if (runOnceCallbacks_ != nullptr && thisIteration) {
431 runOnceCallbacks_->push_back(*wrapper);
433 loopCallbacks_.push_back(*wrapper);
437 bool EventBase::runInEventBaseThread(void (*fn)(void*), void* arg) {
439 // It will be received by the FunctionRunner in the EventBase's thread.
441 // We try not to schedule nullptr callbacks
443 LOG(ERROR) << "EventBase " << this
444 << ": Scheduling nullptr callbacks is not allowed";
448 // Short-circuit if we are already in our event base
449 if (inRunningEventBaseThread()) {
450 runInLoop(new RunInLoopCallback(fn, arg));
456 queue_->putMessage(std::make_pair(fn, arg));
457 } catch (const std::exception& ex) {
458 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
459 << fn << "for EventBase thread: " << ex.what();
466 bool EventBase::runInEventBaseThread(const Cob& fn) {
467 // Short-circuit if we are already in our event base
468 if (inRunningEventBaseThread()) {
474 // Allocate a copy of the function so we can pass it to the other thread
475 // The other thread will delete this copy once the function has been run
477 fnCopy = new Cob(fn);
478 } catch (const std::bad_alloc& ex) {
479 LOG(ERROR) << "failed to allocate tr::function copy "
480 << "for runInEventBaseThread()";
484 if (!runInEventBaseThread(&EventBase::runFunctionPtr, fnCopy)) {
492 bool EventBase::runAfterDelay(const Cob& cob,
494 TimeoutManager::InternalEnum in) {
495 CobTimeout* timeout = new CobTimeout(this, cob, in);
496 if (!timeout->scheduleTimeout(milliseconds)) {
501 pendingCobTimeouts_.push_back(*timeout);
505 bool EventBase::runLoopCallbacks(bool setContext) {
506 if (!loopCallbacks_.empty()) {
508 // Swap the loopCallbacks_ list with a temporary list on our stack.
509 // This way we will only run callbacks scheduled at the time
510 // runLoopCallbacks() was invoked.
512 // If any of these callbacks in turn call runInLoop() to schedule more
513 // callbacks, those new callbacks won't be run until the next iteration
514 // around the event loop. This prevents runInLoop() callbacks from being
515 // able to start file descriptor and timeout based events.
516 LoopCallbackList currentCallbacks;
517 currentCallbacks.swap(loopCallbacks_);
518 runOnceCallbacks_ = ¤tCallbacks;
520 while (!currentCallbacks.empty()) {
521 LoopCallback* callback = ¤tCallbacks.front();
522 currentCallbacks.pop_front();
524 RequestContext::setContext(callback->context_);
526 callback->runLoopCallback();
529 runOnceCallbacks_ = nullptr;
535 void EventBase::initNotificationQueue() {
536 // Infinite size queue
537 queue_.reset(new NotificationQueue<std::pair<void (*)(void*), void*>>());
539 // We allocate fnRunner_ separately, rather than declaring it directly
540 // as a member of EventBase solely so that we don't need to include
541 // NotificationQueue.h from EventBase.h
542 fnRunner_.reset(new FunctionRunner());
544 // Mark this as an internal event, so event_base_loop() will return if
545 // there are no other events besides this one installed.
547 // Most callers don't care about the internal notification queue used by
548 // EventBase. The queue is always installed, so if we did count the queue as
549 // an active event, loop() would never exit with no more events to process.
550 // Users can use loopForever() if they do care about the notification queue.
551 // (This is useful for EventBase threads that do nothing but process
552 // runInEventBaseThread() notifications.)
553 fnRunner_->startConsumingInternal(this, queue_.get());
556 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
557 expCoeff_ = -1.0/timeInterval;
558 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
561 void EventBase::SmoothLoopTime::reset(double value) {
565 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
567 * Position at which the busy sample is considered to be taken.
568 * (Allows to quickly skew our average without editing much code)
570 enum BusySamplePosition {
571 RIGHT = 0, // busy sample placed at the end of the iteration
572 CENTER = 1, // busy sample placed at the middle point of the iteration
573 LEFT = 2, // busy sample placed at the beginning of the iteration
576 VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
577 " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
578 " busy " << busy << " " << __PRETTY_FUNCTION__;
579 idle += oldBusyLeftover_ + busy;
580 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
581 idle -= oldBusyLeftover_;
583 double coeff = exp(idle * expCoeff_);
585 value_ += (1.0 - coeff) * busy;
588 bool EventBase::nothingHandledYet() {
589 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
590 return (nextLoopCnt_ != latestLoopCnt_);
594 void EventBase::runFunctionPtr(Cob* fn) {
595 // The function should never throw an exception, because we have no
596 // way of knowing what sort of error handling to perform.
598 // If it does throw, log a message and abort the program.
601 } catch (const std::exception &ex) {
602 LOG(ERROR) << "runInEventBaseThread() std::function threw a "
603 << typeid(ex).name() << " exception: " << ex.what();
606 LOG(ERROR) << "runInEventBaseThread() std::function threw an exception";
610 // The function object was allocated by runInEventBaseThread().
611 // Delete it once it has been run.
615 EventBase::RunInLoopCallback::RunInLoopCallback(void (*fn)(void*), void* arg)
619 void EventBase::RunInLoopCallback::runLoopCallback() noexcept {
624 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
625 InternalEnum internal) {
627 struct event* ev = obj->getEvent();
628 assert(ev->ev_base == nullptr);
630 event_base_set(getLibeventBase(), ev);
631 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
632 // Set the EVLIST_INTERNAL flag
633 ev->ev_flags |= EVLIST_INTERNAL;
637 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
639 struct event* ev = obj->getEvent();
640 ev->ev_base = nullptr;
643 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
644 std::chrono::milliseconds timeout) {
645 assert(isInEventBaseThread());
646 // Set up the timeval and add the event
648 tv.tv_sec = timeout.count() / 1000LL;
649 tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
651 struct event* ev = obj->getEvent();
652 if (event_add(ev, &tv) < 0) {
653 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
660 void EventBase::cancelTimeout(AsyncTimeout* obj) {
661 assert(isInEventBaseThread());
662 struct event* ev = obj->getEvent();
663 if (EventUtil::isEventRegistered(ev)) {
668 void EventBase::setName(const std::string& name) {
669 assert(isInEventBaseThread());
671 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
673 pthread_setname_np(loopThread_.load(std::memory_order_relaxed),
679 const std::string& EventBase::getName() {
680 assert(isInEventBaseThread());