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() {
226 VLOG(5) << "EventBase(): Starting loop.";
228 bool ranLoopCallbacks;
231 loopThread_.store(pthread_self(), std::memory_order_release);
233 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
234 if (!name_.empty()) {
235 pthread_setname_np(pthread_self(), name_.c_str());
239 auto prev = std::chrono::steady_clock::now();
240 int64_t idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
241 std::chrono::steady_clock::now().time_since_epoch()).count();
243 // TODO: Read stop_ atomically with an acquire barrier.
247 // nobody can add loop callbacks from within this thread if
248 // we don't have to handle anything to start with...
249 nonBlocking = (loopCallbacks_.empty() ? 0 : EVLOOP_NONBLOCK);
250 res = event_base_loop(evb_, EVLOOP_ONCE | nonBlocking);
251 ranLoopCallbacks = runLoopCallbacks();
253 int64_t busy = std::chrono::duration_cast<std::chrono::microseconds>(
254 std::chrono::steady_clock::now().time_since_epoch()).count() - startWork_;
255 int64_t idle = startWork_ - idleStart;
257 avgLoopTime_.addSample(idle, busy);
258 maxLatencyLoopTime_.addSample(idle, busy);
261 if (observerSampleCount_++ == observer_->getSampleRate()) {
262 observerSampleCount_ = 0;
263 observer_->loopSample(busy, idle);
267 VLOG(11) << "EventBase " << this << " did not timeout "
268 " loop time guess: " << busy + idle <<
269 " idle time: " << idle <<
270 " busy time: " << busy <<
271 " avgLoopTime: " << avgLoopTime_.get() <<
272 " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
273 " maxLatency_: " << maxLatency_ <<
274 " nothingHandledYet(): "<< nothingHandledYet();
276 // see if our average loop time has exceeded our limit
277 if ((maxLatency_ > 0) &&
278 (maxLatencyLoopTime_.get() > double(maxLatency_))) {
280 // back off temporarily -- don't keep spamming maxLatencyCob_
281 // if we're only a bit over the limit
282 maxLatencyLoopTime_.dampen(0.9);
285 // Our loop run did real work; reset the idle timer
286 idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
287 std::chrono::steady_clock::now().time_since_epoch()).count();
289 // If the event loop indicate that there were no more events, and
290 // we also didn't have any loop callbacks to run, there is nothing left to
292 if (res != 0 && !ranLoopCallbacks) {
293 // Since Notification Queue is marked 'internal' some events may not have
294 // run. Run them manually if so, and continue looping.
296 if (getNotificationQueueSize() > 0) {
297 fnRunner_->handlerReady(0);
303 VLOG(5) << "EventBase " << this << " loop time: " <<
304 getTimeDelta(&prev).count();
306 // Reset stop_ so loop() can be called again
310 LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
312 } else if (res == 1) {
313 VLOG(5) << "EventBase: ran out of events (exiting loop)!";
314 } else if (res > 1) {
315 LOG(ERROR) << "EventBase: unknown event loop result = " << res;
319 loopThread_.store(0, std::memory_order_release);
321 VLOG(5) << "EventBase(): Done with loop.";
325 void EventBase::loopForever() {
326 // Update the notification queue event to treat it as a normal (non-internal)
327 // event. The notification queue event always remains installed, and the main
328 // loop won't exit with it installed.
329 fnRunner_->stopConsuming();
330 fnRunner_->startConsuming(this, queue_.get());
334 // Restore the notification queue internal flag
335 fnRunner_->stopConsuming();
336 fnRunner_->startConsumingInternal(this, queue_.get());
339 folly::throwSystemError("error in EventBase::loopForever()");
343 bool EventBase::bumpHandlingTime() {
344 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
345 " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
346 if(nothingHandledYet()) {
347 latestLoopCnt_ = nextLoopCnt_;
349 startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
350 std::chrono::steady_clock::now().time_since_epoch()).count();
352 VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
353 " (loop) startWork_ " << startWork_;
359 void EventBase::terminateLoopSoon() {
360 VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
366 // Set stop to true, so the event loop will know to exit.
367 // TODO: We should really use an atomic operation here with a release
371 // Call event_base_loopbreak() so that libevent will exit the next time
373 event_base_loopbreak(evb_);
375 // If terminateLoopSoon() is called from another thread,
376 // the EventBase thread might be stuck waiting for events.
377 // In this case, it won't wake up and notice that stop_ is set until it
378 // receives another event. Send an empty frame to the notification queue
379 // so that the event loop will wake up even if there are no other events.
381 // We don't care about the return value of trySendFrame(). If it fails
382 // this likely means the EventBase already has lots of events waiting
385 queue_->putMessage(std::make_pair(nullptr, nullptr));
387 // We don't care if putMessage() fails. This likely means
388 // the EventBase already has lots of events waiting anyway.
392 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
393 DCHECK(isInEventBaseThread());
394 callback->cancelLoopCallback();
395 callback->context_ = RequestContext::saveContext();
396 if (runOnceCallbacks_ != nullptr && thisIteration) {
397 runOnceCallbacks_->push_back(*callback);
399 loopCallbacks_.push_back(*callback);
403 void EventBase::runInLoop(const Cob& cob, bool thisIteration) {
404 DCHECK(isInEventBaseThread());
405 auto wrapper = new FunctionLoopCallback<Cob>(cob);
406 wrapper->context_ = RequestContext::saveContext();
407 if (runOnceCallbacks_ != nullptr && thisIteration) {
408 runOnceCallbacks_->push_back(*wrapper);
410 loopCallbacks_.push_back(*wrapper);
414 void EventBase::runInLoop(Cob&& cob, bool thisIteration) {
415 DCHECK(isInEventBaseThread());
416 auto wrapper = new FunctionLoopCallback<Cob>(std::move(cob));
417 wrapper->context_ = RequestContext::saveContext();
418 if (runOnceCallbacks_ != nullptr && thisIteration) {
419 runOnceCallbacks_->push_back(*wrapper);
421 loopCallbacks_.push_back(*wrapper);
425 bool EventBase::runInEventBaseThread(void (*fn)(void*), void* arg) {
427 // It will be received by the FunctionRunner in the EventBase's thread.
429 // We try not to schedule nullptr callbacks
431 LOG(ERROR) << "EventBase " << this
432 << ": Scheduling nullptr callbacks is not allowed";
436 // Short-circuit if we are already in our event base
437 if (inRunningEventBaseThread()) {
438 runInLoop(new RunInLoopCallback(fn, arg));
444 queue_->putMessage(std::make_pair(fn, arg));
445 } catch (const std::exception& ex) {
446 LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
447 << fn << "for EventBase thread: " << ex.what();
454 bool EventBase::runInEventBaseThread(const Cob& fn) {
455 // Short-circuit if we are already in our event base
456 if (inRunningEventBaseThread()) {
462 // Allocate a copy of the function so we can pass it to the other thread
463 // The other thread will delete this copy once the function has been run
465 fnCopy = new Cob(fn);
466 } catch (const std::bad_alloc& ex) {
467 LOG(ERROR) << "failed to allocate tr::function copy "
468 << "for runInEventBaseThread()";
472 if (!runInEventBaseThread(&EventBase::runFunctionPtr, fnCopy)) {
480 bool EventBase::runAfterDelay(const Cob& cob,
482 TimeoutManager::InternalEnum in) {
483 CobTimeout* timeout = new CobTimeout(this, cob, in);
484 if (!timeout->scheduleTimeout(milliseconds)) {
489 pendingCobTimeouts_.push_back(*timeout);
493 bool EventBase::runLoopCallbacks(bool setContext) {
494 if (!loopCallbacks_.empty()) {
496 // Swap the loopCallbacks_ list with a temporary list on our stack.
497 // This way we will only run callbacks scheduled at the time
498 // runLoopCallbacks() was invoked.
500 // If any of these callbacks in turn call runInLoop() to schedule more
501 // callbacks, those new callbacks won't be run until the next iteration
502 // around the event loop. This prevents runInLoop() callbacks from being
503 // able to start file descriptor and timeout based events.
504 LoopCallbackList currentCallbacks;
505 currentCallbacks.swap(loopCallbacks_);
506 runOnceCallbacks_ = ¤tCallbacks;
508 while (!currentCallbacks.empty()) {
509 LoopCallback* callback = ¤tCallbacks.front();
510 currentCallbacks.pop_front();
512 RequestContext::setContext(callback->context_);
514 callback->runLoopCallback();
517 runOnceCallbacks_ = nullptr;
523 void EventBase::initNotificationQueue() {
524 // Infinite size queue
525 queue_.reset(new NotificationQueue<std::pair<void (*)(void*), void*>>());
527 // We allocate fnRunner_ separately, rather than declaring it directly
528 // as a member of EventBase solely so that we don't need to include
529 // NotificationQueue.h from EventBase.h
530 fnRunner_.reset(new FunctionRunner());
532 // Mark this as an internal event, so event_base_loop() will return if
533 // there are no other events besides this one installed.
535 // Most callers don't care about the internal notification queue used by
536 // EventBase. The queue is always installed, so if we did count the queue as
537 // an active event, loop() would never exit with no more events to process.
538 // Users can use loopForever() if they do care about the notification queue.
539 // (This is useful for EventBase threads that do nothing but process
540 // runInEventBaseThread() notifications.)
541 fnRunner_->startConsumingInternal(this, queue_.get());
544 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
545 expCoeff_ = -1.0/timeInterval;
546 VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
549 void EventBase::SmoothLoopTime::reset(double value) {
553 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
555 * Position at which the busy sample is considered to be taken.
556 * (Allows to quickly skew our average without editing much code)
558 enum BusySamplePosition {
559 RIGHT = 0, // busy sample placed at the end of the iteration
560 CENTER = 1, // busy sample placed at the middle point of the iteration
561 LEFT = 2, // busy sample placed at the beginning of the iteration
564 VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
565 " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
566 " busy " << busy << " " << __PRETTY_FUNCTION__;
567 idle += oldBusyLeftover_ + busy;
568 oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
569 idle -= oldBusyLeftover_;
571 double coeff = exp(idle * expCoeff_);
573 value_ += (1.0 - coeff) * busy;
576 bool EventBase::nothingHandledYet() {
577 VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
578 return (nextLoopCnt_ != latestLoopCnt_);
582 void EventBase::runFunctionPtr(Cob* fn) {
583 // The function should never throw an exception, because we have no
584 // way of knowing what sort of error handling to perform.
586 // If it does throw, log a message and abort the program.
589 } catch (const std::exception &ex) {
590 LOG(ERROR) << "runInEventBaseThread() std::function threw a "
591 << typeid(ex).name() << " exception: " << ex.what();
594 LOG(ERROR) << "runInEventBaseThread() std::function threw an exception";
598 // The function object was allocated by runInEventBaseThread().
599 // Delete it once it has been run.
603 EventBase::RunInLoopCallback::RunInLoopCallback(void (*fn)(void*), void* arg)
607 void EventBase::RunInLoopCallback::runLoopCallback() noexcept {
612 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
613 InternalEnum internal) {
615 struct event* ev = obj->getEvent();
616 assert(ev->ev_base == nullptr);
618 event_base_set(getLibeventBase(), ev);
619 if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
620 // Set the EVLIST_INTERNAL flag
621 ev->ev_flags |= EVLIST_INTERNAL;
625 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
627 struct event* ev = obj->getEvent();
628 ev->ev_base = nullptr;
631 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
632 std::chrono::milliseconds timeout) {
633 assert(isInEventBaseThread());
634 // Set up the timeval and add the event
636 tv.tv_sec = timeout.count() / 1000LL;
637 tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
639 struct event* ev = obj->getEvent();
640 if (event_add(ev, &tv) < 0) {
641 LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
648 void EventBase::cancelTimeout(AsyncTimeout* obj) {
649 assert(isInEventBaseThread());
650 struct event* ev = obj->getEvent();
651 if (EventUtil::isEventRegistered(ev)) {
656 void EventBase::setName(const std::string& name) {
657 assert(isInEventBaseThread());
659 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
661 pthread_setname_np(loopThread_.load(std::memory_order_relaxed),
667 const std::string& EventBase::getName() {
668 assert(isInEventBaseThread());