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