68a42f58ef2306cbfda8322abab5ce27a34ce363
[folly.git] / folly / io / async / EventBase.cpp
1 /*
2  * Copyright 2014 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/io/async/NotificationQueue.h"
24
25 #include <boost/static_assert.hpp>
26 #include <fcntl.h>
27 #include <pthread.h>
28 #include <unistd.h>
29
30 namespace {
31
32 using folly::Cob;
33 using folly::EventBase;
34
35 template <typename Callback>
36 class FunctionLoopCallback : public EventBase::LoopCallback {
37  public:
38   explicit FunctionLoopCallback(Cob&& function)
39       : function_(std::move(function)) {}
40
41   explicit FunctionLoopCallback(const Cob& function)
42       : function_(function) {}
43
44   virtual void runLoopCallback() noexcept {
45     function_();
46     delete this;
47   }
48
49  private:
50   Callback function_;
51 };
52
53 }
54
55 namespace folly {
56
57 const int kNoFD = -1;
58
59 /*
60  * EventBase::FunctionRunner
61  */
62
63 class EventBase::FunctionRunner
64     : public NotificationQueue<std::pair<void (*)(void*), void*>>::Consumer {
65  public:
66   void messageAvailable(std::pair<void (*)(void*), void*>&& msg) {
67
68     // In libevent2, internal events do not break the loop.
69     // Most users would expect loop(), followed by runInEventBaseThread(),
70     // to break the loop and check if it should exit or not.
71     // To have similar bejaviour to libevent1.4, tell the loop to break here.
72     // Note that loop() may still continue to loop, but it will also check the
73     // stop_ flag as well as runInLoop callbacks, etc.
74     event_base_loopbreak(getEventBase()->evb_);
75
76     if (msg.first == nullptr && msg.second == nullptr) {
77       // terminateLoopSoon() sends a null message just to
78       // wake up the loop.  We can ignore these messages.
79       return;
80     }
81
82     // If function is nullptr, just log and move on
83     if (!msg.first) {
84       LOG(ERROR) << "nullptr callback registered to be run in "
85                  << "event base thread";
86       return;
87     }
88
89     // The function should never throw an exception, because we have no
90     // way of knowing what sort of error handling to perform.
91     //
92     // If it does throw, log a message and abort the program.
93     try {
94       msg.first(msg.second);
95     } catch (const std::exception& ex) {
96       LOG(ERROR) << "runInEventBaseThread() function threw a "
97                  << typeid(ex).name() << " exception: " << ex.what();
98       abort();
99     } catch (...) {
100       LOG(ERROR) << "runInEventBaseThread() function threw an exception";
101       abort();
102     }
103   }
104 };
105
106 /*
107  * EventBase::CobTimeout methods
108  */
109
110 void EventBase::CobTimeout::timeoutExpired() noexcept {
111   // For now, we just swallow any exceptions that the callback threw.
112   try {
113     cob_();
114   } catch (const std::exception& ex) {
115     LOG(ERROR) << "EventBase::runAfterDelay() callback threw "
116                << typeid(ex).name() << " exception: " << ex.what();
117   } catch (...) {
118     LOG(ERROR) << "EventBase::runAfterDelay() callback threw non-exception "
119                << "type";
120   }
121
122   // The CobTimeout object was allocated on the heap by runAfterDelay(),
123   // so delete it now that the it has fired.
124   delete this;
125 }
126
127 /*
128  * EventBase methods
129  */
130
131 EventBase::EventBase()
132   : runOnceCallbacks_(nullptr)
133   , stop_(false)
134   , loopThread_(0)
135   , evb_(static_cast<event_base*>(event_init()))
136   , queue_(nullptr)
137   , fnRunner_(nullptr)
138   , maxLatency_(0)
139   , avgLoopTime_(2000000)
140   , maxLatencyLoopTime_(avgLoopTime_)
141   , nextLoopCnt_(-40)       // Early wrap-around so bugs will manifest soon
142   , latestLoopCnt_(nextLoopCnt_)
143   , startWork_(0)
144   , observer_(nullptr)
145   , observerSampleCount_(0) {
146   VLOG(5) << "EventBase(): Created.";
147   initNotificationQueue();
148   RequestContext::getStaticContext();
149 }
150
151 // takes ownership of the event_base
152 EventBase::EventBase(event_base* evb)
153   : runOnceCallbacks_(nullptr)
154   , stop_(false)
155   , loopThread_(0)
156   , evb_(evb)
157   , queue_(nullptr)
158   , fnRunner_(nullptr)
159   , maxLatency_(0)
160   , avgLoopTime_(2000000)
161   , maxLatencyLoopTime_(avgLoopTime_)
162   , nextLoopCnt_(-40)       // Early wrap-around so bugs will manifest soon
163   , latestLoopCnt_(nextLoopCnt_)
164   , startWork_(0)
165   , observer_(nullptr)
166   , observerSampleCount_(0) {
167   initNotificationQueue();
168   RequestContext::getStaticContext();
169 }
170
171 EventBase::~EventBase() {
172   // Delete any unfired CobTimeout objects, so that we don't leak memory
173   // (Note that we don't fire them.  The caller is responsible for cleaning up
174   // its own data structures if it destroys the EventBase with unfired events
175   // remaining.)
176   while (!pendingCobTimeouts_.empty()) {
177     CobTimeout* timeout = &pendingCobTimeouts_.front();
178     delete timeout;
179   }
180
181   (void) runLoopCallbacks(false);
182
183   // Stop consumer before deleting NotificationQueue
184   fnRunner_->stopConsuming();
185   event_base_free(evb_);
186   VLOG(5) << "EventBase(): Destroyed.";
187 }
188
189 int EventBase::getNotificationQueueSize() const {
190   return queue_->size();
191 }
192
193 // Set smoothing coefficient for loop load average; input is # of milliseconds
194 // for exp(-1) decay.
195 void EventBase::setLoadAvgMsec(uint32_t ms) {
196   uint64_t us = 1000 * ms;
197   if (ms > 0) {
198     maxLatencyLoopTime_.setTimeInterval(us);
199     avgLoopTime_.setTimeInterval(us);
200   } else {
201     LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
202   }
203 }
204
205 void EventBase::resetLoadAvg(double value) {
206   avgLoopTime_.reset(value);
207   maxLatencyLoopTime_.reset(value);
208 }
209
210 static std::chrono::milliseconds
211 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
212   auto result = std::chrono::steady_clock::now() - *prev;
213   *prev = std::chrono::steady_clock::now();
214
215   return std::chrono::duration_cast<std::chrono::milliseconds>(result);
216 }
217
218 void EventBase::waitUntilRunning() {
219   while (!isRunning()) {
220     sched_yield();
221   }
222 }
223
224 // enters the event_base loop -- will only exit when forced to
225 bool EventBase::loop() {
226   VLOG(5) << "EventBase(): Starting loop.";
227   int res = 0;
228   bool ranLoopCallbacks;
229   int nonBlocking;
230
231   loopThread_.store(pthread_self(), std::memory_order_release);
232
233 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
234   if (!name_.empty()) {
235     pthread_setname_np(pthread_self(), name_.c_str());
236   }
237 #endif
238
239   auto prev = std::chrono::steady_clock::now();
240   int64_t idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
241     std::chrono::steady_clock::now().time_since_epoch()).count();
242
243   // TODO: Read stop_ atomically with an acquire barrier.
244   while (!stop_) {
245     ++nextLoopCnt_;
246
247     // nobody can add loop callbacks from within this thread if
248     // we don't have to handle anything to start with...
249     nonBlocking = (loopCallbacks_.empty() ? 0 : EVLOOP_NONBLOCK);
250     res = event_base_loop(evb_, EVLOOP_ONCE | nonBlocking);
251     ranLoopCallbacks = runLoopCallbacks();
252
253     int64_t busy = std::chrono::duration_cast<std::chrono::microseconds>(
254       std::chrono::steady_clock::now().time_since_epoch()).count() - startWork_;
255     int64_t idle = startWork_ - idleStart;
256
257     avgLoopTime_.addSample(idle, busy);
258     maxLatencyLoopTime_.addSample(idle, busy);
259
260     if (observer_) {
261       if (observerSampleCount_++ == observer_->getSampleRate()) {
262         observerSampleCount_ = 0;
263         observer_->loopSample(busy, idle);
264       }
265     }
266
267     VLOG(11) << "EventBase " << this         << " did not timeout "
268      " loop time guess: "    << busy + idle  <<
269      " idle time: "          << idle         <<
270      " busy time: "          << busy         <<
271      " avgLoopTime: "        << avgLoopTime_.get() <<
272      " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
273      " maxLatency_: "        << maxLatency_ <<
274      " nothingHandledYet(): "<< nothingHandledYet();
275
276     // see if our average loop time has exceeded our limit
277     if ((maxLatency_ > 0) &&
278         (maxLatencyLoopTime_.get() > double(maxLatency_))) {
279       maxLatencyCob_();
280       // back off temporarily -- don't keep spamming maxLatencyCob_
281       // if we're only a bit over the limit
282       maxLatencyLoopTime_.dampen(0.9);
283     }
284
285     // Our loop run did real work; reset the idle timer
286     idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
287       std::chrono::steady_clock::now().time_since_epoch()).count();
288
289     // If the event loop indicate that there were no more events, and
290     // we also didn't have any loop callbacks to run, there is nothing left to
291     // do.
292     if (res != 0 && !ranLoopCallbacks) {
293       // Since Notification Queue is marked 'internal' some events may not have
294       // run.  Run them manually if so, and continue looping.
295       //
296       if (getNotificationQueueSize() > 0) {
297         fnRunner_->handlerReady(0);
298       } else {
299         break;
300       }
301     }
302
303     VLOG(5) << "EventBase " << this << " loop time: " <<
304       getTimeDelta(&prev).count();
305   }
306   // Reset stop_ so loop() can be called again
307   stop_ = false;
308
309   if (res < 0) {
310     LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
311     return false;
312   } else if (res == 1) {
313     VLOG(5) << "EventBase: ran out of events (exiting loop)!";
314   } else if (res > 1) {
315     LOG(ERROR) << "EventBase: unknown event loop result = " << res;
316     return false;
317   }
318
319   loopThread_.store(0, std::memory_order_release);
320
321   VLOG(5) << "EventBase(): Done with loop.";
322   return true;
323 }
324
325 void EventBase::loopForever() {
326   // Update the notification queue event to treat it as a normal (non-internal)
327   // event.  The notification queue event always remains installed, and the main
328   // loop won't exit with it installed.
329   fnRunner_->stopConsuming();
330   fnRunner_->startConsuming(this, queue_.get());
331
332   bool ret = loop();
333
334   // Restore the notification queue internal flag
335   fnRunner_->stopConsuming();
336   fnRunner_->startConsumingInternal(this, queue_.get());
337
338   if (!ret) {
339     folly::throwSystemError("error in EventBase::loopForever()");
340   }
341 }
342
343 bool EventBase::bumpHandlingTime() {
344   VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
345     " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
346   if(nothingHandledYet()) {
347     latestLoopCnt_ = nextLoopCnt_;
348     // set the time
349     startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
350       std::chrono::steady_clock::now().time_since_epoch()).count();
351
352     VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
353       " (loop) startWork_ " << startWork_;
354     return true;
355   }
356   return false;
357 }
358
359 void EventBase::terminateLoopSoon() {
360   VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
361
362   if (!isRunning()) {
363     return;
364   }
365
366   // Set stop to true, so the event loop will know to exit.
367   // TODO: We should really use an atomic operation here with a release
368   // barrier.
369   stop_ = true;
370
371   // Call event_base_loopbreak() so that libevent will exit the next time
372   // around the loop.
373   event_base_loopbreak(evb_);
374
375   // If terminateLoopSoon() is called from another thread,
376   // the EventBase thread might be stuck waiting for events.
377   // In this case, it won't wake up and notice that stop_ is set until it
378   // receives another event.  Send an empty frame to the notification queue
379   // so that the event loop will wake up even if there are no other events.
380   //
381   // We don't care about the return value of trySendFrame().  If it fails
382   // this likely means the EventBase already has lots of events waiting
383   // anyway.
384   try {
385     queue_->putMessage(std::make_pair(nullptr, nullptr));
386   } catch (...) {
387     // We don't care if putMessage() fails.  This likely means
388     // the EventBase already has lots of events waiting anyway.
389   }
390 }
391
392 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
393   DCHECK(isInEventBaseThread());
394   callback->cancelLoopCallback();
395   callback->context_ = RequestContext::saveContext();
396   if (runOnceCallbacks_ != nullptr && thisIteration) {
397     runOnceCallbacks_->push_back(*callback);
398   } else {
399     loopCallbacks_.push_back(*callback);
400   }
401 }
402
403 void EventBase::runInLoop(const Cob& cob, bool thisIteration) {
404   DCHECK(isInEventBaseThread());
405   auto wrapper = new FunctionLoopCallback<Cob>(cob);
406   wrapper->context_ = RequestContext::saveContext();
407   if (runOnceCallbacks_ != nullptr && thisIteration) {
408     runOnceCallbacks_->push_back(*wrapper);
409   } else {
410     loopCallbacks_.push_back(*wrapper);
411   }
412 }
413
414 void EventBase::runInLoop(Cob&& cob, bool thisIteration) {
415   DCHECK(isInEventBaseThread());
416   auto wrapper = new FunctionLoopCallback<Cob>(std::move(cob));
417   wrapper->context_ = RequestContext::saveContext();
418   if (runOnceCallbacks_ != nullptr && thisIteration) {
419     runOnceCallbacks_->push_back(*wrapper);
420   } else {
421     loopCallbacks_.push_back(*wrapper);
422   }
423 }
424
425 bool EventBase::runInEventBaseThread(void (*fn)(void*), void* arg) {
426   // Send the message.
427   // It will be received by the FunctionRunner in the EventBase's thread.
428
429   // We try not to schedule nullptr callbacks
430   if (!fn) {
431     LOG(ERROR) << "EventBase " << this
432                << ": Scheduling nullptr callbacks is not allowed";
433     return false;
434   }
435
436   // Short-circuit if we are already in our event base
437   if (inRunningEventBaseThread()) {
438     runInLoop(new RunInLoopCallback(fn, arg));
439     return true;
440
441   }
442
443   try {
444     queue_->putMessage(std::make_pair(fn, arg));
445   } catch (const std::exception& ex) {
446     LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
447                << fn << "for EventBase thread: " << ex.what();
448     return false;
449   }
450
451   return true;
452 }
453
454 bool EventBase::runInEventBaseThread(const Cob& fn) {
455   // Short-circuit if we are already in our event base
456   if (inRunningEventBaseThread()) {
457     runInLoop(fn);
458     return true;
459   }
460
461   Cob* fnCopy;
462   // Allocate a copy of the function so we can pass it to the other thread
463   // The other thread will delete this copy once the function has been run
464   try {
465     fnCopy = new Cob(fn);
466   } catch (const std::bad_alloc& ex) {
467     LOG(ERROR) << "failed to allocate tr::function copy "
468                << "for runInEventBaseThread()";
469     return false;
470   }
471
472   if (!runInEventBaseThread(&EventBase::runFunctionPtr, fnCopy)) {
473     delete fnCopy;
474     return false;
475   }
476
477   return true;
478 }
479
480 bool EventBase::runAfterDelay(const Cob& cob,
481                                int milliseconds,
482                                TimeoutManager::InternalEnum in) {
483   CobTimeout* timeout = new CobTimeout(this, cob, in);
484   if (!timeout->scheduleTimeout(milliseconds)) {
485     delete timeout;
486     return false;
487   }
488
489   pendingCobTimeouts_.push_back(*timeout);
490   return true;
491 }
492
493 bool EventBase::runLoopCallbacks(bool setContext) {
494   if (!loopCallbacks_.empty()) {
495     bumpHandlingTime();
496     // Swap the loopCallbacks_ list with a temporary list on our stack.
497     // This way we will only run callbacks scheduled at the time
498     // runLoopCallbacks() was invoked.
499     //
500     // If any of these callbacks in turn call runInLoop() to schedule more
501     // callbacks, those new callbacks won't be run until the next iteration
502     // around the event loop.  This prevents runInLoop() callbacks from being
503     // able to start file descriptor and timeout based events.
504     LoopCallbackList currentCallbacks;
505     currentCallbacks.swap(loopCallbacks_);
506     runOnceCallbacks_ = &currentCallbacks;
507
508     while (!currentCallbacks.empty()) {
509       LoopCallback* callback = &currentCallbacks.front();
510       currentCallbacks.pop_front();
511       if (setContext) {
512         RequestContext::setContext(callback->context_);
513       }
514       callback->runLoopCallback();
515     }
516
517     runOnceCallbacks_ = nullptr;
518     return true;
519   }
520   return false;
521 }
522
523 void EventBase::initNotificationQueue() {
524   // Infinite size queue
525   queue_.reset(new NotificationQueue<std::pair<void (*)(void*), void*>>());
526
527   // We allocate fnRunner_ separately, rather than declaring it directly
528   // as a member of EventBase solely so that we don't need to include
529   // NotificationQueue.h from EventBase.h
530   fnRunner_.reset(new FunctionRunner());
531
532   // Mark this as an internal event, so event_base_loop() will return if
533   // there are no other events besides this one installed.
534   //
535   // Most callers don't care about the internal notification queue used by
536   // EventBase.  The queue is always installed, so if we did count the queue as
537   // an active event, loop() would never exit with no more events to process.
538   // Users can use loopForever() if they do care about the notification queue.
539   // (This is useful for EventBase threads that do nothing but process
540   // runInEventBaseThread() notifications.)
541   fnRunner_->startConsumingInternal(this, queue_.get());
542 }
543
544 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
545   expCoeff_ = -1.0/timeInterval;
546   VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
547 }
548
549 void EventBase::SmoothLoopTime::reset(double value) {
550   value_ = value;
551 }
552
553 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
554     /*
555      * Position at which the busy sample is considered to be taken.
556      * (Allows to quickly skew our average without editing much code)
557      */
558     enum BusySamplePosition {
559       RIGHT = 0,  // busy sample placed at the end of the iteration
560       CENTER = 1, // busy sample placed at the middle point of the iteration
561       LEFT = 2,   // busy sample placed at the beginning of the iteration
562     };
563
564   VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
565               " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
566               " busy " << busy << " " << __PRETTY_FUNCTION__;
567   idle += oldBusyLeftover_ + busy;
568   oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
569   idle -= oldBusyLeftover_;
570
571   double coeff = exp(idle * expCoeff_);
572   value_ *= coeff;
573   value_ += (1.0 - coeff) * busy;
574 }
575
576 bool EventBase::nothingHandledYet() {
577   VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
578   return (nextLoopCnt_ != latestLoopCnt_);
579 }
580
581 /* static */
582 void EventBase::runFunctionPtr(Cob* fn) {
583   // The function should never throw an exception, because we have no
584   // way of knowing what sort of error handling to perform.
585   //
586   // If it does throw, log a message and abort the program.
587   try {
588     (*fn)();
589   } catch (const std::exception &ex) {
590     LOG(ERROR) << "runInEventBaseThread() std::function threw a "
591                << typeid(ex).name() << " exception: " << ex.what();
592     abort();
593   } catch (...) {
594     LOG(ERROR) << "runInEventBaseThread() std::function threw an exception";
595     abort();
596   }
597
598   // The function object was allocated by runInEventBaseThread().
599   // Delete it once it has been run.
600   delete fn;
601 }
602
603 EventBase::RunInLoopCallback::RunInLoopCallback(void (*fn)(void*), void* arg)
604     : fn_(fn)
605     , arg_(arg) {}
606
607 void EventBase::RunInLoopCallback::runLoopCallback() noexcept {
608   fn_(arg_);
609   delete this;
610 }
611
612 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
613                                       InternalEnum internal) {
614
615   struct event* ev = obj->getEvent();
616   assert(ev->ev_base == nullptr);
617
618   event_base_set(getLibeventBase(), ev);
619   if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
620     // Set the EVLIST_INTERNAL flag
621     ev->ev_flags |= EVLIST_INTERNAL;
622   }
623 }
624
625 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
626   cancelTimeout(obj);
627   struct event* ev = obj->getEvent();
628   ev->ev_base = nullptr;
629 }
630
631 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
632                                  std::chrono::milliseconds timeout) {
633   assert(isInEventBaseThread());
634   // Set up the timeval and add the event
635   struct timeval tv;
636   tv.tv_sec = timeout.count() / 1000LL;
637   tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
638
639   struct event* ev = obj->getEvent();
640   if (event_add(ev, &tv) < 0) {
641     LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
642     return false;
643   }
644
645   return true;
646 }
647
648 void EventBase::cancelTimeout(AsyncTimeout* obj) {
649   assert(isInEventBaseThread());
650   struct event* ev = obj->getEvent();
651   if (EventUtil::isEventRegistered(ev)) {
652     event_del(ev);
653   }
654 }
655
656 void EventBase::setName(const std::string& name) {
657   assert(isInEventBaseThread());
658   name_ = name;
659 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
660   if (isRunning()) {
661     pthread_setname_np(loopThread_.load(std::memory_order_relaxed),
662                        name_.c_str());
663   }
664 #endif
665 }
666
667 const std::string& EventBase::getName() {
668   assert(isInEventBaseThread());
669   return name_;
670 }
671
672 } // folly