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