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