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