Line data Source code
1 : /* 2 : * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. 3 : */ 4 : 5 : #include <string> 6 : 7 : #include "io/event_manager.h" 8 : #include "base/logging.h" 9 : #include "io/io_log.h" 10 : 11 : using boost::asio::io_context; 12 : 13 : SandeshTraceBufferPtr IOTraceBuf(SandeshTraceBufferCreate(IO_TRACE_BUF, 1000)); 14 : 15 20130 : EventManager::EventManager() : shutdown_(false), running_(false) { 16 20130 : } 17 : 18 15525 : void EventManager::Shutdown() { 19 15525 : shutdown_ = true; 20 15525 : io_service_.stop(); 21 15525 : } 22 : 23 15142 : void EventManager::Run() { 24 15142 : Lock(); 25 15142 : io_context::work work(io_service_); 26 : do { 27 24934 : if (shutdown_) break; 28 9792 : boost::system::error_code ec; 29 : try { 30 9792 : io_service_.run(ec); 31 9792 : if (ec) { 32 0 : EVENT_MANAGER_LOG_ERROR("io_service run failed: " << 33 : ec.message()); 34 0 : break; 35 : } 36 0 : } catch (std::exception &except) { 37 0 : static std::string what = except.what(); 38 0 : EVENT_MANAGER_LOG_ERROR("Exception caught in io_service run : " << 39 : what); 40 0 : assert(false); 41 0 : } catch (...) { 42 0 : EVENT_MANAGER_LOG_ERROR("Exception caught in io_service run : " 43 : "bailing out"); 44 0 : assert(false); 45 0 : } 46 9792 : } while (true); 47 15142 : Unlock(); 48 15142 : } 49 : 50 123627 : size_t EventManager::RunOnce() { 51 123627 : Lock(); 52 123627 : if (shutdown_) { 53 0 : Unlock(); 54 0 : return 0; 55 : } 56 123627 : boost::system::error_code err; 57 123627 : size_t res = io_service_.run_one(err); 58 123627 : if (res == 0) 59 0 : io_service_.reset(); 60 123627 : Unlock(); 61 123627 : return res; 62 : } 63 : 64 444 : size_t EventManager::Poll() { 65 444 : Lock(); 66 444 : if (shutdown_) { 67 0 : Unlock(); 68 0 : return 0; 69 : } 70 444 : boost::system::error_code err; 71 444 : size_t res = io_service_.poll(err); 72 444 : if (res == 0) 73 242 : io_service_.reset(); 74 444 : Unlock(); 75 444 : return res; 76 : } 77 : 78 4 : bool EventManager::IsRunning() const { 79 4 : return running_; 80 : } 81 : 82 139213 : void EventManager::Lock() { 83 139213 : tbb::spin_mutex::scoped_lock lock(guard_running_); 84 139213 : assert(io_mutex_.try_lock()); 85 139213 : running_ = true; 86 139213 : } 87 : 88 139213 : void EventManager::Unlock() { 89 139213 : tbb::spin_mutex::scoped_lock lock(guard_running_); 90 139213 : io_mutex_.unlock(); 91 139213 : running_ = false; 92 139213 : }