Get rid of try/catch in messageAvailable, which is now noexcept
[folly.git] / folly / io / async / EventBase.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #ifndef __STDC_FORMAT_MACROS
18 #define __STDC_FORMAT_MACROS
19 #endif
20
21 #include <folly/io/async/EventBase.h>
22 #include <folly/io/async/VirtualEventBase.h>
23
24 #include <folly/Memory.h>
25 #include <folly/ThreadName.h>
26 #include <folly/io/async/NotificationQueue.h>
27 #include <folly/portability/Unistd.h>
28
29 #include <condition_variable>
30 #include <fcntl.h>
31 #include <mutex>
32 #include <thread>
33
34 namespace folly {
35
36 /*
37  * EventBase::FunctionRunner
38  */
39
40 class EventBase::FunctionRunner
41     : public NotificationQueue<EventBase::Func>::Consumer {
42  public:
43   void messageAvailable(Func&& msg) noexcept override {
44     // In libevent2, internal events do not break the loop.
45     // Most users would expect loop(), followed by runInEventBaseThread(),
46     // to break the loop and check if it should exit or not.
47     // To have similar bejaviour to libevent1.4, tell the loop to break here.
48     // Note that loop() may still continue to loop, but it will also check the
49     // stop_ flag as well as runInLoop callbacks, etc.
50     event_base_loopbreak(getEventBase()->evb_);
51
52     if (!msg) {
53       // terminateLoopSoon() sends a null message just to
54       // wake up the loop.  We can ignore these messages.
55       return;
56     }
57     msg();
58   }
59 };
60
61 // The interface used to libevent is not thread-safe.  Calls to
62 // event_init() and event_base_free() directly modify an internal
63 // global 'current_base', so a mutex is required to protect this.
64 //
65 // event_init() should only ever be called once.  Subsequent calls
66 // should be made to event_base_new().  We can recognise that
67 // event_init() has already been called by simply inspecting current_base.
68 static std::mutex libevent_mutex_;
69
70 /*
71  * EventBase methods
72  */
73
74 EventBase::EventBase(bool enableTimeMeasurement)
75   : runOnceCallbacks_(nullptr)
76   , stop_(false)
77   , loopThread_()
78   , queue_(nullptr)
79   , fnRunner_(nullptr)
80   , maxLatency_(0)
81   , avgLoopTime_(std::chrono::seconds(2))
82   , maxLatencyLoopTime_(avgLoopTime_)
83   , enableTimeMeasurement_(enableTimeMeasurement)
84   , nextLoopCnt_(uint64_t(-40)) // Early wrap-around so bugs will manifest soon
85   , latestLoopCnt_(nextLoopCnt_)
86   , startWork_()
87   , observer_(nullptr)
88   , observerSampleCount_(0)
89   , executionObserver_(nullptr) {
90   struct event ev;
91   {
92     std::lock_guard<std::mutex> lock(libevent_mutex_);
93
94     // The value 'current_base' (libevent 1) or
95     // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
96     // allowing examination of its value without an explicit reference here.
97     // If ev.ev_base is NULL, then event_init() must be called, otherwise
98     // call event_base_new().
99     event_set(&ev, 0, 0, nullptr, nullptr);
100     if (!ev.ev_base) {
101       evb_ = event_init();
102     }
103   }
104
105   if (ev.ev_base) {
106     evb_ = event_base_new();
107   }
108
109   if (UNLIKELY(evb_ == nullptr)) {
110     LOG(ERROR) << "EventBase(): Failed to init event base.";
111     folly::throwSystemError("error in EventBase::EventBase()");
112   }
113   VLOG(5) << "EventBase(): Created.";
114   initNotificationQueue();
115   RequestContext::saveContext();
116 }
117
118 // takes ownership of the event_base
119 EventBase::EventBase(event_base* evb, bool enableTimeMeasurement)
120   : runOnceCallbacks_(nullptr)
121   , stop_(false)
122   , loopThread_()
123   , evb_(evb)
124   , queue_(nullptr)
125   , fnRunner_(nullptr)
126   , maxLatency_(0)
127   , avgLoopTime_(std::chrono::seconds(2))
128   , maxLatencyLoopTime_(avgLoopTime_)
129   , enableTimeMeasurement_(enableTimeMeasurement)
130   , nextLoopCnt_(uint64_t(-40)) // Early wrap-around so bugs will manifest soon
131   , latestLoopCnt_(nextLoopCnt_)
132   , startWork_()
133   , observer_(nullptr)
134   , observerSampleCount_(0)
135   , executionObserver_(nullptr) {
136   if (UNLIKELY(evb_ == nullptr)) {
137     LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
138     throw std::invalid_argument("EventBase(): event base cannot be nullptr");
139   }
140   initNotificationQueue();
141   RequestContext::saveContext();
142 }
143
144 EventBase::~EventBase() {
145   std::future<void> virtualEventBaseDestroyFuture;
146   if (virtualEventBase_) {
147     virtualEventBaseDestroyFuture = virtualEventBase_->destroy();
148   }
149
150   // Keep looping until all keep-alive handles are released. Each keep-alive
151   // handle signals that some external code will still schedule some work on
152   // this EventBase (so it's not safe to destroy it).
153   while (loopKeepAliveCount() > 0) {
154     applyLoopKeepAlive();
155     loopOnce();
156   }
157
158   if (virtualEventBaseDestroyFuture.valid()) {
159     virtualEventBaseDestroyFuture.get();
160   }
161
162   // Call all destruction callbacks, before we start cleaning up our state.
163   while (!onDestructionCallbacks_.empty()) {
164     LoopCallback* callback = &onDestructionCallbacks_.front();
165     onDestructionCallbacks_.pop_front();
166     callback->runLoopCallback();
167   }
168
169   clearCobTimeouts();
170
171   DCHECK_EQ(0u, runBeforeLoopCallbacks_.size());
172
173   (void)runLoopCallbacks();
174
175   if (!fnRunner_->consumeUntilDrained()) {
176     LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
177   }
178
179   // Stop consumer before deleting NotificationQueue
180   fnRunner_->stopConsuming();
181   {
182     std::lock_guard<std::mutex> lock(libevent_mutex_);
183     event_base_free(evb_);
184   }
185
186   {
187     std::lock_guard<std::mutex> lock(localStorageMutex_);
188     for (auto storage : localStorageToDtor_) {
189       storage->onEventBaseDestruction(*this);
190     }
191   }
192   VLOG(5) << "EventBase(): Destroyed.";
193 }
194
195 size_t EventBase::getNotificationQueueSize() const {
196   return queue_->size();
197 }
198
199 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
200   fnRunner_->setMaxReadAtOnce(maxAtOnce);
201 }
202
203 // Set smoothing coefficient for loop load average; input is # of milliseconds
204 // for exp(-1) decay.
205 void EventBase::setLoadAvgMsec(std::chrono::milliseconds ms) {
206   assert(enableTimeMeasurement_);
207   std::chrono::microseconds us = std::chrono::milliseconds(ms);
208   if (ms > std::chrono::milliseconds::zero()) {
209     maxLatencyLoopTime_.setTimeInterval(us);
210     avgLoopTime_.setTimeInterval(us);
211   } else {
212     LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
213   }
214 }
215
216 void EventBase::resetLoadAvg(double value) {
217   assert(enableTimeMeasurement_);
218   avgLoopTime_.reset(value);
219   maxLatencyLoopTime_.reset(value);
220 }
221
222 static std::chrono::milliseconds
223 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
224   auto result = std::chrono::steady_clock::now() - *prev;
225   *prev = std::chrono::steady_clock::now();
226
227   return std::chrono::duration_cast<std::chrono::milliseconds>(result);
228 }
229
230 void EventBase::waitUntilRunning() {
231   while (!isRunning()) {
232     std::this_thread::yield();
233   }
234 }
235
236 // enters the event_base loop -- will only exit when forced to
237 bool EventBase::loop() {
238   return loopBody();
239 }
240
241 bool EventBase::loopOnce(int flags) {
242   return loopBody(flags | EVLOOP_ONCE);
243 }
244
245 bool EventBase::loopBody(int flags) {
246   VLOG(5) << "EventBase(): Starting loop.";
247
248   DCHECK(!invokingLoop_)
249       << "Your code just tried to loop over an event base from inside another "
250       << "event base loop. Since libevent is not reentrant, this leads to "
251       << "undefined behavior in opt builds. Please fix immediately. For the "
252       << "common case of an inner function that needs to do some synchronous "
253       << "computation on an event-base, replace getEventBase() by a new, "
254       << "stack-allocated EvenBase.";
255   invokingLoop_ = true;
256   SCOPE_EXIT {
257     invokingLoop_ = false;
258   };
259
260   int res = 0;
261   bool ranLoopCallbacks;
262   bool blocking = !(flags & EVLOOP_NONBLOCK);
263   bool once = (flags & EVLOOP_ONCE);
264
265   // time-measurement variables.
266   std::chrono::steady_clock::time_point prev;
267   std::chrono::steady_clock::time_point idleStart = {};
268   std::chrono::microseconds busy;
269   std::chrono::microseconds idle;
270
271   loopThread_.store(std::this_thread::get_id(), std::memory_order_release);
272
273   if (!name_.empty()) {
274     setThreadName(name_);
275   }
276
277   if (enableTimeMeasurement_) {
278     prev = std::chrono::steady_clock::now();
279     idleStart = std::chrono::steady_clock::now();
280   }
281
282   while (!stop_.load(std::memory_order_acquire)) {
283     applyLoopKeepAlive();
284     ++nextLoopCnt_;
285
286     // Run the before loop callbacks
287     LoopCallbackList callbacks;
288     callbacks.swap(runBeforeLoopCallbacks_);
289
290     while(!callbacks.empty()) {
291       auto* item = &callbacks.front();
292       callbacks.pop_front();
293       item->runLoopCallback();
294     }
295
296     // nobody can add loop callbacks from within this thread if
297     // we don't have to handle anything to start with...
298     if (blocking && loopCallbacks_.empty()) {
299       res = event_base_loop(evb_, EVLOOP_ONCE);
300     } else {
301       res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
302     }
303
304     ranLoopCallbacks = runLoopCallbacks();
305
306     if (enableTimeMeasurement_) {
307       busy = std::chrono::duration_cast<std::chrono::microseconds>(
308           std::chrono::steady_clock::now() - startWork_);
309       idle = std::chrono::duration_cast<std::chrono::microseconds>(
310           startWork_ - idleStart);
311
312       avgLoopTime_.addSample(std::chrono::microseconds(idle),
313         std::chrono::microseconds(busy));
314       maxLatencyLoopTime_.addSample(std::chrono::microseconds(idle),
315         std::chrono::microseconds(busy));
316
317       if (observer_) {
318         if (observerSampleCount_++ == observer_->getSampleRate()) {
319           observerSampleCount_ = 0;
320           observer_->loopSample(busy.count(), idle.count());
321         }
322       }
323
324       VLOG(11) << "EventBase "  << this         << " did not timeout " <<
325         " loop time guess: "    << (busy + idle).count()  <<
326         " idle time: "          << idle.count()         <<
327         " busy time: "          << busy.count()         <<
328         " avgLoopTime: "        << avgLoopTime_.get() <<
329         " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
330         " maxLatency_: "        << maxLatency_.count() << "us" <<
331         " notificationQueueSize: " << getNotificationQueueSize() <<
332         " nothingHandledYet(): " << nothingHandledYet();
333
334       // see if our average loop time has exceeded our limit
335       if ((maxLatency_ > std::chrono::microseconds::zero()) &&
336           (maxLatencyLoopTime_.get() > double(maxLatency_.count()))) {
337         maxLatencyCob_();
338         // back off temporarily -- don't keep spamming maxLatencyCob_
339         // if we're only a bit over the limit
340         maxLatencyLoopTime_.dampen(0.9);
341       }
342
343       // Our loop run did real work; reset the idle timer
344       idleStart = std::chrono::steady_clock::now();
345     } else {
346       VLOG(11) << "EventBase " << this << " did not timeout";
347     }
348
349     // If the event loop indicate that there were no more events, and
350     // we also didn't have any loop callbacks to run, there is nothing left to
351     // do.
352     if (res != 0 && !ranLoopCallbacks) {
353       // Since Notification Queue is marked 'internal' some events may not have
354       // run.  Run them manually if so, and continue looping.
355       //
356       if (getNotificationQueueSize() > 0) {
357         fnRunner_->handlerReady(0);
358       } else {
359         break;
360       }
361     }
362
363     if (enableTimeMeasurement_) {
364       VLOG(11) << "EventBase " << this << " loop time: " <<
365         getTimeDelta(&prev).count();
366     }
367
368     if (once) {
369       break;
370     }
371   }
372   // Reset stop_ so loop() can be called again
373   stop_ = false;
374
375   if (res < 0) {
376     LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
377     return false;
378   } else if (res == 1) {
379     VLOG(5) << "EventBase: ran out of events (exiting loop)!";
380   } else if (res > 1) {
381     LOG(ERROR) << "EventBase: unknown event loop result = " << res;
382     return false;
383   }
384
385   loopThread_.store({}, std::memory_order_release);
386
387   VLOG(5) << "EventBase(): Done with loop.";
388   return true;
389 }
390
391 ssize_t EventBase::loopKeepAliveCount() {
392   if (loopKeepAliveCountAtomic_.load(std::memory_order_relaxed)) {
393     loopKeepAliveCount_ +=
394         loopKeepAliveCountAtomic_.exchange(0, std::memory_order_relaxed);
395   }
396   DCHECK_GE(loopKeepAliveCount_, 0);
397
398   return loopKeepAliveCount_;
399 }
400
401 void EventBase::applyLoopKeepAlive() {
402   auto keepAliveCount = loopKeepAliveCount();
403   // Make sure default VirtualEventBase won't hold EventBase::loop() forever.
404   if (virtualEventBase_ && virtualEventBase_->keepAliveCount() == 1) {
405     --keepAliveCount;
406   }
407
408   if (loopKeepAliveActive_ && keepAliveCount == 0) {
409     // Restore the notification queue internal flag
410     fnRunner_->stopConsuming();
411     fnRunner_->startConsumingInternal(this, queue_.get());
412     loopKeepAliveActive_ = false;
413   } else if (!loopKeepAliveActive_ && keepAliveCount > 0) {
414     // Update the notification queue event to treat it as a normal
415     // (non-internal) event.  The notification queue event always remains
416     // installed, and the main loop won't exit with it installed.
417     fnRunner_->stopConsuming();
418     fnRunner_->startConsuming(this, queue_.get());
419     loopKeepAliveActive_ = true;
420   }
421 }
422
423 void EventBase::loopForever() {
424   bool ret;
425   {
426     SCOPE_EXIT {
427       applyLoopKeepAlive();
428     };
429     // Make sure notification queue events are treated as normal events.
430     // We can't use loopKeepAlive() here since LoopKeepAlive token can only be
431     // released inside a loop.
432     ++loopKeepAliveCount_;
433     SCOPE_EXIT {
434       --loopKeepAliveCount_;
435     };
436     ret = loop();
437   }
438
439   if (!ret) {
440     folly::throwSystemError("error in EventBase::loopForever()");
441   }
442 }
443
444 void EventBase::bumpHandlingTime() {
445   if (!enableTimeMeasurement_) {
446     return;
447   }
448
449   VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
450     " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
451   if (nothingHandledYet()) {
452     latestLoopCnt_ = nextLoopCnt_;
453     // set the time
454     startWork_ = std::chrono::steady_clock::now();
455
456     VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
457              << " (loop) startWork_ " << startWork_.time_since_epoch().count();
458   }
459 }
460
461 void EventBase::terminateLoopSoon() {
462   VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
463
464   // Set stop to true, so the event loop will know to exit.
465   // TODO: We should really use an atomic operation here with a release
466   // barrier.
467   stop_ = true;
468
469   // Call event_base_loopbreak() so that libevent will exit the next time
470   // around the loop.
471   event_base_loopbreak(evb_);
472
473   // If terminateLoopSoon() is called from another thread,
474   // the EventBase thread might be stuck waiting for events.
475   // In this case, it won't wake up and notice that stop_ is set until it
476   // receives another event.  Send an empty frame to the notification queue
477   // so that the event loop will wake up even if there are no other events.
478   //
479   // We don't care about the return value of trySendFrame().  If it fails
480   // this likely means the EventBase already has lots of events waiting
481   // anyway.
482   try {
483     queue_->putMessage(nullptr);
484   } catch (...) {
485     // We don't care if putMessage() fails.  This likely means
486     // the EventBase already has lots of events waiting anyway.
487   }
488 }
489
490 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
491   DCHECK(isInEventBaseThread());
492   callback->cancelLoopCallback();
493   callback->context_ = RequestContext::saveContext();
494   if (runOnceCallbacks_ != nullptr && thisIteration) {
495     runOnceCallbacks_->push_back(*callback);
496   } else {
497     loopCallbacks_.push_back(*callback);
498   }
499 }
500
501 void EventBase::runInLoop(Func cob, bool thisIteration) {
502   DCHECK(isInEventBaseThread());
503   auto wrapper = new FunctionLoopCallback(std::move(cob));
504   wrapper->context_ = RequestContext::saveContext();
505   if (runOnceCallbacks_ != nullptr && thisIteration) {
506     runOnceCallbacks_->push_back(*wrapper);
507   } else {
508     loopCallbacks_.push_back(*wrapper);
509   }
510 }
511
512 void EventBase::runOnDestruction(LoopCallback* callback) {
513   std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
514   callback->cancelLoopCallback();
515   onDestructionCallbacks_.push_back(*callback);
516 }
517
518 void EventBase::runBeforeLoop(LoopCallback* callback) {
519   DCHECK(isInEventBaseThread());
520   callback->cancelLoopCallback();
521   runBeforeLoopCallbacks_.push_back(*callback);
522 }
523
524 bool EventBase::runInEventBaseThread(Func fn) {
525   // Send the message.
526   // It will be received by the FunctionRunner in the EventBase's thread.
527
528   // We try not to schedule nullptr callbacks
529   if (!fn) {
530     LOG(ERROR) << "EventBase " << this
531                << ": Scheduling nullptr callbacks is not allowed";
532     return false;
533   }
534
535   // Short-circuit if we are already in our event base
536   if (inRunningEventBaseThread()) {
537     runInLoop(std::move(fn));
538     return true;
539
540   }
541
542   try {
543     queue_->putMessage(std::move(fn));
544   } catch (const std::exception& ex) {
545     LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
546                << "for EventBase thread: " << ex.what();
547     return false;
548   }
549
550   return true;
551 }
552
553 bool EventBase::runInEventBaseThreadAndWait(FuncRef fn) {
554   if (inRunningEventBaseThread()) {
555     LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
556                << "allowed";
557     return false;
558   }
559
560   bool ready = false;
561   std::mutex m;
562   std::condition_variable cv;
563   runInEventBaseThread([&] {
564       SCOPE_EXIT {
565         std::unique_lock<std::mutex> l(m);
566         ready = true;
567         cv.notify_one();
568         // We cannot release the lock before notify_one, because a spurious
569         // wakeup in the waiting thread may lead to cv and m going out of scope
570         // prematurely.
571       };
572       fn();
573   });
574   std::unique_lock<std::mutex> l(m);
575   cv.wait(l, [&] { return ready; });
576
577   return true;
578 }
579
580 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(FuncRef fn) {
581   if (isInEventBaseThread()) {
582     fn();
583     return true;
584   } else {
585     return runInEventBaseThreadAndWait(std::move(fn));
586   }
587 }
588
589 bool EventBase::runLoopCallbacks() {
590   if (!loopCallbacks_.empty()) {
591     bumpHandlingTime();
592     // Swap the loopCallbacks_ list with a temporary list on our stack.
593     // This way we will only run callbacks scheduled at the time
594     // runLoopCallbacks() was invoked.
595     //
596     // If any of these callbacks in turn call runInLoop() to schedule more
597     // callbacks, those new callbacks won't be run until the next iteration
598     // around the event loop.  This prevents runInLoop() callbacks from being
599     // able to start file descriptor and timeout based events.
600     LoopCallbackList currentCallbacks;
601     currentCallbacks.swap(loopCallbacks_);
602     runOnceCallbacks_ = &currentCallbacks;
603
604     while (!currentCallbacks.empty()) {
605       LoopCallback* callback = &currentCallbacks.front();
606       currentCallbacks.pop_front();
607       folly::RequestContextScopeGuard rctx(callback->context_);
608       callback->runLoopCallback();
609     }
610
611     runOnceCallbacks_ = nullptr;
612     return true;
613   }
614   return false;
615 }
616
617 void EventBase::initNotificationQueue() {
618   // Infinite size queue
619   queue_.reset(new NotificationQueue<Func>());
620
621   // We allocate fnRunner_ separately, rather than declaring it directly
622   // as a member of EventBase solely so that we don't need to include
623   // NotificationQueue.h from EventBase.h
624   fnRunner_.reset(new FunctionRunner());
625
626   // Mark this as an internal event, so event_base_loop() will return if
627   // there are no other events besides this one installed.
628   //
629   // Most callers don't care about the internal notification queue used by
630   // EventBase.  The queue is always installed, so if we did count the queue as
631   // an active event, loop() would never exit with no more events to process.
632   // Users can use loopForever() if they do care about the notification queue.
633   // (This is useful for EventBase threads that do nothing but process
634   // runInEventBaseThread() notifications.)
635   fnRunner_->startConsumingInternal(this, queue_.get());
636 }
637
638 void EventBase::SmoothLoopTime::setTimeInterval(
639     std::chrono::microseconds timeInterval) {
640   expCoeff_ = -1.0 / timeInterval.count();
641   VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
642 }
643
644 void EventBase::SmoothLoopTime::reset(double value) {
645   value_ = value;
646 }
647
648 void EventBase::SmoothLoopTime::addSample(
649     std::chrono::microseconds idle,
650     std::chrono::microseconds busy) {
651   /*
652    * Position at which the busy sample is considered to be taken.
653    * (Allows to quickly skew our average without editing much code)
654    */
655   enum BusySamplePosition {
656     RIGHT = 0, // busy sample placed at the end of the iteration
657     CENTER = 1, // busy sample placed at the middle point of the iteration
658     LEFT = 2, // busy sample placed at the beginning of the iteration
659   };
660
661   // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
662   // and D676020 for more info on this calculation.
663   VLOG(11) << "idle " << idle.count() << " oldBusyLeftover_ "
664            << oldBusyLeftover_.count() << " idle + oldBusyLeftover_ "
665            << (idle + oldBusyLeftover_).count() << " busy " << busy.count()
666            << " " << __PRETTY_FUNCTION__;
667   idle += oldBusyLeftover_ + busy;
668   oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
669   idle -= oldBusyLeftover_;
670
671   double coeff = exp(idle.count() * expCoeff_);
672   value_ *= coeff;
673   value_ += (1.0 - coeff) * busy.count();
674 }
675
676 bool EventBase::nothingHandledYet() const noexcept {
677   VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
678   return (nextLoopCnt_ != latestLoopCnt_);
679 }
680
681 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
682                                       InternalEnum internal) {
683
684   struct event* ev = obj->getEvent();
685   assert(ev->ev_base == nullptr);
686
687   event_base_set(getLibeventBase(), ev);
688   if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
689     // Set the EVLIST_INTERNAL flag
690     event_ref_flags(ev) |= EVLIST_INTERNAL;
691   }
692 }
693
694 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
695   cancelTimeout(obj);
696   struct event* ev = obj->getEvent();
697   ev->ev_base = nullptr;
698 }
699
700 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
701                                  TimeoutManager::timeout_type timeout) {
702   assert(isInEventBaseThread());
703   // Set up the timeval and add the event
704   struct timeval tv;
705   tv.tv_sec = long(timeout.count() / 1000LL);
706   tv.tv_usec = long((timeout.count() % 1000LL) * 1000LL);
707
708   struct event* ev = obj->getEvent();
709   if (event_add(ev, &tv) < 0) {
710     LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
711     return false;
712   }
713
714   return true;
715 }
716
717 void EventBase::cancelTimeout(AsyncTimeout* obj) {
718   assert(isInEventBaseThread());
719   struct event* ev = obj->getEvent();
720   if (EventUtil::isEventRegistered(ev)) {
721     event_del(ev);
722   }
723 }
724
725 void EventBase::setName(const std::string& name) {
726   assert(isInEventBaseThread());
727   name_ = name;
728
729   if (isRunning()) {
730     setThreadName(loopThread_.load(std::memory_order_relaxed),
731                   name_);
732   }
733 }
734
735 const std::string& EventBase::getName() {
736   assert(isInEventBaseThread());
737   return name_;
738 }
739
740 const char* EventBase::getLibeventVersion() { return event_get_version(); }
741 const char* EventBase::getLibeventMethod() { return event_get_method(); }
742
743 VirtualEventBase& EventBase::getVirtualEventBase() {
744   folly::call_once(virtualEventBaseInitFlag_, [&] {
745     virtualEventBase_ = folly::make_unique<VirtualEventBase>(*this);
746   });
747
748   return *virtualEventBase_;
749 }
750
751 } // folly