From 1d6ec2a5bc5c8693d459d746c36ff39b72b14c6c Mon Sep 17 00:00:00 2001 From: Yang Liming Date: Fri, 6 Nov 2026 17:29:41 +0800 Subject: [PATCH 1/2] Add polling mode and callback registration to EventDispatcher Add event_dispatcher_use_polling for non-blocking epoll/kqueue polling while preserving the bthread model and existing urgent/background scheduling switch. Support per-tag callback registration with dispatcher-local contexts, initialization rollback, and synchronous unregistration. Use atomic stop and task identifiers and safely acknowledge pending callback commands during shutdown. Add tests for idle polling, tag isolation, callback lifecycle, concurrent shutdown, and TCP urgent/background processing. Validation: git diff --check passed. Build and unit tests remain blocked by missing Protobuf dependencies and a Google Test download timeout. --- src/brpc/event_dispatcher.cpp | 266 ++++++++++- src/brpc/event_dispatcher.h | 100 ++++- src/brpc/event_dispatcher_epoll.cpp | 53 ++- src/brpc/event_dispatcher_kqueue.cpp | 52 ++- test/brpc_event_dispatcher_unittest.cpp | 561 ++++++++++++++++++++++++ 5 files changed, 962 insertions(+), 70 deletions(-) diff --git a/src/brpc/event_dispatcher.cpp b/src/brpc/event_dispatcher.cpp index bc9ec6ab8b..e2361e638e 100644 --- a/src/brpc/event_dispatcher.cpp +++ b/src/brpc/event_dispatcher.cpp @@ -16,6 +16,8 @@ // under the License. #include // `atexit` +#include +#include #include // DEFINE_int32 #include "butil/compat.h" #include "butil/fd_utility.h" // make_close_on_exec @@ -23,6 +25,8 @@ #include "butil/third_party/murmurhash3/murmurhash3.h"// fmix32 #include "bvar/latency_recorder.h" // bvar::LatencyRecorder #include "bthread/bthread.h" // bthread_start_background +#include "bthread/countdown_event.h" +#include "bthread/mutex.h" #include "bthread/task_group.h" // TaskGroup::address_meta #include "brpc/event_dispatcher.h" @@ -32,7 +36,10 @@ DECLARE_int32(event_dispatcher_num); namespace brpc { DEFINE_bool(event_dispatcher_edisp_unsched, false, - "Disable event dispatcher schedule"); + "Enqueue transport input processing without an urgent bthread switch"); +DEFINE_bool(event_dispatcher_use_polling, false, + "Busy poll epoll/kqueue without sleeping. Set before dispatchers " + "start; urgent/background input scheduling remains independent."); DEFINE_bool(usercode_in_pthread, false, "Call user's callback in pthreads, use bthreads otherwise"); @@ -43,46 +50,171 @@ static EventDispatcher* g_edisp = nullptr; static bvar::LatencyRecorder* g_edisp_read_lantency = nullptr; static bvar::LatencyRecorder* g_edisp_write_lantency = nullptr; static pthread_once_t g_edisp_once = PTHREAD_ONCE_INIT; +static int g_edisp_ntags = 0; +static int g_edisp_num = 0; + +struct EventDispatcherPollingState { + EventDispatcherPollingState(const PollingCallbacks& cb, + uint64_t generation) + : callbacks(cb), id(generation) {} + const PollingCallbacks callbacks; + const uint64_t id; +}; + +struct EventDispatcherPollingCommand { + explicit EventDispatcherPollingCommand(EventDispatcherPollingState* s) + : state(s), rc(0) {} + EventDispatcherPollingState* state; + int rc; + bthread::CountdownEvent done; +}; + +struct EventDispatcherPollingGroup { + // Registration may suspend its caller while dispatchers acknowledge. A + // pthread mutex held across this wait could deadlock the worker pool. + bthread::Mutex mutex; + uint64_t next_id = 0; + std::unique_ptr state; +}; +static EventDispatcherPollingGroup* g_polling_groups = nullptr; + +bool EventDispatcher::IsDispatcherThread() const { + const bthread_t tid = _tid.load(std::memory_order_acquire); + return tid != INVALID_BTHREAD && bthread_self() == tid; +} + +int EventDispatcher::SetPollingCallbacks(EventDispatcherPollingState* state) { + EventDispatcherPollingCommand command(state); + { + BAIDU_SCOPED_LOCK(_polling_command_mutex); + // A dispatcher that failed to start has no thread to acknowledge a + // command and will never reach FinishPolling(). + if (_polling_finished || + _tid.load(std::memory_order_acquire) == INVALID_BTHREAD) { + return state ? ESHUTDOWN : 0; + } + if (state && _stop.load(std::memory_order_acquire)) { + return ESHUTDOWN; + } + CHECK(_polling_command.load(std::memory_order_relaxed) == nullptr); + _polling_command.store(&command, std::memory_order_release); + } + // Only polling dispatchers accept commands, so no wakeup syscall is needed. + CHECK_EQ(0, command.done.wait()); + return command.rc; +} + +void EventDispatcher::ReleasePollingCallbacks() { + if (_polling_state) { + if (_polling_state->callbacks.release_fn) { + _polling_state->callbacks.release_fn(_polling_context); + } + _polling_state = nullptr; + _polling_context.user_data = nullptr; + } +} + +void EventDispatcher::ProcessPollingCommand() { + // Run() only probes the pointer with a relaxed load. Acquire the command + // published by SetPollingCallbacks() before accessing its contents. + EventDispatcherPollingCommand* command = + _polling_command.exchange(nullptr, std::memory_order_acquire); + if (!command) { + return; + } + ReleasePollingCallbacks(); + if (command->state) { + if (_stop.load(std::memory_order_acquire)) { + command->rc = ESHUTDOWN; + } else { + _polling_state = command->state; + _polling_context.tag = bthread_self_tag(); + _polling_context.dispatcher_index = _priority_index; + if (_polling_state->callbacks.init_fn) { + command->rc = + _polling_state->callbacks.init_fn(_polling_context); + if (command->rc != 0) { + if (command->rc < 0) { + command->rc = EINVAL; + } + ReleasePollingCallbacks(); + } + } + } + } + // signal() may resume the caller, which destroys the stack command. + command->done.signal(); +} + +void EventDispatcher::RunPollingCallback() { + if (_polling_state && !_stop.load(std::memory_order_acquire)) { + _polling_state->callbacks.poll_fn(_polling_context); + } +} + +void EventDispatcher::FinishPolling() { + // Release first: a concurrent unregister must not return while release_fn + // still uses the registration. Then reject/acknowledge pending commands. + ReleasePollingCallbacks(); + EventDispatcherPollingCommand* command; + { + BAIDU_SCOPED_LOCK(_polling_command_mutex); + _polling_finished = true; + command = _polling_command.exchange(nullptr, std::memory_order_acquire); + if (command) { + command->rc = command->state ? ESHUTDOWN : 0; + } + } + // Acknowledgement may switch bthreads; never hold a pthread mutex here. + if (command) { + command->done.signal(); + } +} bool EventDispatcherUnsched() { return FLAGS_event_dispatcher_edisp_unsched; } static void StopAndJoinGlobalDispatchers() { - for (int i = 0; i < FLAGS_task_group_ntags; ++i) { - for (int j = 0; j < FLAGS_event_dispatcher_num; ++j) { - g_edisp[i * FLAGS_event_dispatcher_num + j].Stop(); - g_edisp[i * FLAGS_event_dispatcher_num + j].Join(); - } + for (int i = 0; i < g_edisp_ntags * g_edisp_num; ++i) { + g_edisp[i].Stop(); + } + for (int i = 0; i < g_edisp_ntags * g_edisp_num; ++i) { + g_edisp[i].Join(); } } void InitializeGlobalDispatchers() { + // These options define array sizes and fd ownership and are startup-only. + g_edisp_ntags = FLAGS_task_group_ntags; + g_edisp_num = FLAGS_event_dispatcher_num; + CHECK_GT(g_edisp_ntags, 0); + CHECK_GT(g_edisp_num, 0); // A dispatcher may switch bthreads through `bthread_start_urgent()` // while handling events. Waiting in `epoll_wait`/`kevent` blocks its worker - // pthread. Reserve one extra worker per dispatcher to compensate for that - // blocked capacity and preserve the normal concurrency configured by + // pthread. Busy polling also occupies a worker. Reserve one extra worker + // per dispatcher to preserve the normal concurrency configured by // `ServerOptions.num_threads` or `-bthread_concurrency`. // Without reservations, `event_dispatcher_num >= num_threads` can leave // all workers blocked in dispatcher waits, preventing other work. - for (int i = 0; i < FLAGS_task_group_ntags; ++i) { - bthread_tag_t tag = (BTHREAD_TAG_DEFAULT + i) % FLAGS_task_group_ntags; - int rc = bthread_add_reserved_concurrency_by_tag( - FLAGS_event_dispatcher_num, tag); - CHECK_EQ(0, rc) << "Fail to reserve " << FLAGS_event_dispatcher_num + for (int i = 0; i < g_edisp_ntags; ++i) { + bthread_tag_t tag = (BTHREAD_TAG_DEFAULT + i) % g_edisp_ntags; + int rc = bthread_add_reserved_concurrency_by_tag(g_edisp_num, tag); + CHECK_EQ(0, rc) << "Fail to reserve " << g_edisp_num << " workers for event dispatchers of tag=" << tag << ": " << berror(rc); } g_edisp_read_lantency = new bvar::LatencyRecorder("event_dispatcher_read"); g_edisp_write_lantency = new bvar::LatencyRecorder("event_dispatcher_write"); - g_edisp = new EventDispatcher[FLAGS_task_group_ntags * FLAGS_event_dispatcher_num]; - for (int i = 0; i < FLAGS_task_group_ntags; ++i) { - for (int j = 0; j < FLAGS_event_dispatcher_num; ++j) { + g_edisp = new EventDispatcher[g_edisp_ntags * g_edisp_num]; + g_polling_groups = new EventDispatcherPollingGroup[g_edisp_ntags]; + for (int i = 0; i < g_edisp_ntags; ++i) { + for (int j = 0; j < g_edisp_num; ++j) { bthread_attr_t attr = FLAGS_usercode_in_pthread ? BTHREAD_ATTR_PTHREAD : BTHREAD_ATTR_NORMAL; - attr.tag = (BTHREAD_TAG_DEFAULT + i) % FLAGS_task_group_ntags; - g_edisp[i * FLAGS_event_dispatcher_num + j].set_priority_index(j); - CHECK_EQ(0, g_edisp[i * FLAGS_event_dispatcher_num + j].Start(&attr)); + attr.tag = (BTHREAD_TAG_DEFAULT + i) % g_edisp_ntags; + g_edisp[i * g_edisp_num + j].set_priority_index(j); + CHECK_EQ(0, g_edisp[i * g_edisp_num + j].Start(&attr)); } } // This atexit is will be run before g_task_control.stop() because above @@ -92,11 +224,101 @@ void InitializeGlobalDispatchers() { EventDispatcher& GetGlobalEventDispatcher(int fd, bthread_tag_t tag) { pthread_once(&g_edisp_once, InitializeGlobalDispatchers); - if (FLAGS_task_group_ntags == 1 && FLAGS_event_dispatcher_num == 1) { + if (g_edisp_ntags == 1 && g_edisp_num == 1) { return g_edisp[0]; } - int index = butil::fmix32(fd) % FLAGS_event_dispatcher_num; - return g_edisp[tag * FLAGS_event_dispatcher_num + index]; + int index = butil::fmix32(fd) % g_edisp_num; + return g_edisp[tag * g_edisp_num + index]; +} + +static bool IsGlobalDispatcherThread() { + for (int i = 0; i < g_edisp_ntags * g_edisp_num; ++i) { + if (g_edisp[i].IsDispatcherThread()) { + return true; + } + } + return false; +} + +int RegisterPollingCallbacksWithTag(bthread_tag_t tag, + const PollingCallbacks& callbacks, + PollingRegistration* registration) { + if (!registration || !callbacks.poll_fn || tag < 0 || + tag >= FLAGS_task_group_ntags) { + errno = EINVAL; + return -1; + } + pthread_once(&g_edisp_once, InitializeGlobalDispatchers); + if (IsGlobalDispatcherThread()) { + errno = EDEADLK; + return -1; + } + if (tag >= g_edisp_ntags) { + errno = EINVAL; + return -1; + } + EventDispatcherPollingGroup& group = g_polling_groups[tag]; + std::unique_lock lock(group.mutex); + if (group.state) { + errno = EEXIST; + return -1; + } + EventDispatcher* dispatchers = g_edisp + tag * g_edisp_num; + if (!dispatchers[0].use_polling()) { + errno = EPERM; + return -1; + } + std::unique_ptr state( + new EventDispatcherPollingState(callbacks, ++group.next_id)); + for (int i = 0; i < g_edisp_num; ++i) { + const int rc = dispatchers[i].SetPollingCallbacks(state.get()); + if (rc != 0) { + for (int j = 0; j < i; ++j) { + CHECK_EQ(0, dispatchers[j].SetPollingCallbacks(nullptr)); + } + // Captured objects may reenter registration when destroyed. + lock.unlock(); + state.reset(); + errno = rc; + return -1; + } + } + registration->_tag = tag; + registration->_id = state->id; + group.state = std::move(state); + return 0; +} + +int UnregisterPollingCallbacks(PollingRegistration registration) { + if (!registration._id || registration._tag < 0) { + errno = EINVAL; + return -1; + } + pthread_once(&g_edisp_once, InitializeGlobalDispatchers); + if (IsGlobalDispatcherThread()) { + errno = EDEADLK; + return -1; + } + if (registration._tag >= g_edisp_ntags) { + errno = EINVAL; + return -1; + } + EventDispatcherPollingGroup& group = g_polling_groups[registration._tag]; + std::unique_lock lock(group.mutex); + if (!group.state || group.state->id != registration._id) { + errno = ENOENT; + return -1; + } + EventDispatcher* dispatchers = + g_edisp + registration._tag * g_edisp_num; + for (int i = 0; i < g_edisp_num; ++i) { + CHECK_EQ(0, dispatchers[i].SetPollingCallbacks(nullptr)); + } + // Clear the registration under the lock, but destroy the callbacks after + // unlocking: a captured object's destructor may reenter on the same tag. + auto state = std::move(group.state); + lock.unlock(); + return 0; } int IOEventData::OnCreated(const IOEventDataOptions& options) { diff --git a/src/brpc/event_dispatcher.h b/src/brpc/event_dispatcher.h index 33f3537ebb..aef1090a24 100644 --- a/src/brpc/event_dispatcher.h +++ b/src/brpc/event_dispatcher.h @@ -19,7 +19,10 @@ #ifndef BRPC_EVENT_DISPATCHER_H #define BRPC_EVENT_DISPATCHER_H +#include +#include #include // DECLARE_bool +#include "butil/synchronization/lock.h" #include "butil/macros.h" // DISALLOW_COPY_AND_ASSIGN #include "bthread/types.h" // bthread_t, bthread_attr_t #include "brpc/versioned_ref_with_id.h" @@ -28,6 +31,68 @@ namespace brpc { DECLARE_bool(event_dispatcher_edisp_unsched); +DECLARE_bool(event_dispatcher_use_polling); + +// Each dispatcher owns a separate context. A bthread may migrate between +// worker pthreads: this context is dispatcher-local, not pthread-local. +struct PollingContext { + bthread_tag_t tag = BTHREAD_TAG_INVALID; + int dispatcher_index = -1; + void* user_data = nullptr; +}; + +struct PollingCallbacks { + // Return 0 on success or a positive errno value on failure. + std::function init_fn; + // Called inline after each event batch, including batches with no events. + std::function poll_fn; + // Also called after failed initialization to clean up partial resources. + std::function release_fn; +}; + +// An opaque token. Copies refer to the same registration; a stale token cannot +// unregister a newer registration on the same tag. +class PollingRegistration { +public: + PollingRegistration() : _tag(BTHREAD_TAG_INVALID), _id(0) {} + +private: + friend int RegisterPollingCallbacksWithTag( + bthread_tag_t, const PollingCallbacks&, PollingRegistration*); + friend int UnregisterPollingCallbacks(PollingRegistration); + bthread_tag_t _tag; + uint64_t _id; +}; + +// Requires event_dispatcher_use_polling to be set before dispatchers start. +// Register one callback set on all dispatchers of the tag, even if they have +// already started. Success requires initialization on every dispatcher. +// A dispatcher can call poll_fn after its own init_fn succeeds (or once the +// callbacks are installed if init_fn is absent), before other dispatchers +// finish initializing and before this function returns. +// +// On failure, callbacks installed by this attempt are stopped and their +// contexts are released before returning, but events already consumed by +// poll_fn and other side effects are not rolled back. To prevent consumption +// on a failed attempt, gate it in poll_fn with a synchronized flag that starts +// disabled and is enabled only after this function returns 0. Otherwise, +// account for any events already consumed before retrying. +// +// Callbacks are serial per dispatcher, but concurrent across dispatchers. They +// must not block, throw, or synchronously register/unregister callbacks (EDEADLK). +// poll_fn must be non-null. Returns 0 on success, -1 with errno on failure. +// Duplicate registration fails with EEXIST. A polling dispatcher that did not +// start or cannot accept an install command causes ESHUTDOWN. +int RegisterPollingCallbacksWithTag(bthread_tag_t tag, + const PollingCallbacks& callbacks, + PollingRegistration* registration); + +// On success, all callbacks have stopped and release_fn has completed. This +// does not stop dispatchers or TCP traffic. Returns 0 or -1 with errno. +int UnregisterPollingCallbacks(PollingRegistration registration); + +struct EventDispatcherPollingState; +struct EventDispatcherPollingCommand; // Unique identifier of a IOEventData. // Users shall store EventDataId instead of EventData and call EventData::Address() @@ -97,6 +162,9 @@ class EventDispatcher { friend class Socket; friend class rdma::RdmaEndpoint; template friend class IOEvent; +friend int RegisterPollingCallbacksWithTag( + bthread_tag_t, const PollingCallbacks&, PollingRegistration*); +friend int UnregisterPollingCallbacks(PollingRegistration); public: EventDispatcher(); @@ -111,6 +179,12 @@ template friend class IOEvent; // True iff this dispatcher is running in a bthread bool Running() const; + // Waiting policy is captured by Start(), independently of the urgent / + // background input-processing policy controlled by EventDispatcherUnsched. + bool use_polling() const { return _use_polling; } + + bool IsDispatcherThread() const; + // Stop bthread of this dispatcher. void Stop(); @@ -148,6 +222,15 @@ template friend class IOEvent; // Thread entry. void Run(); + // Registration is serialized outside the hot path. Only the dispatcher + // modifies its callbacks/context; commands synchronously acknowledge this. + int SetPollingCallbacks(EventDispatcherPollingState* state); + // Slow path: called only when Run() observes a pending command. + void ProcessPollingCommand(); + void RunPollingCallback(); + void ReleasePollingCallbacks(); + void FinishPolling(); + // Remove the file descriptor `fd' from epoll. int RemoveConsumer(int fd); @@ -179,26 +262,33 @@ template friend class IOEvent; // The epoll/kqueue fd to watch events. int _event_dispatcher_fd; - // false unless Stop() is called. - volatile bool _stop; + // false unless Stop() is called. Polling must not rely on syscall fences. + std::atomic _stop; // identifier of hosting bthread - bthread_t _tid; + std::atomic _tid; // The attribute of bthreads calling user callbacks. bthread_attr_t _thread_attr; // Pipe fds to wakeup EventDispatcher from `epoll_wait' in order to quit - int _wakeup_fds[2]; + int _wakeup_fds[2]{-1, -1}; int _priority_index{-1}; + + bool _use_polling{false}; + butil::Mutex _polling_command_mutex; + bool _polling_finished{false}; + std::atomic _polling_command{nullptr}; + EventDispatcherPollingState* _polling_state{nullptr}; + PollingContext _polling_context; }; EventDispatcher& GetGlobalEventDispatcher(int fd, bthread_tag_t tag); // Unified unsched switch for transport layer. // false -> urgent start (foreground scheduling before caller continues), -// true -> background start (allowing schedule away). +// true -> background start (enqueue input processing without switching away). bool EventDispatcherUnsched(); // IOEvent class manages the IO events of a file descriptor conveniently. diff --git a/src/brpc/event_dispatcher_epoll.cpp b/src/brpc/event_dispatcher_epoll.cpp index 1a3e74ef8e..9bd9e4db7d 100644 --- a/src/brpc/event_dispatcher_epoll.cpp +++ b/src/brpc/event_dispatcher_epoll.cpp @@ -34,11 +34,10 @@ EventDispatcher::EventDispatcher() } CHECK_EQ(0, butil::make_close_on_exec(_event_dispatcher_fd)); - _wakeup_fds[0] = -1; - _wakeup_fds[1] = -1; if (pipe(_wakeup_fds) != 0) { PLOG(FATAL) << "Fail to create pipe"; - return; + close(_event_dispatcher_fd); + _event_dispatcher_fd = -1; } } @@ -49,24 +48,25 @@ EventDispatcher::~EventDispatcher() { close(_event_dispatcher_fd); _event_dispatcher_fd = -1; } - if (_wakeup_fds[0] > 0) { + if (_wakeup_fds[0] >= 0) { close(_wakeup_fds[0]); close(_wakeup_fds[1]); } } int EventDispatcher::Start(const bthread_attr_t* thread_attr) { - if (_event_dispatcher_fd < 0) { - LOG(FATAL) << "epoll was not created"; - return -1; - } - if (_tid != 0) { - LOG(FATAL) << "Already started this dispatcher(" << this + LOG(FATAL) << "Already started this dispatcher(" << this << ") in bthread=" << _tid; return -1; } + _use_polling = FLAGS_event_dispatcher_use_polling; + if (_event_dispatcher_fd < 0) { + LOG(FATAL) << "EventDispatcher fd setup failed"; + return -1; + } + // Set _thread_attr before creating epoll thread to make sure // everyting seems sane to the thread. if (thread_attr) { @@ -85,11 +85,13 @@ int EventDispatcher::Start(const bthread_attr_t* thread_attr) { // when the older comlog (e.g. 3.1.85) calls com_openlog_r(). Since this // is also a potential issue for consumer threads, using the same attr // should be a reasonable solution. - int rc = bthread_start_background(&_tid, &epoll_thread_attr, RunThis, this); + bthread_t tid; + int rc = bthread_start_background(&tid, &epoll_thread_attr, RunThis, this); if (rc) { LOG(FATAL) << "Fail to create epoll thread: " << berror(rc); return -1; } + _tid.store(tid, std::memory_order_release); return 0; } @@ -98,7 +100,7 @@ bool EventDispatcher::Running() const { } void EventDispatcher::Stop() { - _stop = true; + _stop.store(true, std::memory_order_release); if (_event_dispatcher_fd >= 0) { epoll_event evt = { EPOLLOUT, { nullptr } }; @@ -107,9 +109,10 @@ void EventDispatcher::Stop() { } void EventDispatcher::Join() { - if (_tid) { - bthread_join(_tid, nullptr); - _tid = 0; + const bthread_t tid = _tid.load(std::memory_order_acquire); + if (tid) { + bthread_join(tid, nullptr); + _tid.store(0, std::memory_order_release); } } @@ -201,21 +204,23 @@ void* EventDispatcher::RunThis(void* arg) { } void EventDispatcher::Run() { - while (!_stop) { + while (!_stop.load(std::memory_order_acquire)) { + if (_use_polling && BAIDU_UNLIKELY( + _polling_command.load(std::memory_order_relaxed) != nullptr)) { + ProcessPollingCommand(); + } epoll_event e[32]; #ifdef BRPC_ADDITIONAL_EPOLL // Performance downgrades in examples. int n = epoll_wait(_event_dispatcher_fd, e, ARRAY_SIZE(e), 0); - if (n == 0) { + if (n == 0 && !_use_polling) { n = epoll_wait(_event_dispatcher_fd, e, ARRAY_SIZE(e), -1); } #else - const int n = epoll_wait(_event_dispatcher_fd, e, ARRAY_SIZE(e), -1); + const int n = epoll_wait(_event_dispatcher_fd, e, ARRAY_SIZE(e), + _use_polling ? 0 : -1); #endif - if (_stop) { - // epoll_ctl/epoll_wait should have some sort of memory fencing - // guaranteeing that we(after epoll_wait) see _stop set before - // epoll_ctl. + if (_stop.load(std::memory_order_acquire)) { break; } if (n < 0) { @@ -246,7 +251,11 @@ void EventDispatcher::Run() { (*g_edisp_write_lantency) << (butil::cpuwide_time_us() - start_us); } } + if (_use_polling) { + RunPollingCallback(); + } } + FinishPolling(); } } // namespace brpc diff --git a/src/brpc/event_dispatcher_kqueue.cpp b/src/brpc/event_dispatcher_kqueue.cpp index 8bec41aa8f..eb838aecea 100644 --- a/src/brpc/event_dispatcher_kqueue.cpp +++ b/src/brpc/event_dispatcher_kqueue.cpp @@ -34,11 +34,10 @@ EventDispatcher::EventDispatcher() } CHECK_EQ(0, butil::make_close_on_exec(_event_dispatcher_fd)); - _wakeup_fds[0] = -1; - _wakeup_fds[1] = -1; if (pipe(_wakeup_fds) != 0) { PLOG(FATAL) << "Fail to create pipe"; - return; + close(_event_dispatcher_fd); + _event_dispatcher_fd = -1; } } @@ -49,24 +48,25 @@ EventDispatcher::~EventDispatcher() { close(_event_dispatcher_fd); _event_dispatcher_fd = -1; } - if (_wakeup_fds[0] > 0) { + if (_wakeup_fds[0] >= 0) { close(_wakeup_fds[0]); close(_wakeup_fds[1]); } } int EventDispatcher::Start(const bthread_attr_t* thread_attr) { - if (_event_dispatcher_fd < 0) { - LOG(FATAL) << "kqueue was not created"; - return -1; - } - if (_tid != 0) { - LOG(FATAL) << "Already started this dispatcher(" << this + LOG(FATAL) << "Already started this dispatcher(" << this << ") in bthread=" << _tid; return -1; } + _use_polling = FLAGS_event_dispatcher_use_polling; + if (_event_dispatcher_fd < 0) { + LOG(FATAL) << "EventDispatcher fd setup failed"; + return -1; + } + // Set _thread_attr before creating kqueue thread to make sure // everyting seems sane to the thread. if (thread_attr) { @@ -85,12 +85,14 @@ int EventDispatcher::Start(const bthread_attr_t* thread_attr) { // when the older comlog (e.g. 3.1.85) calls com_openlog_r(). Since this // is also a potential issue for consumer threads, using the same attr // should be a reasonable solution. + bthread_t tid; int rc = bthread_start_background( - &_tid, &kqueue_thread_attr, RunThis, this); + &tid, &kqueue_thread_attr, RunThis, this); if (rc) { LOG(FATAL) << "Fail to create kqueue thread: " << berror(rc); return -1; } + _tid.store(tid, std::memory_order_release); return 0; } @@ -99,7 +101,7 @@ bool EventDispatcher::Running() const { } void EventDispatcher::Stop() { - _stop = true; + _stop.store(true, std::memory_order_release); if (_event_dispatcher_fd >= 0) { struct kevent kqueue_event; @@ -110,9 +112,10 @@ void EventDispatcher::Stop() { } void EventDispatcher::Join() { - if (_tid) { - bthread_join(_tid, nullptr); - _tid = 0; + const bthread_t tid = _tid.load(std::memory_order_acquire); + if (tid) { + bthread_join(tid, nullptr); + _tid.store(0, std::memory_order_release); } } @@ -191,13 +194,16 @@ void* EventDispatcher::RunThis(void* arg) { } void EventDispatcher::Run() { - while (!_stop) { + const timespec no_wait = {0, 0}; + while (!_stop.load(std::memory_order_acquire)) { + if (_use_polling && BAIDU_UNLIKELY( + _polling_command.load(std::memory_order_relaxed) != nullptr)) { + ProcessPollingCommand(); + } struct kevent e[32]; - int n = kevent(_event_dispatcher_fd, nullptr, 0, e, ARRAY_SIZE(e), nullptr); - if (_stop) { - // EV_SET/kevent should have some sort of memory fencing - // guaranteeing that we(after kevent) see _stop set before - // EV_SET + int n = kevent(_event_dispatcher_fd, nullptr, 0, e, ARRAY_SIZE(e), + _use_polling ? &no_wait : nullptr); + if (_stop.load(std::memory_order_acquire)) { break; } if (n < 0) { @@ -226,7 +232,11 @@ void EventDispatcher::Run() { (*g_edisp_write_lantency) << (butil::cpuwide_time_us() - start_us); } } + if (_use_polling) { + RunPollingCallback(); + } } + FinishPolling(); } } // namespace brpc diff --git a/test/brpc_event_dispatcher_unittest.cpp b/test/brpc_event_dispatcher_unittest.cpp index 1825fe296d..969ec6d097 100644 --- a/test/brpc_event_dispatcher_unittest.cpp +++ b/test/brpc_event_dispatcher_unittest.cpp @@ -19,8 +19,12 @@ // Date: Sun Jul 13 15:04:18 CST 2014 +#include #include +#include +#include #include +#include #include #include #include @@ -28,6 +32,8 @@ #include "gperftools_helper.h" #include "butil/time.h" #include "butil/macros.h" +#include "butil/processor.h" +#include "butil/fd_guard.h" #include "butil/fd_utility.h" #include "butil/memory/scope_guard.h" #include "bthread/bthread.h" @@ -126,6 +132,506 @@ TEST(EventDispatcherDeathTest, max_concurrency_supports_both_initialization_orde } } +// Separate processes keep startup-only polling/tag options independent from +// the blocking-mode tests and bound any missed acknowledgement to 20 seconds. +void configure_polling_test() { + alarm(20); + FLAGS_task_group_ntags = 2; + FLAGS_event_dispatcher_num = 2; + brpc::FLAGS_event_dispatcher_use_polling = true; +} + +bool wait_for_poll_count(const std::atomic& count, int expected) { + const int64_t deadline = butil::gettimeofday_us() + 5000000; + while (count.load(std::memory_order_acquire) < expected && + butil::gettimeofday_us() < deadline) { + usleep(1000); + } + return count.load(std::memory_order_acquire) >= expected; +} + +void check_polling_callback_lifecycle() { + configure_polling_test(); + std::atomic counts[2][2]; + for (auto& tag_counts : counts) { + for (auto& count : tag_counts) { + std::atomic_init(&count, 0); + } + } + int initialized[2][2] = {}; + int released[2][2] = {}; + bthread_t tids[2][2] = {}; + brpc::PollingRegistration registrations[2]; + brpc::PollingCallbacks callbacks; + callbacks.init_fn = [&](brpc::PollingContext& ctx) { + EXPECT_EQ(ctx.tag, bthread_self_tag()); + EXPECT_TRUE(ctx.dispatcher_index >= 0 && ctx.dispatcher_index < 2); + EXPECT_EQ(nullptr, ctx.user_data); + ctx.user_data = new int(ctx.dispatcher_index); + tids[ctx.tag][ctx.dispatcher_index] = bthread_self(); + ++initialized[ctx.tag][ctx.dispatcher_index]; + return 0; + }; + callbacks.poll_fn = [&](brpc::PollingContext& ctx) { + EXPECT_EQ(tids[ctx.tag][ctx.dispatcher_index], bthread_self()); + EXPECT_EQ(ctx.dispatcher_index, *static_cast(ctx.user_data)); + counts[ctx.tag][ctx.dispatcher_index].fetch_add( + 1, std::memory_order_release); + }; + callbacks.release_fn = [&](brpc::PollingContext& ctx) { + EXPECT_EQ(tids[ctx.tag][ctx.dispatcher_index], bthread_self()); + delete static_cast(ctx.user_data); + ++released[ctx.tag][ctx.dispatcher_index]; + }; + bool active[2] = {}; + auto cleanup = butil::MakeScopeGuard([&] { + for (int tag = 0; tag < 2; ++tag) { + if (active[tag]) { + brpc::UnregisterPollingCallbacks(registrations[tag]); + } + } + }); + // Registration itself initializes idle dispatchers: no sockets are needed. + for (int tag = 0; tag < 2; ++tag) { + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag( + tag, callbacks, ®istrations[tag])); + active[tag] = true; + for (int i = 0; i < 2; ++i) { + EXPECT_EQ(1, initialized[tag][i]); + ASSERT_TRUE(wait_for_poll_count(counts[tag][i], 10)); + } + } + brpc::PollingRegistration duplicate; + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag(0, callbacks, &duplicate)); + EXPECT_EQ(EEXIST, errno); + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(registrations[0])); + active[0] = false; + int stopped_counts[2] = {counts[0][0].load(), counts[0][1].load()}; + ASSERT_TRUE(wait_for_poll_count(counts[1][0], counts[1][0].load() + 10)); + for (int i = 0; i < 2; ++i) { + EXPECT_EQ(stopped_counts[i], counts[0][i].load()); + EXPECT_EQ(1, released[0][i]); + } + // Old tokens must not unregister a newly registered callback set. + brpc::PollingRegistration replacement; + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag(0, callbacks, &replacement)); + const brpc::PollingRegistration stale = registrations[0]; + registrations[0] = replacement; + active[0] = true; + EXPECT_EQ(-1, brpc::UnregisterPollingCallbacks(stale)); + EXPECT_EQ(ENOENT, errno); + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(replacement)); + active[0] = false; + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(registrations[1])); + active[1] = false; + for (int i = 0; i < 2; ++i) { + EXPECT_EQ(2, initialized[0][i]); + EXPECT_EQ(2, released[0][i]); + EXPECT_EQ(1, released[1][i]); + } + // The dispatcher remains alive after callback removal. + EXPECT_TRUE(brpc::GetGlobalEventDispatcher(0, 0).Running()); +} + +TEST(EventDispatcherDeathTest, polling_callbacks_on_idle_dispatchers) { + set_threadsafe_death_test_style(); + ASSERT_EXIT({ + check_polling_callback_lifecycle(); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); +} + +#if !BRPC_WITH_GLOG +void check_polling_dispatcher_start_failure(int available_fds) { + configure_polling_test(); + FLAGS_task_group_ntags = 1; + ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption( + "crash_on_fatal_log", "false").empty()); + ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption( + "print_stack_on_check", "false").empty()); + + // Initialize the bthread runtime before restricting fds: optional + // components such as the task tracer also create file descriptors. + bthread_t tid = INVALID_BTHREAD; + ASSERT_EQ(0, bthread_start_background( + &tid, nullptr, [](void*) -> void* { return nullptr; }, nullptr)); + ASSERT_EQ(0, bthread_join(tid, nullptr)); + + // open() reserves the lowest unused fds. Set the limit just above these + // slots, then release them: dispatcher 0 uses three, leaving either no fd + // for dispatcher 1's event queue or only one fd and no room for its pipe. + struct rlimit original_limit; + ASSERT_EQ(0, getrlimit(RLIMIT_NOFILE, &original_limit)); + struct rlimit limit = original_limit; + butil::fd_guard slots[4]; + for (int i = 0; i < available_fds; ++i) { + const int fd = open("/dev/null", O_RDONLY); + slots[i].reset(fd); + ASSERT_GE(fd, 0); + limit.rlim_cur = static_cast(fd) + 1; + } + ASSERT_EQ(0, setrlimit(RLIMIT_NOFILE, &limit)); + auto restore_limit = butil::MakeScopeGuard([&] { + EXPECT_EQ(0, setrlimit(RLIMIT_NOFILE, &original_limit)); + }); + for (auto& slot : slots) { + slot.reset(-1); + } + + int initialized[2] = {}; + int released[2] = {}; + brpc::PollingCallbacks callbacks; + callbacks.init_fn = [&](brpc::PollingContext& ctx) { + ++initialized[ctx.dispatcher_index]; + return 0; + }; + callbacks.poll_fn = [](brpc::PollingContext&) {}; + callbacks.release_fn = [&](brpc::PollingContext& ctx) { + ++released[ctx.dispatcher_index]; + }; + brpc::PollingRegistration registration; + const int rc = brpc::RegisterPollingCallbacksWithTag( + BTHREAD_TAG_DEFAULT, callbacks, ®istration); + const int error = errno; + if (rc == 0) { + EXPECT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); + } + ASSERT_EQ(-1, rc); + EXPECT_EQ(ESHUTDOWN, error); + EXPECT_EQ(1, initialized[0]); + EXPECT_EQ(0, initialized[1]); + EXPECT_EQ(1, released[0]); + EXPECT_EQ(0, released[1]); + EXPECT_EQ(-1, brpc::UnregisterPollingCallbacks(registration)); + EXPECT_EQ(EINVAL, errno); +} + +TEST(EventDispatcherDeathTest, polling_dispatcher_start_failure_rolls_back) { + set_threadsafe_death_test_style(); + for (int available_fds : {3, 4}) { + SCOPED_TRACE(available_fds); + ASSERT_EXIT({ + check_polling_dispatcher_start_failure(available_fds); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); + } +} +#endif // !BRPC_WITH_GLOG + +void check_polling_capture_destruction_can_unregister() { + configure_polling_test(); + brpc::PollingRegistration registration; + int released[2] = {}; + int destroyed = 0; + auto captured = std::shared_ptr(new int(0), [&](int* value) { + delete value; + EXPECT_EQ(1, released[0]); + EXPECT_EQ(1, released[1]); + const int rc = brpc::UnregisterPollingCallbacks(registration); + const int error = errno; + EXPECT_EQ(-1, rc); + EXPECT_EQ(ENOENT, error); + ++destroyed; + }); + brpc::PollingCallbacks callbacks; + callbacks.poll_fn = [captured](brpc::PollingContext&) { + static_cast(captured); + }; + callbacks.release_fn = [&](brpc::PollingContext& ctx) { + ++released[ctx.dispatcher_index]; + }; + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + // Leave the registered callback as the sole owner of the capture. + captured.reset(); + callbacks.poll_fn = nullptr; + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); + EXPECT_EQ(1, destroyed); +} + +TEST(EventDispatcherDeathTest, polling_capture_destructor_can_unregister) { + set_threadsafe_death_test_style(); + ASSERT_EXIT({ + check_polling_capture_destruction_can_unregister(); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); +} + +void check_polling_initialization_rollback() { + configure_polling_test(); + int initialized[2] = {}; + int released[2] = {}; + brpc::PollingCallbacks callbacks; + callbacks.init_fn = [&](brpc::PollingContext& ctx) { + ctx.user_data = new int(1); + ++initialized[ctx.dispatcher_index]; + return ctx.dispatcher_index == 1 ? ENOMEM : 0; + }; + callbacks.poll_fn = [](brpc::PollingContext&) {}; + callbacks.release_fn = [&](brpc::PollingContext& ctx) { + delete static_cast(ctx.user_data); + ++released[ctx.dispatcher_index]; + }; + brpc::PollingRegistration registration; + const int rc = brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration); + auto cleanup = butil::MakeScopeGuard([&] { + brpc::UnregisterPollingCallbacks(registration); + }); + ASSERT_EQ(-1, rc); + EXPECT_EQ(ENOMEM, errno); + for (int i = 0; i < 2; ++i) { + EXPECT_EQ(1, initialized[i]); + EXPECT_EQ(1, released[i]); + } + callbacks.init_fn = nullptr; + callbacks.release_fn = nullptr; + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); +} + +TEST(EventDispatcherDeathTest, polling_initialization_failure_rolls_back) { + set_threadsafe_death_test_style(); + ASSERT_EXIT({ + check_polling_initialization_rollback(); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); +} + +void check_polling_reentrant_registration() { + configure_polling_test(); + std::atomic ready{false}; + std::atomic checked{0}; + brpc::PollingRegistration registration; + brpc::PollingCallbacks nested; + nested.poll_fn = [](brpc::PollingContext&) {}; + brpc::PollingCallbacks callbacks; + callbacks.poll_fn = [&](brpc::PollingContext&) { + if (!ready.load(std::memory_order_acquire)) { + return; + } + brpc::PollingRegistration token; + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag(1, nested, &token)); + EXPECT_EQ(EDEADLK, errno); + EXPECT_EQ(-1, brpc::UnregisterPollingCallbacks(registration)); + EXPECT_EQ(EDEADLK, errno); + checked.fetch_add(1, std::memory_order_release); + }; + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + auto cleanup = butil::MakeScopeGuard([&] { + brpc::UnregisterPollingCallbacks(registration); + }); + ready.store(true, std::memory_order_release); + ASSERT_TRUE(wait_for_poll_count(checked, 2)); + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); +} + +TEST(EventDispatcherDeathTest, polling_reentrant_registration_is_rejected) { + set_threadsafe_death_test_style(); + ASSERT_EXIT({ + check_polling_reentrant_registration(); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); +} + +void check_polling_shutdown() { + configure_polling_test(); + int released = 0; + brpc::PollingCallbacks callbacks; + callbacks.poll_fn = [](brpc::PollingContext&) {}; + callbacks.release_fn = [&](brpc::PollingContext&) { ++released; }; + brpc::PollingRegistration registration; + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + auto cleanup = butil::MakeScopeGuard([&] { + brpc::UnregisterPollingCallbacks(registration); + }); + auto& dispatcher = brpc::GetGlobalEventDispatcher(0, 0); + dispatcher.Stop(); + dispatcher.Join(); + EXPECT_FALSE(dispatcher.IsDispatcherThread()); + EXPECT_FALSE(dispatcher.Running()); + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); + EXPECT_EQ(2, released); + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + EXPECT_EQ(ESHUTDOWN, errno); +} + +TEST(EventDispatcherDeathTest, polling_shutdown_releases_callbacks) { + set_threadsafe_death_test_style(); + ASSERT_EXIT({ + check_polling_shutdown(); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); +} + +struct PollingUnregisterArgs { + brpc::PollingRegistration registration; + std::atomic started{0}; + std::atomic done{0}; + int rc = -1; +}; + +void* unregister_polling_callbacks(void* arg) { + auto* args = static_cast(arg); + args->started.store(1, std::memory_order_release); + args->rc = brpc::UnregisterPollingCallbacks(args->registration); + args->done.store(1, std::memory_order_release); + return nullptr; +} + +void check_polling_unregister_waits(bool stop) { + configure_polling_test(); + std::atomic entered{0}; + std::atomic leave{false}; + int released[2] = {}; + brpc::PollingCallbacks callbacks; + callbacks.poll_fn = [&](brpc::PollingContext& ctx) { + if (ctx.dispatcher_index == 0) { + entered.store(1, std::memory_order_release); + // Artificially stall one iteration to verify the acknowledgement + // waits for in-flight callbacks, including the shutdown path. + while (!leave.load(std::memory_order_acquire)) { + cpu_relax(); + } + } + }; + callbacks.release_fn = [&](brpc::PollingContext& ctx) { + ++released[ctx.dispatcher_index]; + }; + PollingUnregisterArgs args; + bthread_t tid = INVALID_BTHREAD; + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag( + 0, callbacks, &args.registration)); + auto cleanup = butil::MakeScopeGuard([&] { + leave.store(true, std::memory_order_release); + if (tid) { + bthread_join(tid, nullptr); + } + brpc::UnregisterPollingCallbacks(args.registration); + if (stop) { + auto& dispatcher = brpc::GetGlobalEventDispatcher(0, 0); + dispatcher.Stop(); + dispatcher.Join(); + } + }); + ASSERT_TRUE(wait_for_poll_count(entered, 1)); + bthread_attr_t attr = BTHREAD_ATTR_NORMAL; + attr.tag = 0; + ASSERT_EQ(0, bthread_start_background( + &tid, &attr, unregister_polling_callbacks, &args)); + ASSERT_TRUE(wait_for_poll_count(args.started, 1)); + auto& dispatcher = brpc::GetGlobalEventDispatcher(0, 0); + const int64_t deadline = butil::gettimeofday_us() + 5000000; + while (!dispatcher._polling_command.load(std::memory_order_acquire) && + butil::gettimeofday_us() < deadline) { + usleep(1000); + } + ASSERT_NE(nullptr, dispatcher._polling_command.load(std::memory_order_acquire)); + // The stalled callback prevents consumption: Stop now must acknowledge + // this exact pending unregister command from FinishPolling(). + if (stop) { + dispatcher.Stop(); + } + EXPECT_EQ(0, args.done.load(std::memory_order_acquire)); + leave.store(true, std::memory_order_release); + ASSERT_TRUE(wait_for_poll_count(args.done, 1)); + ASSERT_EQ(0, bthread_join(tid, nullptr)); + tid = INVALID_BTHREAD; + EXPECT_EQ(0, args.rc); + for (int i = 0; i < 2; ++i) { + EXPECT_EQ(1, released[i]); + } + if (stop) { + dispatcher.Join(); + } +} + +TEST(EventDispatcherDeathTest, polling_unregister_waits_for_inflight_callback) { + set_threadsafe_death_test_style(); + for (bool stop : {false, true}) { + SCOPED_TRACE(stop); + ASSERT_EXIT({ + check_polling_unregister_waits(stop); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); + } +} + +void* check_registration_from_bthread(void*) { + int initialized[2] = {}; + int released[2] = {}; + brpc::PollingCallbacks callbacks; + callbacks.init_fn = [&](brpc::PollingContext& ctx) { + ++initialized[ctx.dispatcher_index]; + return 0; + }; + callbacks.poll_fn = [](brpc::PollingContext&) {}; + callbacks.release_fn = [&](brpc::PollingContext& ctx) { + ++released[ctx.dispatcher_index]; + }; + brpc::PollingRegistration registration; + auto cleanup = butil::MakeScopeGuard([&] { + brpc::UnregisterPollingCallbacks(registration); + }); + EXPECT_EQ(0, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + EXPECT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); + for (int i = 0; i < 2; ++i) { + EXPECT_EQ(1, initialized[i]); + EXPECT_EQ(1, released[i]); + } + callbacks.init_fn = [&](brpc::PollingContext& ctx) { + ++initialized[ctx.dispatcher_index]; + return ctx.dispatcher_index == 1 ? ENOMEM : 0; + }; + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + EXPECT_EQ(ENOMEM, errno); + for (int i = 0; i < 2; ++i) { + EXPECT_EQ(2, initialized[i]); + EXPECT_EQ(2, released[i]); + } + return nullptr; +} + +void check_polling_bthread_registration() { + configure_polling_test(); + // Start the worker pool with final tag settings before spawning a caller + // that registers callbacks on its own tag. + brpc::GetGlobalEventDispatcher(0, 0); + bthread_attr_t attr = BTHREAD_ATTR_NORMAL; + attr.tag = 0; + bthread_t tid; + ASSERT_EQ(0, bthread_start_background( + &tid, &attr, check_registration_from_bthread, nullptr)); + ASSERT_EQ(0, bthread_join(tid, nullptr)); +} + +TEST(EventDispatcherDeathTest, polling_registration_from_same_tag_bthread) { + set_threadsafe_death_test_style(); + ASSERT_EXIT({ + check_polling_bthread_registration(); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); +} + +TEST_F(EventDispatcherTest, polling_registration_validation) { + brpc::PollingRegistration registration; + brpc::PollingCallbacks callbacks; + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + EXPECT_EQ(EINVAL, errno); + callbacks.poll_fn = [](brpc::PollingContext&) {}; + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag(-1, callbacks, ®istration)); + EXPECT_EQ(EINVAL, errno); + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag( + FLAGS_task_group_ntags, callbacks, ®istration)); + EXPECT_EQ(EINVAL, errno); + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag(0, callbacks, nullptr)); + EXPECT_EQ(EINVAL, errno); + EXPECT_EQ(-1, brpc::UnregisterPollingCallbacks(registration)); + EXPECT_EQ(EINVAL, errno); + if (!brpc::GetGlobalEventDispatcher(0, 0).use_polling()) { + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + EXPECT_EQ(EPERM, errno); + } +} + TEST_F(EventDispatcherTest, has_epollrdhup) { LOG(INFO) << brpc::has_epollrdhup; } @@ -651,6 +1157,61 @@ void* stop_and_join(void* arg) { return nullptr; } +void check_tcp_with_polling(bool background) { + configure_polling_test(); + brpc::FLAGS_event_dispatcher_edisp_unsched = background; + std::atomic polls{0}; + brpc::PollingCallbacks callbacks; + callbacks.poll_fn = [&](brpc::PollingContext&) { + polls.fetch_add(1, std::memory_order_release); + }; + brpc::PollingRegistration registration; + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag(0, callbacks, ®istration)); + auto cleanup = butil::MakeScopeGuard([&] { + brpc::UnregisterPollingCallbacks(registration); + }); + ASSERT_TRUE(wait_for_poll_count(polls, 10)); + ReserveEchoServiceImpl service; + brpc::Server server; + ASSERT_EQ(0, server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE)); + brpc::ServerOptions options; + options.num_threads = 4; + ASSERT_EQ(0, server.Start("127.0.0.1:0", &options)); + brpc::Channel channel; + brpc::ChannelOptions copt; + copt.timeout_ms = 3000; + ASSERT_EQ(0, channel.Init(server.listen_address(), &copt)); + test::EchoService_Stub stub(&channel); + // Unregister between requests: it must leave the TCP path intact. + for (int i = 0; i < 20; ++i) { + if (i == 10) { + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); + } + brpc::Controller cntl; + test::EchoRequest req; + test::EchoResponse res; + req.set_message("polling echo"); + stub.Echo(&cntl, &req, &res, nullptr); + ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText(); + EXPECT_EQ(req.message(), res.message()); + } + server.Stop(0); + server.Join(); + EXPECT_GE(bthread::g_task_control->reserved_concurrency(0), 2); + EXPECT_EQ(background, brpc::EventDispatcherUnsched()); +} + +TEST(EventDispatcherDeathTest, polling_tcp_supports_urgent_and_background) { + set_threadsafe_death_test_style(); + for (bool background : {false, true}) { + SCOPED_TRACE(background); + ASSERT_EXIT({ + check_tcp_with_polling(background); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); + } +} + // Dispatchers need extra workers beyond the configured normal concurrency. TEST_F(EventDispatcherTest, dispatchers_do_not_consume_configured_concurrency) { ASSERT_EQ(NUM_EVENT_DISPATCHERS, FLAGS_event_dispatcher_num); From 83ecfcbf64394c7cb88332c0535c975f4f4e1390 Mon Sep 17 00:00:00 2001 From: Yang Liming Date: Thu, 3 Dec 2026 17:38:46 +0800 Subject: [PATCH 2/2] Fix EventDispatcher startup and polling callback reentrancy Fail fast when a global dispatcher cannot start so fd routing never publishes an unusable shard. Copy polling callbacks outside the group lock and recheck registration before installation. Cover fd exhaustion and callback-copy reentrancy in regression tests. --- src/brpc/event_dispatcher.cpp | 37 +++++-- src/brpc/event_dispatcher.h | 4 +- test/brpc_event_dispatcher_unittest.cpp | 122 +++++++++++++++++------- 3 files changed, 116 insertions(+), 47 deletions(-) diff --git a/src/brpc/event_dispatcher.cpp b/src/brpc/event_dispatcher.cpp index e2361e638e..eb26a48874 100644 --- a/src/brpc/event_dispatcher.cpp +++ b/src/brpc/event_dispatcher.cpp @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -#include // `atexit` +#include // `abort`, `atexit` #include #include #include // DEFINE_int32 @@ -54,11 +54,11 @@ static int g_edisp_ntags = 0; static int g_edisp_num = 0; struct EventDispatcherPollingState { - EventDispatcherPollingState(const PollingCallbacks& cb, - uint64_t generation) - : callbacks(cb), id(generation) {} + explicit EventDispatcherPollingState(const PollingCallbacks& cb) + : callbacks(cb) {} const PollingCallbacks callbacks; - const uint64_t id; + // Assigned under the group lock before installing the callbacks. + uint64_t id = 0; }; struct EventDispatcherPollingCommand { @@ -87,8 +87,8 @@ int EventDispatcher::SetPollingCallbacks(EventDispatcherPollingState* state) { EventDispatcherPollingCommand command(state); { BAIDU_SCOPED_LOCK(_polling_command_mutex); - // A dispatcher that failed to start has no thread to acknowledge a - // command and will never reach FinishPolling(). + // There is no dispatcher thread to acknowledge commands after it + // finishes or is joined. if (_polling_finished || _tid.load(std::memory_order_acquire) == INVALID_BTHREAD) { return state ? ESHUTDOWN : 0; @@ -214,7 +214,12 @@ void InitializeGlobalDispatchers() { FLAGS_usercode_in_pthread ? BTHREAD_ATTR_PTHREAD : BTHREAD_ATTR_NORMAL; attr.tag = (BTHREAD_TAG_DEFAULT + i) % g_edisp_ntags; g_edisp[i * g_edisp_num + j].set_priority_index(j); - CHECK_EQ(0, g_edisp[i * g_edisp_num + j].Start(&attr)); + if (g_edisp[i * g_edisp_num + j].Start(&attr) != 0) { + // Do not let pthread_once complete with an unusable fd shard. + LOG(FATAL) << "Fail to start global event dispatcher, tag=" + << attr.tag << ", index=" << j; + abort(); // FATAL logging may be configured not to terminate. + } } } // This atexit is will be run before g_task_control.stop() because above @@ -258,6 +263,8 @@ int RegisterPollingCallbacksWithTag(bthread_tag_t tag, return -1; } EventDispatcherPollingGroup& group = g_polling_groups[tag]; + // If registration unwinds, release the lock before destroying callbacks. + std::unique_ptr state; std::unique_lock lock(group.mutex); if (group.state) { errno = EEXIST; @@ -268,8 +275,18 @@ int RegisterPollingCallbacksWithTag(bthread_tag_t tag, errno = EPERM; return -1; } - std::unique_ptr state( - new EventDispatcherPollingState(callbacks, ++group.next_id)); + // Copying a callable may reenter registration or unregistration. + lock.unlock(); + state.reset(new EventDispatcherPollingState(callbacks)); + lock.lock(); + // Another registration (including a reentrant one) may have won the tag. + if (group.state) { + lock.unlock(); + state.reset(); + errno = EEXIST; + return -1; + } + state->id = ++group.next_id; for (int i = 0; i < g_edisp_num; ++i) { const int rc = dispatchers[i].SetPollingCallbacks(state.get()); if (rc != 0) { diff --git a/src/brpc/event_dispatcher.h b/src/brpc/event_dispatcher.h index aef1090a24..c3c66df60d 100644 --- a/src/brpc/event_dispatcher.h +++ b/src/brpc/event_dispatcher.h @@ -81,8 +81,8 @@ class PollingRegistration { // Callbacks are serial per dispatcher, but concurrent across dispatchers. They // must not block, throw, or synchronously register/unregister callbacks (EDEADLK). // poll_fn must be non-null. Returns 0 on success, -1 with errno on failure. -// Duplicate registration fails with EEXIST. A polling dispatcher that did not -// start or cannot accept an install command causes ESHUTDOWN. +// Duplicate registration fails with EEXIST. A polling dispatcher that is +// shutting down or has stopped causes ESHUTDOWN. int RegisterPollingCallbacksWithTag(bthread_tag_t tag, const PollingCallbacks& callbacks, PollingRegistration* registration); diff --git a/test/brpc_event_dispatcher_unittest.cpp b/test/brpc_event_dispatcher_unittest.cpp index 969ec6d097..c68f8943b2 100644 --- a/test/brpc_event_dispatcher_unittest.cpp +++ b/test/brpc_event_dispatcher_unittest.cpp @@ -21,9 +21,12 @@ #include #include +#include #include +#include #include #include +#include #include #include #include @@ -242,13 +245,13 @@ TEST(EventDispatcherDeathTest, polling_callbacks_on_idle_dispatchers) { } #if !BRPC_WITH_GLOG -void check_polling_dispatcher_start_failure(int available_fds) { - configure_polling_test(); +void trigger_dispatcher_start_failure(int available_fds) { + alarm(20); FLAGS_task_group_ntags = 1; + FLAGS_event_dispatcher_num = 2; + brpc::FLAGS_event_dispatcher_use_polling = false; ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption( "crash_on_fatal_log", "false").empty()); - ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption( - "print_stack_on_check", "false").empty()); // Initialize the bthread runtime before restricting fds: optional // components such as the task tracer also create file descriptors. @@ -278,42 +281,16 @@ void check_polling_dispatcher_start_failure(int available_fds) { slot.reset(-1); } - int initialized[2] = {}; - int released[2] = {}; - brpc::PollingCallbacks callbacks; - callbacks.init_fn = [&](brpc::PollingContext& ctx) { - ++initialized[ctx.dispatcher_index]; - return 0; - }; - callbacks.poll_fn = [](brpc::PollingContext&) {}; - callbacks.release_fn = [&](brpc::PollingContext& ctx) { - ++released[ctx.dispatcher_index]; - }; - brpc::PollingRegistration registration; - const int rc = brpc::RegisterPollingCallbacksWithTag( - BTHREAD_TAG_DEFAULT, callbacks, ®istration); - const int error = errno; - if (rc == 0) { - EXPECT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); - } - ASSERT_EQ(-1, rc); - EXPECT_EQ(ESHUTDOWN, error); - EXPECT_EQ(1, initialized[0]); - EXPECT_EQ(0, initialized[1]); - EXPECT_EQ(1, released[0]); - EXPECT_EQ(0, released[1]); - EXPECT_EQ(-1, brpc::UnregisterPollingCallbacks(registration)); - EXPECT_EQ(EINVAL, errno); + brpc::GetGlobalEventDispatcher(0, BTHREAD_TAG_DEFAULT); } -TEST(EventDispatcherDeathTest, polling_dispatcher_start_failure_rolls_back) { +TEST(EventDispatcherDeathTest, global_dispatcher_start_failure_aborts) { set_threadsafe_death_test_style(); for (int available_fds : {3, 4}) { SCOPED_TRACE(available_fds); - ASSERT_EXIT({ - check_polling_dispatcher_start_failure(available_fds); - _exit(::testing::Test::HasFailure() ? 1 : 0); - }, ::testing::ExitedWithCode(0), ""); + ASSERT_EXIT(trigger_dispatcher_start_failure(available_fds), + ::testing::KilledBySignal(SIGABRT), + "Fail to start global event dispatcher, tag=[0-9]+, index=1"); } } #endif // !BRPC_WITH_GLOG @@ -356,6 +333,81 @@ TEST(EventDispatcherDeathTest, polling_capture_destructor_can_unregister) { }, ::testing::ExitedWithCode(0), ""); } +struct PollingCallbackWithCopyHook { + explicit PollingCallbackWithCopyHook(std::function hook) + : on_copy(std::move(hook)) {} + PollingCallbackWithCopyHook(const PollingCallbackWithCopyHook& other) + : on_copy(other.on_copy) { + on_copy(); + } + PollingCallbackWithCopyHook(PollingCallbackWithCopyHook&&) = default; + void operator()(brpc::PollingContext&) const {} + + std::function on_copy; +}; + +void check_polling_callback_copy_can_reenter(bool register_on_copy) { + configure_polling_test(); + const bthread_tag_t tag = BTHREAD_TAG_DEFAULT; + brpc::PollingCallbacks plain_callbacks; + plain_callbacks.poll_fn = [](brpc::PollingContext&) {}; + brpc::PollingRegistration stale; + ASSERT_EQ(0, brpc::RegisterPollingCallbacksWithTag( + tag, plain_callbacks, &stale)); + ASSERT_EQ(0, brpc::UnregisterPollingCallbacks(stale)); + + int copies = 0; + brpc::PollingRegistration nested; + brpc::PollingCallbacks callbacks; + callbacks.poll_fn = PollingCallbackWithCopyHook([&] { + ++copies; + EXPECT_EQ(-1, brpc::UnregisterPollingCallbacks(stale)); + EXPECT_EQ(ENOENT, errno); + if (register_on_copy) { + EXPECT_EQ(0, brpc::RegisterPollingCallbacksWithTag( + tag, plain_callbacks, &nested)); + } + }); + ASSERT_EQ(0, copies); // Assigning the temporary moves the target. + + brpc::PollingRegistration registration; + const int rc = brpc::RegisterPollingCallbacksWithTag( + tag, callbacks, ®istration); + const int error = errno; + EXPECT_EQ(1, copies); + if (register_on_copy) { + EXPECT_EQ(-1, rc); + EXPECT_EQ(EEXIST, error); + EXPECT_EQ(-1, brpc::UnregisterPollingCallbacks(registration)); + EXPECT_EQ(EINVAL, errno); + EXPECT_EQ(0, brpc::UnregisterPollingCallbacks(nested)); + } else { + ASSERT_EQ(0, rc); + brpc::PollingRegistration duplicate; + EXPECT_EQ(-1, brpc::RegisterPollingCallbacksWithTag( + tag, callbacks, &duplicate)); + EXPECT_EQ(EEXIST, errno); + EXPECT_EQ(1, copies); // An already occupied tag does not copy callbacks. + EXPECT_EQ(0, brpc::UnregisterPollingCallbacks(registration)); + } +} + +TEST(EventDispatcherDeathTest, polling_callback_copy_can_unregister_stale_token) { + set_threadsafe_death_test_style(); + ASSERT_EXIT({ + check_polling_callback_copy_can_reenter(false); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); +} + +TEST(EventDispatcherDeathTest, polling_callback_copy_preserves_nested_registration) { + set_threadsafe_death_test_style(); + ASSERT_EXIT({ + check_polling_callback_copy_can_reenter(true); + _exit(::testing::Test::HasFailure() ? 1 : 0); + }, ::testing::ExitedWithCode(0), ""); +} + void check_polling_initialization_rollback() { configure_polling_test(); int initialized[2] = {};