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