QueueBenchmark set max read at once
[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 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
194   fnRunner_->setMaxReadAtOnce(maxAtOnce);
195 }
196
197 // Set smoothing coefficient for loop load average; input is # of milliseconds
198 // for exp(-1) decay.
199 void EventBase::setLoadAvgMsec(uint32_t ms) {
200   uint64_t us = 1000 * ms;
201   if (ms > 0) {
202     maxLatencyLoopTime_.setTimeInterval(us);
203     avgLoopTime_.setTimeInterval(us);
204   } else {
205     LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
206   }
207 }
208
209 void EventBase::resetLoadAvg(double value) {
210   avgLoopTime_.reset(value);
211   maxLatencyLoopTime_.reset(value);
212 }
213
214 static std::chrono::milliseconds
215 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
216   auto result = std::chrono::steady_clock::now() - *prev;
217   *prev = std::chrono::steady_clock::now();
218
219   return std::chrono::duration_cast<std::chrono::milliseconds>(result);
220 }
221
222 void EventBase::waitUntilRunning() {
223   while (!isRunning()) {
224     sched_yield();
225   }
226 }
227
228 // enters the event_base loop -- will only exit when forced to
229 bool EventBase::loop() {
230   return loopBody();
231 }
232
233 bool EventBase::loopOnce() {
234   return loopBody(true);
235 }
236
237 bool EventBase::loopBody(bool once) {
238   VLOG(5) << "EventBase(): Starting loop.";
239   int res = 0;
240   bool ranLoopCallbacks;
241   int nonBlocking;
242
243   loopThread_.store(pthread_self(), std::memory_order_release);
244
245 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
246   if (!name_.empty()) {
247     pthread_setname_np(pthread_self(), name_.c_str());
248   }
249 #endif
250
251   auto prev = std::chrono::steady_clock::now();
252   int64_t idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
253     std::chrono::steady_clock::now().time_since_epoch()).count();
254
255   // TODO: Read stop_ atomically with an acquire barrier.
256   while (!stop_) {
257     ++nextLoopCnt_;
258
259     // nobody can add loop callbacks from within this thread if
260     // we don't have to handle anything to start with...
261     nonBlocking = (loopCallbacks_.empty() ? 0 : EVLOOP_NONBLOCK);
262     res = event_base_loop(evb_, EVLOOP_ONCE | nonBlocking);
263     ranLoopCallbacks = runLoopCallbacks();
264
265     int64_t busy = std::chrono::duration_cast<std::chrono::microseconds>(
266       std::chrono::steady_clock::now().time_since_epoch()).count() - startWork_;
267     int64_t idle = startWork_ - idleStart;
268
269     avgLoopTime_.addSample(idle, busy);
270     maxLatencyLoopTime_.addSample(idle, busy);
271
272     if (observer_) {
273       if (observerSampleCount_++ == observer_->getSampleRate()) {
274         observerSampleCount_ = 0;
275         observer_->loopSample(busy, idle);
276       }
277     }
278
279     VLOG(11) << "EventBase " << this         << " did not timeout "
280      " loop time guess: "    << busy + idle  <<
281      " idle time: "          << idle         <<
282      " busy time: "          << busy         <<
283      " avgLoopTime: "        << avgLoopTime_.get() <<
284      " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
285      " maxLatency_: "        << maxLatency_ <<
286      " nothingHandledYet(): "<< nothingHandledYet();
287
288     // see if our average loop time has exceeded our limit
289     if ((maxLatency_ > 0) &&
290         (maxLatencyLoopTime_.get() > double(maxLatency_))) {
291       maxLatencyCob_();
292       // back off temporarily -- don't keep spamming maxLatencyCob_
293       // if we're only a bit over the limit
294       maxLatencyLoopTime_.dampen(0.9);
295     }
296
297     // Our loop run did real work; reset the idle timer
298     idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
299       std::chrono::steady_clock::now().time_since_epoch()).count();
300
301     // If the event loop indicate that there were no more events, and
302     // we also didn't have any loop callbacks to run, there is nothing left to
303     // do.
304     if (res != 0 && !ranLoopCallbacks) {
305       // Since Notification Queue is marked 'internal' some events may not have
306       // run.  Run them manually if so, and continue looping.
307       //
308       if (getNotificationQueueSize() > 0) {
309         fnRunner_->handlerReady(0);
310       } else {
311         break;
312       }
313     }
314
315     VLOG(5) << "EventBase " << this << " loop time: " <<
316       getTimeDelta(&prev).count();
317
318     if (once) {
319       break;
320     }
321   }
322   // Reset stop_ so loop() can be called again
323   stop_ = false;
324
325   if (res < 0) {
326     LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
327     return false;
328   } else if (res == 1) {
329     VLOG(5) << "EventBase: ran out of events (exiting loop)!";
330   } else if (res > 1) {
331     LOG(ERROR) << "EventBase: unknown event loop result = " << res;
332     return false;
333   }
334
335   loopThread_.store(0, std::memory_order_release);
336
337   VLOG(5) << "EventBase(): Done with loop.";
338   return true;
339 }
340
341 void EventBase::loopForever() {
342   // Update the notification queue event to treat it as a normal (non-internal)
343   // event.  The notification queue event always remains installed, and the main
344   // loop won't exit with it installed.
345   fnRunner_->stopConsuming();
346   fnRunner_->startConsuming(this, queue_.get());
347
348   bool ret = loop();
349
350   // Restore the notification queue internal flag
351   fnRunner_->stopConsuming();
352   fnRunner_->startConsumingInternal(this, queue_.get());
353
354   if (!ret) {
355     folly::throwSystemError("error in EventBase::loopForever()");
356   }
357 }
358
359 bool EventBase::bumpHandlingTime() {
360   VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
361     " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
362   if(nothingHandledYet()) {
363     latestLoopCnt_ = nextLoopCnt_;
364     // set the time
365     startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
366       std::chrono::steady_clock::now().time_since_epoch()).count();
367
368     VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
369       " (loop) startWork_ " << startWork_;
370     return true;
371   }
372   return false;
373 }
374
375 void EventBase::terminateLoopSoon() {
376   VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
377
378   if (!isRunning()) {
379     return;
380   }
381
382   // Set stop to true, so the event loop will know to exit.
383   // TODO: We should really use an atomic operation here with a release
384   // barrier.
385   stop_ = true;
386
387   // Call event_base_loopbreak() so that libevent will exit the next time
388   // around the loop.
389   event_base_loopbreak(evb_);
390
391   // If terminateLoopSoon() is called from another thread,
392   // the EventBase thread might be stuck waiting for events.
393   // In this case, it won't wake up and notice that stop_ is set until it
394   // receives another event.  Send an empty frame to the notification queue
395   // so that the event loop will wake up even if there are no other events.
396   //
397   // We don't care about the return value of trySendFrame().  If it fails
398   // this likely means the EventBase already has lots of events waiting
399   // anyway.
400   try {
401     queue_->putMessage(std::make_pair(nullptr, nullptr));
402   } catch (...) {
403     // We don't care if putMessage() fails.  This likely means
404     // the EventBase already has lots of events waiting anyway.
405   }
406 }
407
408 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
409   DCHECK(isInEventBaseThread());
410   callback->cancelLoopCallback();
411   callback->context_ = RequestContext::saveContext();
412   if (runOnceCallbacks_ != nullptr && thisIteration) {
413     runOnceCallbacks_->push_back(*callback);
414   } else {
415     loopCallbacks_.push_back(*callback);
416   }
417 }
418
419 void EventBase::runInLoop(const Cob& cob, bool thisIteration) {
420   DCHECK(isInEventBaseThread());
421   auto wrapper = new FunctionLoopCallback<Cob>(cob);
422   wrapper->context_ = RequestContext::saveContext();
423   if (runOnceCallbacks_ != nullptr && thisIteration) {
424     runOnceCallbacks_->push_back(*wrapper);
425   } else {
426     loopCallbacks_.push_back(*wrapper);
427   }
428 }
429
430 void EventBase::runInLoop(Cob&& cob, bool thisIteration) {
431   DCHECK(isInEventBaseThread());
432   auto wrapper = new FunctionLoopCallback<Cob>(std::move(cob));
433   wrapper->context_ = RequestContext::saveContext();
434   if (runOnceCallbacks_ != nullptr && thisIteration) {
435     runOnceCallbacks_->push_back(*wrapper);
436   } else {
437     loopCallbacks_.push_back(*wrapper);
438   }
439 }
440
441 bool EventBase::runInEventBaseThread(void (*fn)(void*), void* arg) {
442   // Send the message.
443   // It will be received by the FunctionRunner in the EventBase's thread.
444
445   // We try not to schedule nullptr callbacks
446   if (!fn) {
447     LOG(ERROR) << "EventBase " << this
448                << ": Scheduling nullptr callbacks is not allowed";
449     return false;
450   }
451
452   // Short-circuit if we are already in our event base
453   if (inRunningEventBaseThread()) {
454     runInLoop(new RunInLoopCallback(fn, arg));
455     return true;
456
457   }
458
459   try {
460     queue_->putMessage(std::make_pair(fn, arg));
461   } catch (const std::exception& ex) {
462     LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
463                << fn << "for EventBase thread: " << ex.what();
464     return false;
465   }
466
467   return true;
468 }
469
470 bool EventBase::runInEventBaseThread(const Cob& fn) {
471   // Short-circuit if we are already in our event base
472   if (inRunningEventBaseThread()) {
473     runInLoop(fn);
474     return true;
475   }
476
477   Cob* fnCopy;
478   // Allocate a copy of the function so we can pass it to the other thread
479   // The other thread will delete this copy once the function has been run
480   try {
481     fnCopy = new Cob(fn);
482   } catch (const std::bad_alloc& ex) {
483     LOG(ERROR) << "failed to allocate tr::function copy "
484                << "for runInEventBaseThread()";
485     return false;
486   }
487
488   if (!runInEventBaseThread(&EventBase::runFunctionPtr, fnCopy)) {
489     delete fnCopy;
490     return false;
491   }
492
493   return true;
494 }
495
496 bool EventBase::runAfterDelay(const Cob& cob,
497                                int milliseconds,
498                                TimeoutManager::InternalEnum in) {
499   CobTimeout* timeout = new CobTimeout(this, cob, in);
500   if (!timeout->scheduleTimeout(milliseconds)) {
501     delete timeout;
502     return false;
503   }
504
505   pendingCobTimeouts_.push_back(*timeout);
506   return true;
507 }
508
509 bool EventBase::runLoopCallbacks(bool setContext) {
510   if (!loopCallbacks_.empty()) {
511     bumpHandlingTime();
512     // Swap the loopCallbacks_ list with a temporary list on our stack.
513     // This way we will only run callbacks scheduled at the time
514     // runLoopCallbacks() was invoked.
515     //
516     // If any of these callbacks in turn call runInLoop() to schedule more
517     // callbacks, those new callbacks won't be run until the next iteration
518     // around the event loop.  This prevents runInLoop() callbacks from being
519     // able to start file descriptor and timeout based events.
520     LoopCallbackList currentCallbacks;
521     currentCallbacks.swap(loopCallbacks_);
522     runOnceCallbacks_ = &currentCallbacks;
523
524     while (!currentCallbacks.empty()) {
525       LoopCallback* callback = &currentCallbacks.front();
526       currentCallbacks.pop_front();
527       if (setContext) {
528         RequestContext::setContext(callback->context_);
529       }
530       callback->runLoopCallback();
531     }
532
533     runOnceCallbacks_ = nullptr;
534     return true;
535   }
536   return false;
537 }
538
539 void EventBase::initNotificationQueue() {
540   // Infinite size queue
541   queue_.reset(new NotificationQueue<std::pair<void (*)(void*), void*>>());
542
543   // We allocate fnRunner_ separately, rather than declaring it directly
544   // as a member of EventBase solely so that we don't need to include
545   // NotificationQueue.h from EventBase.h
546   fnRunner_.reset(new FunctionRunner());
547
548   // Mark this as an internal event, so event_base_loop() will return if
549   // there are no other events besides this one installed.
550   //
551   // Most callers don't care about the internal notification queue used by
552   // EventBase.  The queue is always installed, so if we did count the queue as
553   // an active event, loop() would never exit with no more events to process.
554   // Users can use loopForever() if they do care about the notification queue.
555   // (This is useful for EventBase threads that do nothing but process
556   // runInEventBaseThread() notifications.)
557   fnRunner_->startConsumingInternal(this, queue_.get());
558 }
559
560 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
561   expCoeff_ = -1.0/timeInterval;
562   VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
563 }
564
565 void EventBase::SmoothLoopTime::reset(double value) {
566   value_ = value;
567 }
568
569 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
570     /*
571      * Position at which the busy sample is considered to be taken.
572      * (Allows to quickly skew our average without editing much code)
573      */
574     enum BusySamplePosition {
575       RIGHT = 0,  // busy sample placed at the end of the iteration
576       CENTER = 1, // busy sample placed at the middle point of the iteration
577       LEFT = 2,   // busy sample placed at the beginning of the iteration
578     };
579
580   VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
581               " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
582               " busy " << busy << " " << __PRETTY_FUNCTION__;
583   idle += oldBusyLeftover_ + busy;
584   oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
585   idle -= oldBusyLeftover_;
586
587   double coeff = exp(idle * expCoeff_);
588   value_ *= coeff;
589   value_ += (1.0 - coeff) * busy;
590 }
591
592 bool EventBase::nothingHandledYet() {
593   VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
594   return (nextLoopCnt_ != latestLoopCnt_);
595 }
596
597 /* static */
598 void EventBase::runFunctionPtr(Cob* fn) {
599   // The function should never throw an exception, because we have no
600   // way of knowing what sort of error handling to perform.
601   //
602   // If it does throw, log a message and abort the program.
603   try {
604     (*fn)();
605   } catch (const std::exception &ex) {
606     LOG(ERROR) << "runInEventBaseThread() std::function threw a "
607                << typeid(ex).name() << " exception: " << ex.what();
608     abort();
609   } catch (...) {
610     LOG(ERROR) << "runInEventBaseThread() std::function threw an exception";
611     abort();
612   }
613
614   // The function object was allocated by runInEventBaseThread().
615   // Delete it once it has been run.
616   delete fn;
617 }
618
619 EventBase::RunInLoopCallback::RunInLoopCallback(void (*fn)(void*), void* arg)
620     : fn_(fn)
621     , arg_(arg) {}
622
623 void EventBase::RunInLoopCallback::runLoopCallback() noexcept {
624   fn_(arg_);
625   delete this;
626 }
627
628 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
629                                       InternalEnum internal) {
630
631   struct event* ev = obj->getEvent();
632   assert(ev->ev_base == nullptr);
633
634   event_base_set(getLibeventBase(), ev);
635   if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
636     // Set the EVLIST_INTERNAL flag
637     ev->ev_flags |= EVLIST_INTERNAL;
638   }
639 }
640
641 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
642   cancelTimeout(obj);
643   struct event* ev = obj->getEvent();
644   ev->ev_base = nullptr;
645 }
646
647 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
648                                  std::chrono::milliseconds timeout) {
649   assert(isInEventBaseThread());
650   // Set up the timeval and add the event
651   struct timeval tv;
652   tv.tv_sec = timeout.count() / 1000LL;
653   tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
654
655   struct event* ev = obj->getEvent();
656   if (event_add(ev, &tv) < 0) {
657     LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
658     return false;
659   }
660
661   return true;
662 }
663
664 void EventBase::cancelTimeout(AsyncTimeout* obj) {
665   assert(isInEventBaseThread());
666   struct event* ev = obj->getEvent();
667   if (EventUtil::isEventRegistered(ev)) {
668     event_del(ev);
669   }
670 }
671
672 void EventBase::setName(const std::string& name) {
673   assert(isInEventBaseThread());
674   name_ = name;
675 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12)
676   if (isRunning()) {
677     pthread_setname_np(loopThread_.load(std::memory_order_relaxed),
678                        name_.c_str());
679   }
680 #endif
681 }
682
683 const std::string& EventBase::getName() {
684   assert(isInEventBaseThread());
685   return name_;
686 }
687
688 } // folly