Retire BOOST_STATIC_ASSERT in favor of static_assert
[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     ++nextLoopCnt_;
323
324     // Run the before loop callbacks
325     LoopCallbackList callbacks;
326     callbacks.swap(runBeforeLoopCallbacks_);
327
328     while(!callbacks.empty()) {
329       auto* item = &callbacks.front();
330       callbacks.pop_front();
331       item->runLoopCallback();
332     }
333
334     // nobody can add loop callbacks from within this thread if
335     // we don't have to handle anything to start with...
336     if (blocking && loopCallbacks_.empty()) {
337       res = event_base_loop(evb_, EVLOOP_ONCE);
338     } else {
339       res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
340     }
341
342     ranLoopCallbacks = runLoopCallbacks();
343
344     if (enableTimeMeasurement_) {
345       busy = std::chrono::duration_cast<std::chrono::microseconds>(
346         std::chrono::steady_clock::now().time_since_epoch()).count() -
347         startWork_;
348       idle = startWork_ - idleStart;
349
350       avgLoopTime_.addSample(idle, busy);
351       maxLatencyLoopTime_.addSample(idle, busy);
352
353       if (observer_) {
354         if (observerSampleCount_++ == observer_->getSampleRate()) {
355           observerSampleCount_ = 0;
356           observer_->loopSample(busy, idle);
357         }
358       }
359
360       VLOG(11) << "EventBase "  << this         << " did not timeout "
361         " loop time guess: "    << busy + idle  <<
362         " idle time: "          << idle         <<
363         " busy time: "          << busy         <<
364         " avgLoopTime: "        << avgLoopTime_.get() <<
365         " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
366         " maxLatency_: "        << maxLatency_ <<
367         " notificationQueueSize: " << getNotificationQueueSize() <<
368         " nothingHandledYet(): "<< nothingHandledYet();
369
370       // see if our average loop time has exceeded our limit
371       if ((maxLatency_ > 0) &&
372           (maxLatencyLoopTime_.get() > double(maxLatency_))) {
373         maxLatencyCob_();
374         // back off temporarily -- don't keep spamming maxLatencyCob_
375         // if we're only a bit over the limit
376         maxLatencyLoopTime_.dampen(0.9);
377       }
378
379       // Our loop run did real work; reset the idle timer
380       idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
381         std::chrono::steady_clock::now().time_since_epoch()).count();
382     } else {
383       VLOG(11) << "EventBase "  << this << " did not timeout "
384         " time measurement is disabled "
385         " nothingHandledYet(): "<< nothingHandledYet();
386     }
387
388     // If the event loop indicate that there were no more events, and
389     // we also didn't have any loop callbacks to run, there is nothing left to
390     // do.
391     if (res != 0 && !ranLoopCallbacks) {
392       // Since Notification Queue is marked 'internal' some events may not have
393       // run.  Run them manually if so, and continue looping.
394       //
395       if (getNotificationQueueSize() > 0) {
396         fnRunner_->handlerReady(0);
397       } else {
398         break;
399       }
400     }
401
402     if (enableTimeMeasurement_) {
403       VLOG(5) << "EventBase " << this << " loop time: " <<
404         getTimeDelta(&prev).count();
405     }
406
407     if (once) {
408       break;
409     }
410   }
411   // Reset stop_ so loop() can be called again
412   stop_ = false;
413
414   if (res < 0) {
415     LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
416     return false;
417   } else if (res == 1) {
418     VLOG(5) << "EventBase: ran out of events (exiting loop)!";
419   } else if (res > 1) {
420     LOG(ERROR) << "EventBase: unknown event loop result = " << res;
421     return false;
422   }
423
424   loopThread_.store({}, std::memory_order_release);
425
426   VLOG(5) << "EventBase(): Done with loop.";
427   return true;
428 }
429
430 void EventBase::loopForever() {
431   // Update the notification queue event to treat it as a normal (non-internal)
432   // event.  The notification queue event always remains installed, and the main
433   // loop won't exit with it installed.
434   fnRunner_->stopConsuming();
435   fnRunner_->startConsuming(this, queue_.get());
436
437   bool ret = loop();
438
439   // Restore the notification queue internal flag
440   fnRunner_->stopConsuming();
441   fnRunner_->startConsumingInternal(this, queue_.get());
442
443   if (!ret) {
444     folly::throwSystemError("error in EventBase::loopForever()");
445   }
446 }
447
448 bool EventBase::bumpHandlingTime() {
449   VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
450     " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
451   if(nothingHandledYet()) {
452     latestLoopCnt_ = nextLoopCnt_;
453     if (enableTimeMeasurement_) {
454       // set the time
455       startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
456         std::chrono::steady_clock::now().time_since_epoch()).count();
457
458       VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
459         " (loop) startWork_ " << startWork_;
460     }
461     return true;
462   }
463   return false;
464 }
465
466 void EventBase::terminateLoopSoon() {
467   VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
468
469   // Set stop to true, so the event loop will know to exit.
470   // TODO: We should really use an atomic operation here with a release
471   // barrier.
472   stop_ = true;
473
474   // Call event_base_loopbreak() so that libevent will exit the next time
475   // around the loop.
476   event_base_loopbreak(evb_);
477
478   // If terminateLoopSoon() is called from another thread,
479   // the EventBase thread might be stuck waiting for events.
480   // In this case, it won't wake up and notice that stop_ is set until it
481   // receives another event.  Send an empty frame to the notification queue
482   // so that the event loop will wake up even if there are no other events.
483   //
484   // We don't care about the return value of trySendFrame().  If it fails
485   // this likely means the EventBase already has lots of events waiting
486   // anyway.
487   try {
488     queue_->putMessage(nullptr);
489   } catch (...) {
490     // We don't care if putMessage() fails.  This likely means
491     // the EventBase already has lots of events waiting anyway.
492   }
493 }
494
495 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
496   DCHECK(isInEventBaseThread());
497   callback->cancelLoopCallback();
498   callback->context_ = RequestContext::saveContext();
499   if (runOnceCallbacks_ != nullptr && thisIteration) {
500     runOnceCallbacks_->push_back(*callback);
501   } else {
502     loopCallbacks_.push_back(*callback);
503   }
504 }
505
506 void EventBase::runInLoop(Func cob, bool thisIteration) {
507   DCHECK(isInEventBaseThread());
508   auto wrapper = new FunctionLoopCallback(std::move(cob));
509   wrapper->context_ = RequestContext::saveContext();
510   if (runOnceCallbacks_ != nullptr && thisIteration) {
511     runOnceCallbacks_->push_back(*wrapper);
512   } else {
513     loopCallbacks_.push_back(*wrapper);
514   }
515 }
516
517 void EventBase::runAfterDrain(Func cob) {
518   auto callback = new FunctionLoopCallback(std::move(cob));
519   std::lock_guard<std::mutex> lg(runAfterDrainCallbacksMutex_);
520   callback->cancelLoopCallback();
521   runAfterDrainCallbacks_.push_back(*callback);
522 }
523
524 void EventBase::runOnDestruction(LoopCallback* callback) {
525   std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
526   callback->cancelLoopCallback();
527   onDestructionCallbacks_.push_back(*callback);
528 }
529
530 void EventBase::runBeforeLoop(LoopCallback* callback) {
531   DCHECK(isInEventBaseThread());
532   callback->cancelLoopCallback();
533   runBeforeLoopCallbacks_.push_back(*callback);
534 }
535
536 bool EventBase::runInEventBaseThread(Func fn) {
537   // Send the message.
538   // It will be received by the FunctionRunner in the EventBase's thread.
539
540   // We try not to schedule nullptr callbacks
541   if (!fn) {
542     LOG(ERROR) << "EventBase " << this
543                << ": Scheduling nullptr callbacks is not allowed";
544     return false;
545   }
546
547   // Short-circuit if we are already in our event base
548   if (inRunningEventBaseThread()) {
549     runInLoop(std::move(fn));
550     return true;
551
552   }
553
554   try {
555     queue_->putMessage(std::move(fn));
556   } catch (const std::exception& ex) {
557     LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
558                << "for EventBase thread: " << ex.what();
559     return false;
560   }
561
562   return true;
563 }
564
565 bool EventBase::runInEventBaseThreadAndWait(Func fn) {
566   if (inRunningEventBaseThread()) {
567     LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
568                << "allowed";
569     return false;
570   }
571
572   bool ready = false;
573   std::mutex m;
574   std::condition_variable cv;
575   runInEventBaseThread([&] {
576       SCOPE_EXIT {
577         std::unique_lock<std::mutex> l(m);
578         ready = true;
579         cv.notify_one();
580         // We cannot release the lock before notify_one, because a spurious
581         // wakeup in the waiting thread may lead to cv and m going out of scope
582         // prematurely.
583       };
584       fn();
585   });
586   std::unique_lock<std::mutex> l(m);
587   cv.wait(l, [&] { return ready; });
588
589   return true;
590 }
591
592 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(Func fn) {
593   if (isInEventBaseThread()) {
594     fn();
595     return true;
596   } else {
597     return runInEventBaseThreadAndWait(std::move(fn));
598   }
599 }
600
601 void EventBase::runAfterDelay(
602     Func cob,
603     uint32_t milliseconds,
604     TimeoutManager::InternalEnum in) {
605   if (!tryRunAfterDelay(std::move(cob), milliseconds, in)) {
606     folly::throwSystemError(
607       "error in EventBase::runAfterDelay(), failed to schedule timeout");
608   }
609 }
610
611 bool EventBase::tryRunAfterDelay(
612     Func cob,
613     uint32_t milliseconds,
614     TimeoutManager::InternalEnum in) {
615   CobTimeout* timeout = new CobTimeout(this, std::move(cob), in);
616   if (!timeout->scheduleTimeout(milliseconds)) {
617     delete timeout;
618     return false;
619   }
620   pendingCobTimeouts_.push_back(*timeout);
621   return true;
622 }
623
624 bool EventBase::runLoopCallbacks(bool setContext) {
625   if (!loopCallbacks_.empty()) {
626     bumpHandlingTime();
627     // Swap the loopCallbacks_ list with a temporary list on our stack.
628     // This way we will only run callbacks scheduled at the time
629     // runLoopCallbacks() was invoked.
630     //
631     // If any of these callbacks in turn call runInLoop() to schedule more
632     // callbacks, those new callbacks won't be run until the next iteration
633     // around the event loop.  This prevents runInLoop() callbacks from being
634     // able to start file descriptor and timeout based events.
635     LoopCallbackList currentCallbacks;
636     currentCallbacks.swap(loopCallbacks_);
637     runOnceCallbacks_ = &currentCallbacks;
638
639     while (!currentCallbacks.empty()) {
640       LoopCallback* callback = &currentCallbacks.front();
641       currentCallbacks.pop_front();
642       if (setContext) {
643         RequestContext::setContext(callback->context_);
644       }
645       callback->runLoopCallback();
646     }
647
648     runOnceCallbacks_ = nullptr;
649     return true;
650   }
651   return false;
652 }
653
654 void EventBase::initNotificationQueue() {
655   // Infinite size queue
656   queue_.reset(new NotificationQueue<Func>());
657
658   // We allocate fnRunner_ separately, rather than declaring it directly
659   // as a member of EventBase solely so that we don't need to include
660   // NotificationQueue.h from EventBase.h
661   fnRunner_.reset(new FunctionRunner());
662
663   // Mark this as an internal event, so event_base_loop() will return if
664   // there are no other events besides this one installed.
665   //
666   // Most callers don't care about the internal notification queue used by
667   // EventBase.  The queue is always installed, so if we did count the queue as
668   // an active event, loop() would never exit with no more events to process.
669   // Users can use loopForever() if they do care about the notification queue.
670   // (This is useful for EventBase threads that do nothing but process
671   // runInEventBaseThread() notifications.)
672   fnRunner_->startConsumingInternal(this, queue_.get());
673 }
674
675 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
676   expCoeff_ = -1.0/timeInterval;
677   VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
678 }
679
680 void EventBase::SmoothLoopTime::reset(double value) {
681   value_ = value;
682 }
683
684 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
685     /*
686      * Position at which the busy sample is considered to be taken.
687      * (Allows to quickly skew our average without editing much code)
688      */
689     enum BusySamplePosition {
690       RIGHT = 0,  // busy sample placed at the end of the iteration
691       CENTER = 1, // busy sample placed at the middle point of the iteration
692       LEFT = 2,   // busy sample placed at the beginning of the iteration
693     };
694
695   // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
696   // and D676020 for more info on this calculation.
697   VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
698               " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
699               " busy " << busy << " " << __PRETTY_FUNCTION__;
700   idle += oldBusyLeftover_ + busy;
701   oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
702   idle -= oldBusyLeftover_;
703
704   double coeff = exp(idle * expCoeff_);
705   value_ *= coeff;
706   value_ += (1.0 - coeff) * busy;
707 }
708
709 bool EventBase::nothingHandledYet() {
710   VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
711   return (nextLoopCnt_ != latestLoopCnt_);
712 }
713
714 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
715                                       InternalEnum internal) {
716
717   struct event* ev = obj->getEvent();
718   assert(ev->ev_base == nullptr);
719
720   event_base_set(getLibeventBase(), ev);
721   if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
722     // Set the EVLIST_INTERNAL flag
723     event_ref_flags(ev) |= EVLIST_INTERNAL;
724   }
725 }
726
727 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
728   cancelTimeout(obj);
729   struct event* ev = obj->getEvent();
730   ev->ev_base = nullptr;
731 }
732
733 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
734                                  TimeoutManager::timeout_type timeout) {
735   assert(isInEventBaseThread());
736   // Set up the timeval and add the event
737   struct timeval tv;
738   tv.tv_sec = timeout.count() / 1000LL;
739   tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
740
741   struct event* ev = obj->getEvent();
742   if (event_add(ev, &tv) < 0) {
743     LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
744     return false;
745   }
746
747   return true;
748 }
749
750 void EventBase::cancelTimeout(AsyncTimeout* obj) {
751   assert(isInEventBaseThread());
752   struct event* ev = obj->getEvent();
753   if (EventUtil::isEventRegistered(ev)) {
754     event_del(ev);
755   }
756 }
757
758 void EventBase::setName(const std::string& name) {
759   assert(isInEventBaseThread());
760   name_ = name;
761
762   if (isRunning()) {
763     setThreadName(loopThread_.load(std::memory_order_relaxed),
764                   name_);
765   }
766 }
767
768 const std::string& EventBase::getName() {
769   assert(isInEventBaseThread());
770   return name_;
771 }
772
773 const char* EventBase::getLibeventVersion() { return event_get_version(); }
774 const char* EventBase::getLibeventMethod() { return event_get_method(); }
775
776 } // folly