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