LCOV - code coverage report
Current view: top level - root/contrail/src/contrail-common/base - timer.cc (source / functions) Hit Total Coverage
Test: OpenSDN C/C++ coverage (all TARGET_SET jobs) Lines: 118 129 91.5 %
Date: 2026-11-30 02:00:48 Functions: 16 17 94.1 %
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             : #include "base/timer.h"
       7             : #include "base/timer_impl.h"
       8             : 
       9             : class Timer::TimerTask : public Task {
      10             : public:
      11       57431 :     TimerTask(TimerPtr timer, boost::system::error_code ec)
      12       57431 :         : Task(timer->task_id_, timer->task_instance_), timer_(timer), ec_(ec) {
      13       57431 :     }
      14             : 
      15      114862 :     virtual ~TimerTask() {
      16      114862 :     }
      17             : 
      18             :     // Invokes user callback.
      19             :     // Timer could have been cancelled or delete when task was enqueued
      20       57190 :     virtual bool Run() {
      21             :         {
      22       57190 :             std::unique_lock<std::mutex> lock(timer_->mutex_);
      23             : 
      24             :             // cancelled task .. ignore
      25       57307 :             if (task_cancelled()) {
      26             :                 // Cancelled timer's task releases the ownership of the timer
      27           1 :                 lock.unlock();
      28           1 :                 timer_ = NULL;
      29           1 :                 return true;
      30             :             }
      31             : 
      32             :             // Conditions to invoke user callback met. Fire it
      33       57282 :             timer_->SetState(Timer::Fired);
      34       57269 :         }
      35             : 
      36       57284 :         bool restart = false;
      37             : 
      38             :         // TODO: Is this error needed by user?
      39       57284 :         if (ec_ && !timer_->error_handler_.empty()) {
      40           0 :             timer_->error_handler_(timer_->name_,
      41           0 :                                    std::string(ec_.category().name()),
      42           0 :                                    ec_.message());
      43             :         } else {
      44       57267 :             restart = timer_->handler_();
      45             :         }
      46             : 
      47       57274 :         OnTaskCancel();
      48             : 
      49       57255 :         if (restart) {
      50       63852 :             timer_->Start(timer_->time_, timer_->handler_,
      51       31968 :                           timer_->error_handler_);
      52       25259 :         } else if (timer_->delete_on_completion_) {
      53         164 :             TimerManager::DeleteTimer(timer_.get());
      54             :         }
      55       57341 :         return true;
      56             :     }
      57             : 
      58             :     // Task Cancelled/Destroyed when it was Fired.
      59       57259 :     void OnTaskCancel() {
      60       57259 :         if (!timer_) {
      61           1 :             return;
      62             :         }
      63       57257 :         std::scoped_lock lock(timer_->mutex_);
      64             : 
      65       57245 :         if (timer_->timer_task_ != this) {
      66           0 :             assert(!timer_->timer_task_);
      67             :         }
      68             : 
      69       57198 :         timer_->timer_task_ = NULL;
      70       57160 :         timer_->SetState(Timer::Init);
      71       57118 :     }
      72             : 
      73           0 :     virtual std::string Description() const {
      74           0 :         return timer_->Description();
      75             :     }
      76             : 
      77             : private:
      78             :     TimerPtr timer_;
      79             :     boost::system::error_code ec_;
      80             :     DISALLOW_COPY_AND_ASSIGN(TimerTask);
      81             : };
      82             : 
      83      379172 : Timer::Timer(boost::asio::io_context &service, const std::string &name,
      84      379172 :           int task_id, int task_instance, bool delete_on_completion)
      85      379172 :         : impl_(new TimerImpl(service)),
      86      379170 :           name_(name),
      87      379168 :           handler_(NULL),
      88      379169 :           error_handler_(NULL),
      89      379169 :           state_(Init),
      90      379169 :           timer_task_(NULL),
      91      379169 :           time_(0),
      92      379169 :           task_id_(task_id),
      93      379169 :           task_instance_(task_instance),
      94      379169 :           seq_no_(0),
      95      758341 :           delete_on_completion_(delete_on_completion) {
      96      379169 :     refcount_ = 0;
      97      379172 : }
      98             : 
      99      755498 : Timer::~Timer() {
     100      377749 :     assert(state_ != Running && state_ != Fired);
     101      755498 : }
     102             : 
     103             : //
     104             : // Start a timer
     105             : //
     106             : // If the timer is already running, return silently
     107             : //
     108     4752149 : bool Timer::Start(int time, Handler handler, ErrorHandler error_handler) {
     109     4752149 :     std::scoped_lock lock(mutex_);
     110             : 
     111     4752497 :     if (time < 0) {
     112         138 :         return true;
     113             :     }
     114             : 
     115     4752359 :     if (state_ == Running || state_ == Fired) {
     116      175952 :         return true;
     117             :     }
     118             : 
     119             :     // Restart the timer
     120     4576407 :     time_ = time;
     121     4576407 :     handler_ = handler;
     122     4575567 :     seq_no_++;
     123     4575567 :     error_handler_ = error_handler;
     124     4575192 :     boost::system::error_code ec;
     125     4575192 :     impl_->expires_from_now(time, ec);
     126     4576469 :     if (ec) {
     127           0 :         return false;
     128             :     }
     129             : 
     130     4576458 :     SetState(Running);
     131     9152893 :     impl_->async_wait(
     132     9152986 :         boost::bind(&Timer::StartTimerTask, this, TimerPtr(this),
     133             :                     time, seq_no_, boost::asio::placeholders::error));
     134     4576579 :     return true;
     135     4752669 : }
     136             : 
     137        9961 : bool Timer::Reschedule(int time)
     138             : {
     139        9961 :     if (state_ != Fired)
     140         183 :         return false;
     141             : 
     142        9778 :     if (time < 0)
     143           0 :         return false;
     144             : 
     145        9778 :     time_ = time;
     146        9778 :     return true;
     147             : }
     148             : 
     149             : // Cancel a running timer
     150     5440282 : bool Timer::Cancel() {
     151     5440282 :     std::scoped_lock lock(mutex_);
     152             : 
     153             :     // A fired timer cannot be cancelled
     154     5440315 :     if (state_ == Fired) {
     155        4522 :         return false;
     156             :     }
     157             : 
     158             :     // Cancel Task. If Task cancel succeeds, there will be no callback.
     159             :     // Reset TaskRef if call succeeds.
     160     5435793 :     if (timer_task_) {
     161             :         TaskScheduler::CancelReturnCode rc =
     162          89 :             TaskScheduler::GetInstance()->Cancel(timer_task_);
     163          89 :         assert(rc != TaskScheduler::FAILED);
     164          89 :         timer_task_ = NULL;
     165             :     }
     166             : 
     167     5435793 :     SetState(Cancelled);
     168     5435742 :     return true;
     169     5440264 : }
     170             : 
     171             : // ASIO callback on timer expiry. Start a task to serve the timer
     172     4496975 : void Timer::StartTimerTask(TimerPtr reference, int time, uint32_t seq_no,
     173             :                            const boost::system::error_code &ec) {
     174     4496975 :     std::scoped_lock lock(mutex_);
     175             : 
     176     4496975 :     if (state_ == Cancelled) {
     177       24779 :         return;
     178             :     }
     179             : 
     180             :     // If timer was cancelled, no callback is invoked
     181     4472196 :     if (ec && ec.value() == boost::asio::error::operation_aborted) {
     182     4414764 :         return;
     183             :     }
     184             : 
     185             :     // Timer could have fired for previous run. Validate the seq_no_
     186       57432 :     if (seq_no_ != seq_no) {
     187           0 :         return;
     188             :     }
     189             :     // Start a task and add Task reference.
     190       57432 :     assert(timer_task_ == NULL);
     191       57432 :     timer_task_ = new TimerTask(reference, ec);
     192       57431 :     TaskScheduler::GetInstance()->Enqueue(timer_task_);
     193     4496974 : }
     194             : 
     195             : //
     196             : // TimerManager class routines
     197             : //
     198             : TimerManager::TimerSet TimerManager::timer_ref_;
     199             : std::mutex TimerManager::mutex_;
     200             : 
     201      379172 : Timer *TimerManager::CreateTimer(
     202             :             boost::asio::io_context &service, const std::string &name,
     203             :             int task_id, int task_instance, bool delete_on_completion) {
     204             :     Timer *timer = new Timer(service, name, task_id, task_instance,
     205      379172 :                              delete_on_completion);
     206      379172 :     AddTimer(timer);
     207      379172 :     return timer;
     208             : }
     209             : 
     210      379172 : void TimerManager::AddTimer(Timer *timer) {
     211      379172 :     std::scoped_lock lock(mutex_);
     212      379172 :     timer_ref_.insert(TimerPtr(timer));
     213             : 
     214      758344 :     return;
     215      379172 : }
     216             : 
     217             : //
     218             : // Delete a timer object from the data base, by removing the intrusive
     219             : // reference. If any other objects has a reference to this timer such as
     220             : // boost::asio, the timer object deletion is automatically deferred
     221             : //
     222      373568 : bool TimerManager::DeleteTimer(Timer *timer) {
     223      373568 :     if (!timer || timer->fired()) return false;
     224             : 
     225      361803 :     if (!timer->Cancel() && timer->IsDeleteOnCompletion())
     226           0 :         return false;
     227             : 
     228      361803 :     std::scoped_lock lock(mutex_);
     229      361803 :     timer_ref_.erase(TimerPtr(timer));
     230             : 
     231      361803 :     return true;
     232      361803 : }
     233             : 
     234             : // Get timer's already elapsed time in milliseconds.
     235         731 : int64_t Timer::GetElapsedTime() const {
     236         731 :     std::scoped_lock lock(mutex_);
     237             :     int64_t elapsed;
     238             : 
     239             : #if __cplusplus >= 201103L
     240         731 :     elapsed = std::chrono::nanoseconds(impl_->expires_from_now()).count();
     241             : #else
     242             :     elapsed = boost::chrono::nanoseconds(impl_->expires_from_now()).count();
     243             : #endif
     244             : 
     245         731 :     elapsed = time_ - elapsed / 1000000; // Convert nanoseconds to milliseconds.
     246         731 :     if (elapsed < 0)
     247           0 :         elapsed = 0;
     248         731 :     return elapsed;
     249         731 : }

Generated by: LCOV version 1.14