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