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