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