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 10 : StatsCollector(int task_id, int32_t instance, boost::asio::io_service &io, 24 10 : int exp, std::string timer_name) : run_counter_(0), 25 10 : timer_(TimerManager::CreateTimer(io, timer_name.c_str(), 26 : task_id, instance)), 27 20 : timer_restart_trigger_(new TaskTrigger( 28 : boost::bind(&StatsCollector::RestartTimer, this), 29 10 : task_id, instance)), 30 10 : expiry_time_(exp) { 31 10 : }; 32 : 33 10 : virtual ~StatsCollector() { 34 10 : Shutdown(); 35 10 : timer_restart_trigger_->Reset(); 36 10 : delete timer_restart_trigger_; 37 10 : } 38 : 39 10 : void InitDone() { 40 10 : timer_->Start(expiry_time_, 41 : boost::bind(&StatsCollector::TimerExpiry, this)); 42 10 : } 43 : 44 : virtual bool Run() = 0; 45 20 : void Shutdown() { 46 20 : if (timer_) { 47 10 : timer_->Cancel(); 48 10 : TimerManager::DeleteTimer(timer_); 49 10 : timer_ = NULL; 50 : } 51 20 : } 52 : 53 : // To be used by UT only 54 124 : void TestStartStopTimer (bool stop) { 55 124 : if (timer_ != NULL) { 56 124 : if (stop) { 57 : // UTs call TestStartStopTimer() without exclusion. Hence, 58 : // timer->Cancel() can potentially fail. Retry in that case 59 54 : int i = 0; 60 54 : for (; i < 8; i++) { 61 54 : if (timer_->Cancel()) 62 54 : break; 63 0 : usleep(1000); 64 : } 65 54 : assert(i < 8); 66 : } else { 67 70 : timer_->Start(expiry_time_, 68 : boost::bind(&StatsCollector::TimerExpiry, this)); 69 : } 70 : } 71 124 : } 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 254 : bool TimerExpiry() { 95 254 : Run(); 96 : /* Return true to request auto-restart of timer */ 97 254 : 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_