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