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