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 : #ifndef vnsw_agent_stats_coll_h_ 7 : #define vnsw_agent_stats_coll_h_ 8 : 9 : #include <boost/asio.hpp> 10 : #include <map> 11 : #include "base/timer.h" 12 : #include "base/queue_task.h" 13 : 14 : //The base class for statistics collector classes. 15 : //Defines Timer functionality to trigger the stats collection events 16 : class StatsCollector { 17 : public: 18 : enum StatsInstance { 19 : FlowStatsCollector, 20 : AgentStatsCollector, 21 : }; 22 : 23 5 : StatsCollector(int task_id, int32_t instance, boost::asio::io_service &io, 24 5 : int exp, std::string timer_name) : run_counter_(0), 25 5 : timer_(TimerManager::CreateTimer(io, timer_name.c_str(), 26 : task_id, instance)), 27 10 : timer_restart_trigger_(new TaskTrigger( 28 : boost::bind(&StatsCollector::RestartTimer, this), 29 5 : task_id, instance)), 30 5 : expiry_time_(exp) { 31 5 : }; 32 : 33 5 : virtual ~StatsCollector() { 34 5 : Shutdown(); 35 5 : timer_restart_trigger_->Reset(); 36 5 : delete timer_restart_trigger_; 37 5 : } 38 : 39 5 : void InitDone() { 40 5 : timer_->Start(expiry_time_, 41 : boost::bind(&StatsCollector::TimerExpiry, this)); 42 5 : } 43 : 44 : virtual bool Run() = 0; 45 10 : void Shutdown() { 46 10 : if (timer_) { 47 5 : timer_->Cancel(); 48 5 : TimerManager::DeleteTimer(timer_); 49 5 : timer_ = NULL; 50 : } 51 10 : } 52 : 53 : // To be used by UT only 54 52 : void TestStartStopTimer (bool stop) { 55 52 : if (timer_ != NULL) { 56 52 : if (stop) { 57 : // UTs call TestStartStopTimer() without exclusion. Hence, 58 : // timer->Cancel() can potentially fail. Retry in that case 59 18 : int i = 0; 60 18 : for (; i < 8; i++) { 61 18 : if (timer_->Cancel()) 62 18 : break; 63 0 : usleep(1000); 64 : } 65 18 : assert(i < 8); 66 : } else { 67 34 : timer_->Start(expiry_time_, 68 : boost::bind(&StatsCollector::TimerExpiry, this)); 69 : } 70 : } 71 52 : } 72 : 73 8 : int expiry_time() const { return expiry_time_; } 74 2 : void set_expiry_time(int time) { 75 2 : if (time != expiry_time_) { 76 2 : expiry_time_ = time; 77 2 : timer_restart_trigger_->Set(); 78 : } 79 2 : } 80 : 81 : void RescheduleTimer(int time) { 82 : timer_->Reschedule(time); 83 : } 84 : 85 : int run_counter_; //used only in UT code 86 : 87 : private: 88 2 : bool RestartTimer() { 89 2 : timer_->Cancel(); 90 2 : timer_->Start(expiry_time_, 91 : boost::bind(&StatsCollector::TimerExpiry, this)); 92 2 : return true; 93 : } 94 160 : bool TimerExpiry() { 95 160 : Run(); 96 : /* Return true to request auto-restart of timer */ 97 160 : return true; 98 : } 99 : 100 : Timer *timer_; 101 : TaskTrigger *timer_restart_trigger_; 102 : int expiry_time_; 103 : DISALLOW_COPY_AND_ASSIGN(StatsCollector); 104 : }; 105 : 106 : #endif // vnsw_agent_stats_coll_h_