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