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 20127 : EventManager::EventManager() : shutdown_(false), running_(false) { 16 20127 : } 17 : 18 15522 : void EventManager::Shutdown() { 19 15522 : shutdown_ = true; 20 15522 : io_service_.stop(); 21 15522 : } 22 : 23 15141 : void EventManager::Run() { 24 15141 : Lock(); 25 15141 : io_context::work work(io_service_); 26 : do { 27 28906 : if (shutdown_) break; 28 13765 : boost::system::error_code ec; 29 : try { 30 13765 : io_service_.run(ec); 31 13765 : 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 13765 : } while (true); 47 15141 : Unlock(); 48 15141 : } 49 : 50 118172 : size_t EventManager::RunOnce() { 51 118172 : Lock(); 52 118172 : if (shutdown_) { 53 0 : Unlock(); 54 0 : return 0; 55 : } 56 118172 : boost::system::error_code err; 57 118172 : size_t res = io_service_.run_one(err); 58 118172 : if (res == 0) 59 0 : io_service_.reset(); 60 118172 : Unlock(); 61 118172 : 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 133757 : void EventManager::Lock() { 83 133757 : tbb::spin_mutex::scoped_lock lock(guard_running_); 84 133757 : assert(io_mutex_.try_lock()); 85 133757 : running_ = true; 86 133757 : } 87 : 88 133757 : void EventManager::Unlock() { 89 133757 : tbb::spin_mutex::scoped_lock lock(guard_running_); 90 133757 : io_mutex_.unlock(); 91 133757 : running_ = false; 92 133757 : }