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