LCOV - code coverage report
Current view: top level - root/contrail/src/contrail-common/base - queue_task.h (source / functions) Hit Total Coverage
Test: OpenSDN C/C++ coverage (all TARGET_SET jobs) Lines: 270 300 90.0 %
Date: 2026-11-30 02:00:48 Functions: 1364 2301 59.3 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
       3             :  * Copyright Contributors to the OpenSDN project
       4             :  */
       5             : 
       6             : // queue_task.h
       7             : //
       8             : // Task based queue processor implementing thread safe enqueue and dequeue
       9             : // using concurrent queues. If queue is empty, enqueue creates a dequeue task
      10             : // that drains the queue. The dequeue task runs a maximum of kMaxIterations
      11             : // before yielding.
      12             : //
      13             : #ifndef __QUEUE_TASK_H__
      14             : #define __QUEUE_TASK_H__
      15             : 
      16             : #include <iostream>
      17             : #include <sstream>
      18             : #include <algorithm>
      19             : #include <vector>
      20             : #include <set>
      21             : #include <mutex>
      22             : #include <atomic>
      23             : 
      24             : #include <tbb/concurrent_queue.h>
      25             : #include <tbb/spin_rw_mutex.h>
      26             : 
      27             : #include <base/task.h>
      28             : #include <base/time_util.h>
      29             : #include <base/watermark.h>
      30             : 
      31             : template <typename QueueEntryT, typename QueueT>
      32             : class QueueTaskRunner : public Task {
      33             : public:
      34     1871273 :     QueueTaskRunner(QueueT *queue)
      35     1871273 :         : Task(queue->GetTaskId(), queue->GetTaskInstance()), queue_(queue) {
      36     1871242 :     }
      37             : 
      38     2460096 :     bool Run() {
      39             :         // Check if this run needs to be deferred
      40     2460096 :         if (!queue_->OnEntry()) {
      41       17738 :             return false;
      42             :         }
      43     2442371 :         return RunQueue();
      44             :         // No more client callbacks after updating
      45             :         // queue running_ and current_runner_ in RunQueue to
      46             :         // avoid client callbacks running concurrently
      47             :     }
      48             : 
      49           0 :     virtual std::string Description() const {
      50           0 :         return queue_->Description();
      51             :     }
      52             : 
      53             : private:
      54     2442362 :     bool RunQueue() {
      55             :         // Check if we need to abort
      56     2442362 :         if (queue_->RunnerAbort()) {
      57          19 :             return queue_->RunnerDone();
      58             :         }
      59             : 
      60     2442432 :         uint64_t start = 0;
      61     2442432 :         if (queue_->measure_busy_time_)
      62           0 :             start = ClockMonotonicUsec();
      63             : 
      64     2442425 :         QueueEntryT entry = QueueEntryT();
      65     2442407 :         size_t count = 0;
      66     9698728 :         while (queue_->Dequeue(&entry)) {
      67             :             // Process the entry
      68     7828399 :             if (!queue_->GetCallback()(entry)) {
      69      525904 :                 break;
      70             :             }
      71     7302553 :             if (++count == queue_->max_iterations_) {
      72       46232 :                 if (start)
      73           0 :                     queue_->add_busy_time(ClockMonotonicUsec() - start);
      74       46232 :                 return queue_->RunnerDone();
      75             :             }
      76             :         }
      77             : 
      78     2396139 :         if (start)
      79           0 :             queue_->add_busy_time(ClockMonotonicUsec() - start);
      80             : 
      81             :         // Running is done if queue_ is empty
      82             :         // While notification is being run, its possible that more entries
      83             :         // are added into queue_
      84     2396139 :         return queue_->RunnerDone();
      85     1383334 :     }
      86             : 
      87             :     QueueT *queue_;
      88             : };
      89             : 
      90             : template <typename QueueEntryT>
      91             : struct WorkQueueDelete {
      92             :     template <typename QueueT>
      93       56380 :     void operator()(QueueT &, bool) {}
      94             : };
      95             : 
      96             : template <typename QueueEntryT>
      97             : struct WorkQueueDelete<QueueEntryT *> {
      98             :     template <typename QueueT>
      99      162974 :     void operator()(QueueT &q, bool delete_entry) {
     100             :         QueueEntryT *entry;
     101      162974 :         while (q.try_pop(entry)) {
     102           0 :             if (delete_entry) {
     103           0 :                 delete entry;
     104             :             }
     105             :         }
     106      162974 :     }
     107             : };
     108             : 
     109             : template <typename QueueEntryT>
     110             : class WorkQueue {
     111             : public:
     112             :     static const int kMaxSize = 1024;
     113             :     static const int kMaxIterations = 32;
     114             :     typedef tbb::concurrent_queue<QueueEntryT> Queue;
     115             :     typedef boost::function<bool (QueueEntryT)> Callback;
     116             :     typedef boost::function<bool (void)> StartRunnerFunc;
     117             :     typedef boost::function<void (bool)> TaskExitCallback;
     118             :     typedef boost::function<bool ()> TaskEntryCallback;
     119             : 
     120      240359 :     WorkQueue(int taskId, int taskInstance, Callback callback,
     121             :               size_t size = kMaxSize,
     122             :               size_t max_iterations = kMaxIterations) :
     123      240359 :         running_(false),
     124      240359 :         taskId_(taskId),
     125      240359 :         taskInstance_(taskInstance),
     126      240359 :         name_(""),
     127      240359 :         callback_(callback),
     128      240359 :         on_entry_cb_(0),
     129      240359 :         on_exit_cb_(0),
     130      240358 :         start_runner_(0),
     131      240357 :         current_runner_(NULL),
     132      240357 :         on_entry_defer_count_(0),
     133      240357 :         deleted_(false),
     134      240357 :         enqueues_(0),
     135      240357 :         dequeues_(0),
     136      240357 :         drops_(0),
     137      240357 :         max_iterations_(max_iterations),
     138      240357 :         size_(size),
     139      240357 :         bounded_(false),
     140      240357 :         shutdown_scheduled_(false),
     141      240357 :         delete_entries_on_shutdown_(true),
     142      240359 :         task_starts_(0),
     143      240359 :         max_queue_len_(0),
     144      240359 :         busy_time_(0),
     145      480716 :         measure_busy_time_(false) {
     146      240359 :         count_ = 0;
     147      240361 :         disabled_ = false;
     148      240361 :     }
     149             : 
     150             :     // Concurrency - should be called from a task whose policy
     151             :     // assures that the dequeue task - QueueTaskRunner is not running
     152             :     // concurrently
     153      219574 :     void Shutdown(bool delete_entries = true) {
     154      219574 :         std::scoped_lock lock(mutex_);
     155      219574 :         ShutdownLocked(delete_entries);
     156      219574 :     }
     157             : 
     158             :     // Concurrency - can be called from any context
     159             :     // Schedule shutdown of the WorkQueue, shutdown may happen asynchronously
     160             :     // or in the caller's context also
     161           4 :     void ScheduleShutdown(bool delete_entries = true) {
     162           4 :         std::scoped_lock lock(mutex_);
     163           4 :         if (shutdown_scheduled_) {
     164           0 :             return;
     165             :         }
     166           4 :         shutdown_scheduled_ = true;
     167           4 :         delete_entries_on_shutdown_ = delete_entries;
     168             : 
     169             :         // Cancel QueueTaskRunner
     170           4 :         if (running_) {
     171           3 :             assert(current_runner_);
     172           3 :             TaskScheduler *scheduler = TaskScheduler::GetInstance();
     173             :             TaskScheduler::CancelReturnCode cancel_code =
     174           3 :                 scheduler->Cancel(current_runner_);
     175           3 :             if (cancel_code == TaskScheduler::CANCELLED) {
     176           1 :                 running_ = false;
     177           1 :                 current_runner_ = NULL;
     178           1 :                 ShutdownLocked(delete_entries);
     179             :             } else {
     180           2 :                 assert(cancel_code == TaskScheduler::QUEUED);
     181             :             }
     182             :         } else {
     183           1 :             ShutdownLocked(delete_entries);
     184             :         }
     185           4 :     }
     186             : 
     187      240339 :     ~WorkQueue() {
     188      240339 :         std::scoped_lock lock(mutex_);
     189             :         // Shutdown() needs to be called before deleting
     190             :         //assert(!running_ && deleted_);
     191      240339 :     }
     192             : 
     193         234 :     void SetStartRunnerFunc(StartRunnerFunc start_runner_fn) {
     194         234 :         start_runner_ = start_runner_fn;
     195         234 :     }
     196             : 
     197          11 :     void SetSize(size_t size) {
     198          11 :         size_ = size;
     199          11 :     }
     200             : 
     201          14 :     void SetBounded(bool bounded) {
     202          14 :         bounded_ = bounded;
     203          14 :     }
     204             : 
     205             :     bool GetBounded() const {
     206             :         return bounded_;
     207             :     }
     208             : 
     209           1 :     void SetHighWaterMark(const WaterMarkInfos &high_water) {
     210           1 :         std::scoped_lock lock(water_mutex_);
     211           1 :         watermarks_.SetHighWaterMark(high_water);
     212           1 :     }
     213             : 
     214         419 :     void SetHighWaterMark(const WaterMarkInfo& hwm_info) {
     215         419 :         std::scoped_lock lock(water_mutex_);
     216         419 :         watermarks_.SetHighWaterMark(hwm_info);
     217         419 :     }
     218             : 
     219      219579 :     void ResetHighWaterMark() {
     220      219579 :         std::scoped_lock lock(water_mutex_);
     221      219579 :         watermarks_.ResetHighWaterMark();
     222      219579 :     }
     223             : 
     224           1 :     WaterMarkInfos GetHighWaterMark() const {
     225           1 :         std::scoped_lock lock(water_mutex_);
     226           2 :         return watermarks_.GetHighWaterMark();
     227           1 :     }
     228             : 
     229           4 :     void SetLowWaterMark(const WaterMarkInfos &low_water) {
     230           4 :         std::scoped_lock lock(water_mutex_);
     231           4 :         watermarks_.SetLowWaterMark(low_water);
     232           4 :      }
     233             : 
     234         404 :     void SetLowWaterMark(const WaterMarkInfo& lwm_info) {
     235         404 :         std::scoped_lock lock(water_mutex_);
     236         404 :         watermarks_.SetLowWaterMark(lwm_info);
     237         404 :      }
     238             : 
     239      219578 :     void ResetLowWaterMark() {
     240      219578 :         std::scoped_lock lock(water_mutex_);
     241      219578 :         watermarks_.ResetLowWaterMark();
     242      219578 :     }
     243             : 
     244           1 :     WaterMarkInfos GetLowWaterMark() const {
     245           1 :         std::scoped_lock lock(water_mutex_);
     246           2 :         return watermarks_.GetLowWaterMark();
     247           1 :     }
     248             : 
     249     7822650 :     bool Enqueue(QueueEntryT entry) {
     250     7822650 :         if (bounded_) {
     251         569 :             if (AreWaterMarksSet()) {
     252           0 :                 return EnqueueBoundedLocked(entry);
     253             :             } else {
     254         569 :                 return EnqueueBounded(entry);
     255             :             }
     256             :         } else {
     257     7822081 :             if (AreWaterMarksSet()) {
     258      112872 :                 return EnqueueInternalLocked(entry);
     259             :             } else {
     260     7709076 :                 return EnqueueInternal(entry);
     261             :             }
     262             :         }
     263             :     }
     264             : 
     265             :     // Returns true if pop is successful.
     266     9698604 :     bool Dequeue(QueueEntryT *entry) {
     267     9698604 :         if (AreWaterMarksSet()) {
     268      119111 :             return DequeueInternalLocked(entry);
     269             :         } else {
     270     9579375 :             return DequeueInternal(entry);
     271             :         }
     272             :     }
     273             : 
     274     1871250 :     int GetTaskId() const {
     275     1871250 :         return taskId_;
     276             :     }
     277             : 
     278     1871268 :     int GetTaskInstance() const {
     279     1871268 :         return taskInstance_;
     280             :     }
     281             : 
     282     7846098 :     void MayBeStartRunner() {
     283     7846098 :         std::scoped_lock lock(mutex_);
     284     7846240 :         if (running_ || queue_.empty() || deleted_ || RunnerAbortLocked()) {
     285     5974702 :             return;
     286             :         }
     287     1871239 :         task_starts_++;
     288     1871239 :         running_ = true;
     289     1871239 :         assert(current_runner_ == NULL);
     290     1871239 :         current_runner_ =
     291     1871239 :             new QueueTaskRunner<QueueEntryT, WorkQueue<QueueEntryT> >(this);
     292     1871239 :         TaskScheduler *scheduler = TaskScheduler::GetInstance();
     293     1871214 :         scheduler->Enqueue(current_runner_);
     294     7846372 :     }
     295             : 
     296     7828392 :     Callback GetCallback() const {
     297     7828392 :         return callback_;
     298             :     }
     299             : 
     300        2087 :     void SetEntryCallback(TaskEntryCallback on_entry) {
     301        2087 :         on_entry_cb_ = on_entry;
     302        2087 :     }
     303             : 
     304       36066 :     void SetExitCallback(TaskExitCallback on_exit) {
     305       36066 :         on_exit_cb_ = on_exit;
     306       36066 :     }
     307             : 
     308       17481 :     void set_name(const std::string &name) {
     309       17481 :         name_ = name;
     310       17481 :     }
     311           0 :     std::string Description() const {
     312           0 :         if (name_.empty() == false)
     313           0 :             return name_;
     314             : 
     315           0 :         std::ostringstream str;
     316           0 :         str << "Function " << callback_;
     317           0 :         return str.str();
     318           0 :     }
     319             : 
     320       34559 :     void set_disable(bool disabled) {
     321       34559 :         if (disabled_ != disabled) {
     322       34558 :             disabled_ = disabled;
     323       34558 :             if (!disabled_) {
     324       17279 :                 MayBeStartRunner();
     325             :             }
     326             :         }
     327       34559 :     }
     328             : 
     329             :     bool IsDisabled() const {
     330             :         return disabled_;
     331             :     }
     332             : 
     333             :     size_t on_entry_defer_count() const {
     334             :         return on_entry_defer_count_;
     335             :     }
     336             : 
     337     2460106 :     bool OnEntry() {
     338     2460106 :         bool run = (on_entry_cb_.empty() || on_entry_cb_());
     339             : 
     340             :         // Track number of times this queue run is deferred
     341     2460113 :         if (!run) {
     342       17738 :             on_entry_defer_count_++;
     343             :         }
     344     2460113 :         return run;
     345             :     }
     346             : 
     347     2442380 :     void OnExit(bool done) {
     348     2442380 :         if (!on_exit_cb_.empty()) {
     349       10713 :             on_exit_cb_(done);
     350             :         }
     351     2442385 :     }
     352             : 
     353     8451535 :     bool IsQueueEmpty() const {
     354     8451535 :         return queue_.empty();
     355             :     }
     356             : 
     357        7952 :     size_t Length() const {
     358        7952 :         return count_;
     359             :     }
     360             : 
     361          20 :     size_t NumEnqueues() const {
     362          20 :         return enqueues_;
     363             :     }
     364             : 
     365          21 :     size_t NumDequeues() const {
     366          21 :         return dequeues_;
     367             :     }
     368             : 
     369             :     size_t NumDrops() const {
     370             :         return drops_;
     371             :     }
     372             : 
     373           3 :     bool deleted() const {
     374           3 :         return deleted_;
     375             :     }
     376             : 
     377           0 :     uint32_t task_starts() const { return task_starts_; }
     378          11 :     size_t max_queue_len() const { return max_queue_len_; }
     379             :     bool measure_busy_time() const { return measure_busy_time_; }
     380          14 :     void set_measure_busy_time(bool val) const { measure_busy_time_ = val; }
     381           0 :     uint64_t busy_time() const { return busy_time_; }
     382           0 :     void add_busy_time(uint64_t t) { busy_time_ += t; }
     383           0 :     void ClearStats() const {
     384           0 :         max_queue_len_ = 0;
     385           0 :         enqueues_ = 0;
     386           0 :         dequeues_ = 0;
     387           0 :         busy_time_ = 0;
     388           0 :         task_starts_ = 0;
     389           0 :     }
     390             : private:
     391             :     // Returns true if pop is successful.
     392     9698460 :     bool DequeueInternal(QueueEntryT *entry) {
     393     9698460 :         bool success = queue_.try_pop(*entry);
     394     9698721 :         if (success) {
     395     7828462 :             dequeues_++;
     396     7828462 :             size_t ncount(AtomicDecrementQueueCount(entry));
     397     7828491 :             ProcessLowWaterMarks(ncount);
     398             :         }
     399     9698675 :         return success;
     400             :     }
     401             : 
     402      119111 :     bool DequeueInternalLocked(QueueEntryT *entry) {
     403      119111 :         std::scoped_lock lock(water_mutex_);
     404      238222 :         return DequeueInternal(entry);
     405      119111 :     }
     406             : 
     407    17527137 :     bool AreWaterMarksSet() const {
     408    17527137 :         return watermarks_.AreWaterMarksSet();
     409             :     }
     410             : 
     411      219578 :     void ShutdownLocked(bool delete_entries) {
     412             :         // Cancel QueueTaskRunner from the scheduler
     413      219578 :         assert(!deleted_);
     414      219578 :         if (running_) {
     415         430 :             running_ = false;
     416         430 :             assert(current_runner_);
     417         430 :             TaskScheduler *scheduler = TaskScheduler::GetInstance();
     418             :             TaskScheduler::CancelReturnCode cancel_code =
     419         430 :                 scheduler->Cancel(current_runner_);
     420         430 :             assert(cancel_code == TaskScheduler::CANCELLED);
     421         430 :             current_runner_ = NULL;
     422             :         }
     423      219578 :         ResetHighWaterMark();
     424      219578 :         ResetLowWaterMark();
     425             :         WorkQueueDelete<QueueEntryT> deleter;
     426      219578 :         deleter(queue_, delete_entries);
     427      219578 :         queue_.clear();
     428      219578 :         count_ = 0;
     429      219578 :         deleted_ = true;
     430      219578 :     }
     431             : 
     432     7797298 :     size_t AtomicIncrementQueueCount(QueueEntryT *entry) {
     433    15594596 :         return count_.fetch_add(1) + 1;
     434             :     }
     435             : 
     436     7803110 :     size_t AtomicDecrementQueueCount(QueueEntryT *entry) {
     437    15606220 :         return count_.fetch_sub(1) - 1;
     438             :     }
     439             : 
     440     7822913 :     void ProcessHighWaterMarks(size_t count) {
     441     7822913 :         watermarks_.ProcessHighWaterMarks(count);
     442     7822752 :     }
     443             : 
     444     7828475 :     void ProcessLowWaterMarks(size_t count) {
     445     7828475 :         watermarks_.ProcessLowWaterMarks(count);
     446     7828410 :     }
     447             : 
     448     7822061 :     bool EnqueueInternal(QueueEntryT entry) {
     449     7822061 :         enqueues_++;
     450     7822061 :         size_t ncount(AtomicIncrementQueueCount(&entry));
     451     7822371 :         if (ncount > max_queue_len_)
     452      913032 :             max_queue_len_ = ncount;
     453     7822371 :         ProcessHighWaterMarks(ncount);
     454     7822184 :         queue_.push(entry);
     455     7822170 :         MayBeStartRunner();
     456     7822402 :         return ncount < size_;
     457             :     }
     458             : 
     459      112872 :     bool EnqueueInternalLocked(QueueEntryT entry) {
     460      112872 :         std::scoped_lock lock(water_mutex_);
     461      225744 :         return EnqueueInternal(entry);
     462      112872 :     }
     463             : 
     464         569 :     bool EnqueueBounded(QueueEntryT entry) {
     465         569 :         size_t ncount(AtomicIncrementQueueCount(&entry));
     466         569 :         if (ncount > max_queue_len_)
     467          34 :             max_queue_len_ = ncount;
     468         569 :         if (ncount < size_) {
     469         564 :             enqueues_++;
     470         564 :             ProcessHighWaterMarks(ncount);
     471         564 :             queue_.push(entry);
     472         564 :             MayBeStartRunner();
     473         564 :             return true;
     474             :         }
     475           5 :         AtomicDecrementQueueCount(&entry);
     476           5 :         drops_++;
     477           5 :         max_queue_len_ = count_;
     478           5 :         return false;
     479             :     }
     480             : 
     481           0 :     bool EnqueueBoundedLocked(QueueEntryT entry) {
     482           0 :         std::scoped_lock lock(water_mutex_);
     483           0 :         return EnqueueBounded(entry);
     484           0 :     }
     485             : 
     486     4918349 :     bool RunnerAbortLocked() {
     487     9803808 :         return (disabled_ || shutdown_scheduled_ ||
     488     9803722 :                 (!start_runner_.empty() && !start_runner_()));
     489             :     }
     490             : 
     491     2442369 :     bool RunnerAbort() {
     492     2442369 :         std::scoped_lock lock(mutex_);
     493     4884919 :         return RunnerAbortLocked();
     494     2442425 :     }
     495             : 
     496     2442482 :     bool RunnerDone() {
     497     2442482 :         std::scoped_lock lock(mutex_);
     498     2442464 :         bool done = false;
     499     2442464 :         if (queue_.empty() || RunnerAbortLocked()) {
     500     1871117 :             done = true;
     501     1871117 :             OnExit(done);
     502     1871118 :             current_runner_ = NULL;
     503     1871118 :             running_ = false;
     504     1871118 :             if (shutdown_scheduled_) {
     505           2 :                 ShutdownLocked(delete_entries_on_shutdown_);
     506             :             }
     507             :         } else {
     508      571268 :             OnExit(done);
     509      571268 :             running_ = true;
     510             :         }
     511     2442467 :         return done;
     512     2442386 :     }
     513             : 
     514             :     Queue queue_;
     515             :     std::atomic<size_t> count_;
     516             :     std::mutex mutex_;
     517             :     bool running_;
     518             :     int taskId_;
     519             :     int taskInstance_;
     520             :     std::string name_;
     521             :     Callback callback_;
     522             :     TaskEntryCallback on_entry_cb_;
     523             :     TaskExitCallback on_exit_cb_;
     524             :     StartRunnerFunc start_runner_;
     525             :     QueueTaskRunner<QueueEntryT, WorkQueue<QueueEntryT> > *current_runner_;
     526             :     size_t on_entry_defer_count_;
     527             :     std::atomic<bool> disabled_;
     528             :     bool deleted_;
     529             :     mutable size_t enqueues_;
     530             :     mutable size_t dequeues_;
     531             :     size_t drops_;
     532             :     size_t max_iterations_;
     533             :     size_t size_;
     534             :     bool bounded_;
     535             :     bool shutdown_scheduled_;
     536             :     bool delete_entries_on_shutdown_;
     537             :     WaterMarkTuple watermarks_;
     538             :     mutable std::mutex water_mutex_;
     539             :     mutable uint32_t task_starts_;
     540             :     mutable size_t max_queue_len_;
     541             :     mutable uint64_t busy_time_;
     542             :     mutable bool measure_busy_time_;
     543             : 
     544             :     friend class QueueTaskTest;
     545             :     friend class QueueTaskShutdownTest;
     546             :     friend class QueueTaskWaterMarkTest;
     547             :     friend class QueueTaskRunner<QueueEntryT, WorkQueue<QueueEntryT> >;
     548             : 
     549             :     DISALLOW_COPY_AND_ASSIGN(WorkQueue);
     550             : };
     551             : 
     552             : #endif /* __QUEUE_TASK_H__ */

Generated by: LCOV version 1.14