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