2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include <sys/types.h>
30 #include <folly/io/async/EventBase.h>
31 #include <folly/io/async/EventHandler.h>
32 #include <folly/io/async/DelayedDestruction.h>
33 #include <folly/io/async/Request.h>
34 #include <folly/Likely.h>
35 #include <folly/ScopeGuard.h>
36 #include <folly/SpinLock.h>
38 #include <glog/logging.h>
40 #if __linux__ && !__ANDROID__
41 #define FOLLY_HAVE_EVENTFD
42 #include <folly/io/async/EventFDWrapper.h>
48 * A producer-consumer queue for passing messages between EventBase threads.
50 * Messages can be added to the queue from any thread. Multiple consumers may
51 * listen to the queue from multiple EventBase threads.
53 * A NotificationQueue may not be destroyed while there are still consumers
54 * registered to receive events from the queue. It is the user's
55 * responsibility to ensure that all consumers are unregistered before the
58 * MessageT should be MoveConstructible (i.e., must support either a move
59 * constructor or a copy constructor, or both). Ideally it's move constructor
60 * (or copy constructor if no move constructor is provided) should never throw
61 * exceptions. If the constructor may throw, the consumers could end up
62 * spinning trying to move a message off the queue and failing, and then
65 template<typename MessageT>
66 class NotificationQueue {
69 * A callback interface for consuming messages from the queue as they arrive.
71 class Consumer : public DelayedDestruction, private EventHandler {
73 enum : uint16_t { kDefaultMaxReadAtOnce = 10 };
77 destroyedFlagPtr_(nullptr),
78 maxReadAtOnce_(kDefaultMaxReadAtOnce) {}
81 * messageAvailable() will be invoked whenever a new
82 * message is available from the pipe.
84 virtual void messageAvailable(MessageT&& message) = 0;
87 * Begin consuming messages from the specified queue.
89 * messageAvailable() will be called whenever a message is available. This
90 * consumer will continue to consume messages until stopConsuming() is
93 * A Consumer may only consume messages from a single NotificationQueue at
94 * a time. startConsuming() should not be called if this consumer is
97 void startConsuming(EventBase* eventBase, NotificationQueue* queue) {
98 init(eventBase, queue);
99 registerHandler(READ | PERSIST);
103 * Same as above but registers this event handler as internal so that it
104 * doesn't count towards the pending reader count for the IOLoop.
106 void startConsumingInternal(
107 EventBase* eventBase, NotificationQueue* queue) {
108 init(eventBase, queue);
109 registerInternalHandler(READ | PERSIST);
113 * Stop consuming messages.
115 * startConsuming() may be called again to resume consumption of messages
116 * at a later point in time.
118 void stopConsuming();
121 * Consume messages off the queue until it is empty. No messages may be
122 * added to the queue while it is draining, so that the process is bounded.
123 * To that end, putMessage/tryPutMessage will throw an std::runtime_error,
124 * and tryPutMessageNoThrow will return false.
126 * @returns true if the queue was drained, false otherwise. In practice,
127 * this will only fail if someone else is already draining the queue.
129 bool consumeUntilDrained(size_t* numConsumed = nullptr) noexcept;
132 * Get the NotificationQueue that this consumer is currently consuming
133 * messages from. Returns nullptr if the consumer is not currently
134 * consuming events from any queue.
136 NotificationQueue* getCurrentQueue() const {
141 * Set a limit on how many messages this consumer will read each iteration
142 * around the event loop.
144 * This helps rate-limit how much work the Consumer will do each event loop
145 * iteration, to prevent it from starving other event handlers.
147 * A limit of 0 means no limit will be enforced. If unset, the limit
148 * defaults to kDefaultMaxReadAtOnce (defined to 10 above).
150 void setMaxReadAtOnce(uint32_t maxAtOnce) {
151 maxReadAtOnce_ = maxAtOnce;
153 uint32_t getMaxReadAtOnce() const {
154 return maxReadAtOnce_;
157 EventBase* getEventBase() {
161 void handlerReady(uint16_t events) noexcept override;
165 void destroy() override;
167 virtual ~Consumer() {}
171 * Consume messages off the the queue until
172 * - the queue is empty (1), or
173 * - until the consumer is destroyed, or
174 * - until the consumer is uninstalled, or
175 * - an exception is thrown in the course of dequeueing, or
176 * - unless isDrain is true, until the maxReadAtOnce_ limit is hit
178 * (1) Well, maybe. See logic/comments around "wasEmpty" in implementation.
180 void consumeMessages(bool isDrain, size_t* numConsumed = nullptr) noexcept;
182 void setActive(bool active, bool shouldLock = false) {
188 queue_->spinlock_.lock();
190 if (!active_ && active) {
191 ++queue_->numActiveConsumers_;
192 } else if (active_ && !active) {
193 --queue_->numActiveConsumers_;
197 queue_->spinlock_.unlock();
200 void init(EventBase* eventBase, NotificationQueue* queue);
202 NotificationQueue* queue_;
203 bool* destroyedFlagPtr_;
204 uint32_t maxReadAtOnce_;
211 #ifdef FOLLY_HAVE_EVENTFD
217 * Create a new NotificationQueue.
219 * If the maxSize parameter is specified, this sets the maximum queue size
220 * that will be enforced by tryPutMessage(). (This size is advisory, and may
221 * be exceeded if producers explicitly use putMessage() instead of
224 * The fdType parameter determines the type of file descriptor used
225 * internally to signal message availability. The default (eventfd) is
226 * preferable for performance and because it won't fail when the queue gets
227 * too long. It is not available on on older and non-linux kernels, however.
228 * In this case the code will fall back to using a pipe, the parameter is
229 * mostly for testing purposes.
231 explicit NotificationQueue(uint32_t maxSize = 0,
232 #ifdef FOLLY_HAVE_EVENTFD
233 FdType fdType = FdType::EVENTFD)
235 FdType fdType = FdType::PIPE)
239 advisoryMaxQueueSize_(maxSize),
243 RequestContext::saveContext();
245 #ifdef FOLLY_HAVE_EVENTFD
246 if (fdType == FdType::EVENTFD) {
247 eventfd_ = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK | EFD_SEMAPHORE);
248 if (eventfd_ == -1) {
249 if (errno == ENOSYS || errno == EINVAL) {
250 // eventfd not availalble
251 LOG(ERROR) << "failed to create eventfd for NotificationQueue: "
252 << errno << ", falling back to pipe mode (is your kernel "
254 fdType = FdType::PIPE;
257 folly::throwSystemError("Failed to create eventfd for "
258 "NotificationQueue", errno);
263 if (fdType == FdType::PIPE) {
264 if (pipe(pipeFds_)) {
265 folly::throwSystemError("Failed to create pipe for NotificationQueue",
269 // put both ends of the pipe into non-blocking mode
270 if (fcntl(pipeFds_[0], F_SETFL, O_RDONLY | O_NONBLOCK) != 0) {
271 folly::throwSystemError("failed to put NotificationQueue pipe read "
272 "endpoint into non-blocking mode", errno);
274 if (fcntl(pipeFds_[1], F_SETFL, O_WRONLY | O_NONBLOCK) != 0) {
275 folly::throwSystemError("failed to put NotificationQueue pipe write "
276 "endpoint into non-blocking mode", errno);
279 ::close(pipeFds_[0]);
280 ::close(pipeFds_[1]);
286 ~NotificationQueue() {
291 if (pipeFds_[0] >= 0) {
292 ::close(pipeFds_[0]);
295 if (pipeFds_[1] >= 0) {
296 ::close(pipeFds_[1]);
302 * Set the advisory maximum queue size.
304 * This maximum queue size affects calls to tryPutMessage(). Message
305 * producers can still use the putMessage() call to unconditionally put a
306 * message on the queue, ignoring the configured maximum queue size. This
307 * can cause the queue size to exceed the configured maximum.
309 void setMaxQueueSize(uint32_t max) {
310 advisoryMaxQueueSize_ = max;
314 * Attempt to put a message on the queue if the queue is not already full.
316 * If the queue is full, a std::overflow_error will be thrown. The
317 * setMaxQueueSize() function controls the maximum queue size.
319 * If the queue is currently draining, an std::runtime_error will be thrown.
321 * This method may contend briefly on a spinlock if many threads are
322 * concurrently accessing the queue, but for all intents and purposes it will
323 * immediately place the message on the queue and return.
325 * tryPutMessage() may throw std::bad_alloc if memory allocation fails, and
326 * may throw any other exception thrown by the MessageT move/copy
329 void tryPutMessage(MessageT&& message) {
330 putMessageImpl(std::move(message), advisoryMaxQueueSize_);
332 void tryPutMessage(const MessageT& message) {
333 putMessageImpl(message, advisoryMaxQueueSize_);
337 * No-throw versions of the above. Instead returns true on success, false on
340 * Only std::overflow_error (the common exception case) and std::runtime_error
341 * (which indicates that the queue is being drained) are prevented from being
342 * thrown. User code must still catch std::bad_alloc errors.
344 bool tryPutMessageNoThrow(MessageT&& message) {
345 return putMessageImpl(std::move(message), advisoryMaxQueueSize_, false);
347 bool tryPutMessageNoThrow(const MessageT& message) {
348 return putMessageImpl(message, advisoryMaxQueueSize_, false);
352 * Unconditionally put a message on the queue.
354 * This method is like tryPutMessage(), but ignores the maximum queue size
355 * and always puts the message on the queue, even if the maximum queue size
358 * putMessage() may throw
359 * - std::bad_alloc if memory allocation fails, and may
360 * - std::runtime_error if the queue is currently draining
361 * - any other exception thrown by the MessageT move/copy constructor.
363 void putMessage(MessageT&& message) {
364 putMessageImpl(std::move(message), 0);
366 void putMessage(const MessageT& message) {
367 putMessageImpl(message, 0);
371 * Put several messages on the queue.
373 template<typename InputIteratorT>
374 void putMessages(InputIteratorT first, InputIteratorT last) {
375 typedef typename std::iterator_traits<InputIteratorT>::iterator_category
377 putMessagesImpl(first, last, IterCategory());
381 * Try to immediately pull a message off of the queue, without blocking.
383 * If a message is immediately available, the result parameter will be
384 * updated to contain the message contents and true will be returned.
386 * If no message is available, false will be returned and result will be left
389 bool tryConsume(MessageT& result) {
394 folly::SpinLockGuard g(spinlock_);
396 if (UNLIKELY(queue_.empty())) {
400 auto data = std::move(queue_.front());
402 RequestContext::setContext(data.second);
406 // Handle an exception if the assignment operator happens to throw.
407 // We consumed an event but weren't able to pop the message off the
408 // queue. Signal the event again since the message is still in the
418 folly::SpinLockGuard g(spinlock_);
419 return queue_.size();
423 * Check that the NotificationQueue is being used from the correct process.
425 * If you create a NotificationQueue in one process, then fork, and try to
426 * send messages to the queue from the child process, you're going to have a
427 * bad time. Unfortunately users have (accidentally) run into this.
429 * Because we use an eventfd/pipe, the child process can actually signal the
430 * parent process that an event is ready. However, it can't put anything on
431 * the parent's queue, so the parent wakes up and finds an empty queue. This
432 * check ensures that we catch the problem in the misbehaving child process
433 * code, and crash before signalling the parent process.
435 void checkPid() const {
436 CHECK_EQ(pid_, getpid());
440 // Forbidden copy constructor and assignment operator
441 NotificationQueue(NotificationQueue const &) = delete;
442 NotificationQueue& operator=(NotificationQueue const &) = delete;
444 inline bool checkQueueSize(size_t maxSize, bool throws=true) const {
445 DCHECK(0 == spinlock_.trylock());
446 if (maxSize > 0 && queue_.size() >= maxSize) {
448 throw std::overflow_error("unable to add message to NotificationQueue: "
456 inline bool checkDraining(bool throws=true) {
457 if (UNLIKELY(draining_ && throws)) {
458 throw std::runtime_error("queue is draining, cannot add message");
463 inline void signalEvent(size_t numAdded = 1) const {
464 static const uint8_t kPipeMessage[] = {
465 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
468 ssize_t bytes_written = 0;
469 ssize_t bytes_expected = 0;
471 // eventfd(2) dictates that we must write a 64-bit integer
472 uint64_t numAdded64(numAdded);
473 bytes_expected = static_cast<ssize_t>(sizeof(numAdded64));
474 bytes_written = ::write(eventfd_, &numAdded64, sizeof(numAdded64));
476 // pipe semantics, add one message for each numAdded
477 bytes_expected = numAdded;
479 size_t messageSize = std::min(numAdded, sizeof(kPipeMessage));
480 ssize_t rc = ::write(pipeFds_[1], kPipeMessage, messageSize);
482 // TODO: if the pipe is full, write will fail with EAGAIN.
483 // See task #1044651 for how this could be handled
488 } while (numAdded > 0);
490 if (bytes_written != bytes_expected) {
491 folly::throwSystemError("failed to signal NotificationQueue after "
496 bool tryConsumeEvent() {
500 rc = ::read(eventfd_, &value, sizeof(value));
503 rc = ::read(pipeFds_[0], &value8, sizeof(value8));
507 // EAGAIN should pretty much be the only error we can ever get.
508 // This means someone else already processed the only available message.
509 CHECK_EQ(errno, EAGAIN);
516 bool putMessageImpl(MessageT&& message, size_t maxSize, bool throws=true) {
520 folly::SpinLockGuard g(spinlock_);
521 if (checkDraining(throws) || !checkQueueSize(maxSize, throws)) {
524 // We only need to signal an event if not all consumers are
526 if (numActiveConsumers_ < numConsumers_) {
529 queue_.emplace_back(std::move(message), RequestContext::saveContext());
538 const MessageT& message, size_t maxSize, bool throws=true) {
542 folly::SpinLockGuard g(spinlock_);
543 if (checkDraining(throws) || !checkQueueSize(maxSize, throws)) {
546 if (numActiveConsumers_ < numConsumers_) {
549 queue_.emplace_back(message, RequestContext::saveContext());
557 template<typename InputIteratorT>
558 void putMessagesImpl(InputIteratorT first, InputIteratorT last,
559 std::input_iterator_tag) {
564 folly::SpinLockGuard g(spinlock_);
566 while (first != last) {
567 queue_.emplace_back(*first, RequestContext::saveContext());
571 if (numActiveConsumers_ < numConsumers_) {
580 mutable folly::SpinLock spinlock_;
582 int pipeFds_[2]; // to fallback to on older/non-linux systems
583 uint32_t advisoryMaxQueueSize_;
585 std::deque<std::pair<MessageT, std::shared_ptr<RequestContext>>> queue_;
586 int numConsumers_{0};
587 std::atomic<int> numActiveConsumers_{0};
588 bool draining_{false};
591 template<typename MessageT>
592 void NotificationQueue<MessageT>::Consumer::destroy() {
593 // If we are in the middle of a call to handlerReady(), destroyedFlagPtr_
594 // will be non-nullptr. Mark the value that it points to, so that
595 // handlerReady() will know the callback is destroyed, and that it cannot
596 // access any member variables anymore.
597 if (destroyedFlagPtr_) {
598 *destroyedFlagPtr_ = true;
601 DelayedDestruction::destroy();
604 template<typename MessageT>
605 void NotificationQueue<MessageT>::Consumer::handlerReady(uint16_t /*events*/)
607 consumeMessages(false);
610 template<typename MessageT>
611 void NotificationQueue<MessageT>::Consumer::consumeMessages(
612 bool isDrain, size_t* numConsumed) noexcept {
613 DestructorGuard dg(this);
614 uint32_t numProcessed = 0;
615 bool firstRun = true;
617 SCOPE_EXIT { setActive(false, /* shouldLock = */ true); };
619 if (numConsumed != nullptr) {
620 *numConsumed = numProcessed;
624 // Try to decrement the eventfd.
626 // The eventfd is only used to wake up the consumer - there may or
627 // may not actually be an event available (another consumer may
628 // have read it). We don't really care, we only care about
629 // emptying the queue.
630 if (!isDrain && firstRun) {
631 queue_->tryConsumeEvent();
635 // Now pop the message off of the queue.
637 // We have to manually acquire and release the spinlock here, rather than
638 // using SpinLockHolder since the MessageT has to be constructed while
639 // holding the spinlock and available after we release it. SpinLockHolder
640 // unfortunately doesn't provide a release() method. (We can't construct
641 // MessageT first since we have no guarantee that MessageT has a default
643 queue_->spinlock_.lock();
647 if (UNLIKELY(queue_->queue_.empty())) {
648 // If there is no message, we've reached the end of the queue, return.
650 queue_->spinlock_.unlock();
654 // Pull a message off the queue.
655 auto& data = queue_->queue_.front();
657 MessageT msg(std::move(data.first));
659 RequestContext::setContext(data.second);
660 queue_->queue_.pop_front();
662 // Check to see if the queue is empty now.
663 // We use this as an optimization to see if we should bother trying to
664 // loop again and read another message after invoking this callback.
665 bool wasEmpty = queue_->queue_.empty();
670 // Now unlock the spinlock before we invoke the callback.
671 queue_->spinlock_.unlock();
675 bool callbackDestroyed = false;
676 CHECK(destroyedFlagPtr_ == nullptr);
677 destroyedFlagPtr_ = &callbackDestroyed;
678 messageAvailable(std::move(msg));
679 destroyedFlagPtr_ = nullptr;
681 RequestContext::setContext(old_ctx);
683 // If the callback was destroyed before it returned, we are done
684 if (callbackDestroyed) {
688 // If the callback is no longer installed, we are done.
689 if (queue_ == nullptr) {
693 // If we have hit maxReadAtOnce_, we are done.
695 if (!isDrain && maxReadAtOnce_ > 0 &&
696 numProcessed >= maxReadAtOnce_) {
697 queue_->signalEvent(1);
701 // If the queue was empty before we invoked the callback, it's probable
702 // that it is still empty now. Just go ahead and return, rather than
703 // looping again and trying to re-read from the eventfd. (If a new
704 // message had in fact arrived while we were invoking the callback, we
705 // will simply be woken up the next time around the event loop and will
706 // process the message then.)
710 } catch (const std::exception& ex) {
711 // This catch block is really just to handle the case where the MessageT
712 // constructor throws. The messageAvailable() callback itself is
713 // declared as noexcept and should never throw.
715 // If the MessageT constructor does throw we try to handle it as best as
716 // we can, but we can't work miracles. We will just ignore the error for
717 // now and return. The next time around the event loop we will end up
718 // trying to read the message again. If MessageT continues to throw we
719 // will never make forward progress and will keep trying each time around
722 // Unlock the spinlock.
723 queue_->spinlock_.unlock();
725 // Push a notification back on the eventfd since we didn't actually
726 // read the message off of the queue.
728 queue_->signalEvent(1);
737 template<typename MessageT>
738 void NotificationQueue<MessageT>::Consumer::init(
739 EventBase* eventBase,
740 NotificationQueue* queue) {
741 assert(eventBase->isInEventBaseThread());
742 assert(queue_ == nullptr);
743 assert(!isHandlerRegistered());
751 folly::SpinLockGuard g(queue_->spinlock_);
752 queue_->numConsumers_++;
754 queue_->signalEvent();
756 if (queue_->eventfd_ >= 0) {
757 initHandler(eventBase, queue_->eventfd_);
759 initHandler(eventBase, queue_->pipeFds_[0]);
763 template<typename MessageT>
764 void NotificationQueue<MessageT>::Consumer::stopConsuming() {
765 if (queue_ == nullptr) {
766 assert(!isHandlerRegistered());
771 folly::SpinLockGuard g(queue_->spinlock_);
772 queue_->numConsumers_--;
776 assert(isHandlerRegistered());
782 template<typename MessageT>
783 bool NotificationQueue<MessageT>::Consumer::consumeUntilDrained(
784 size_t* numConsumed) noexcept {
785 DestructorGuard dg(this);
787 folly::SpinLockGuard g(queue_->spinlock_);
788 if (queue_->draining_) {
791 queue_->draining_ = true;
793 consumeMessages(true, numConsumed);
795 folly::SpinLockGuard g(queue_->spinlock_);
796 queue_->draining_ = false;