This is an automated email from the ASF dual-hosted git repository.
chenBright pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/brpc.git
The following commit(s) were added to refs/heads/master by this push:
new 73ccf6a5a Support RDMA for FlatBuffers RPC (#3746)
73ccf6a5a is described below
commit 73ccf6a5af85f826658cc020d53ef5c6934e76f4
Author: Bright Chen <[email protected]>
AuthorDate: Mon Nov 23 10:22:52 2026 +0800
Support RDMA for FlatBuffers RPC (#3746)
* Support RDMA for FlatBuffers RPC
* Separate FlatBuffers RDMA tests from the default test suite
* Fix FlatBuffers RDMA allocation fallback and add CI coverage
* Fix RDMA memory deregistration during shutdown
---
.github/workflows/ci-linux.yml | 8 +-
src/brpc/flatbuffers/message.cpp | 66 ++++-
src/brpc/rdma/rdma_helper.cpp | 88 +++---
test/BUILD.bazel | 32 ++
test/CMakeLists.txt | 13 +-
test/Makefile | 19 +-
test/brpc_flatbuffers_rdma_unittest.cpp | 503 ++++++++++++++++++++++++++++++++
test/brpc_rdma_unittest.cpp | 12 +
test/run_tests.sh | 4 +
9 files changed, 696 insertions(+), 49 deletions(-)
diff --git a/.github/workflows/ci-linux.yml b/.github/workflows/ci-linux.yml
index eff5b4eab..829420db3 100644
--- a/.github/workflows/ci-linux.yml
+++ b/.github/workflows/ci-linux.yml
@@ -261,6 +261,7 @@ jobs:
--define with_glog=true \
--define with_thrift=true \
--define BRPC_WITH_RDMA=true \
+ --define BRPC_WITH_FLATBUFFERS=true \
--define BRPC_WITH_UBRING=true \
--define BRPC_WITH_BORINGSSL=true \
--define with_debug_bthread_sche_safety=true \
@@ -269,7 +270,7 @@ jobs:
--define with_bthread_tracer=true \
--define BRPC_WITH_NO_PTHREAD_MUTEX_HOOK=true \
--define with_babylon_counter=true \
- -- //:brpc //example/...
+ -- //:brpc //example/...
//test:brpc_flatbuffers_rdma_unittest
- name: external
run: |
cd example/build_with_bazel_module
@@ -277,6 +278,7 @@ jobs:
--define with_glog=true \
--define with_thrift=true \
--define BRPC_WITH_RDMA=true \
+ --define BRPC_WITH_FLATBUFFERS=true \
--define BRPC_WITH_UBRING=true \
--define BRPC_WITH_BORINGSSL=true \
--define with_debug_bthread_sche_safety=true \
@@ -321,6 +323,7 @@ jobs:
--define with_glog=true \
--define with_thrift=true \
--define BRPC_WITH_RDMA=true \
+ --define BRPC_WITH_FLATBUFFERS=true \
--define BRPC_WITH_UBRING=true \
--define BRPC_WITH_BORINGSSL=true \
--define with_debug_bthread_sche_safety=true \
@@ -329,7 +332,7 @@ jobs:
--define with_bthread_tracer=true \
--define BRPC_WITH_NO_PTHREAD_MUTEX_HOOK=true \
--define with_babylon_counter=true \
- -- //:brpc //example/...
+ -- //:brpc //example/...
//test:brpc_flatbuffers_rdma_unittest
- name: external
run: |
cd example/build_with_bazel_module
@@ -338,6 +341,7 @@ jobs:
--define with_glog=true \
--define with_thrift=true \
--define BRPC_WITH_RDMA=true \
+ --define BRPC_WITH_FLATBUFFERS=true \
--define BRPC_WITH_UBRING=true \
--define BRPC_WITH_BORINGSSL=true \
--define with_debug_bthread_sche_safety=true \
diff --git a/src/brpc/flatbuffers/message.cpp b/src/brpc/flatbuffers/message.cpp
index d3116d9a7..7e71cbcad 100644
--- a/src/brpc/flatbuffers/message.cpp
+++ b/src/brpc/flatbuffers/message.cpp
@@ -20,12 +20,71 @@
#if BRPC_WITH_FLATBUFFERS
#include <cstring>
#include <cerrno>
+#include <cstdlib>
#include "butil/logging.h"
+#if BRPC_WITH_RDMA
+#include "butil/iobuf_inl.h"
+#include "butil/memory/scope_guard.h"
+#include "brpc/rdma/block_pool.h"
+#include "brpc/rdma/rdma_helper.h"
+#endif // BRPC_WITH_RDMA
namespace brpc {
namespace flatbuffers {
namespace {
+void* AllocateStorage(butil::SingleIOBuf* storage, uint32_t size) {
+#if BRPC_WITH_RDMA
+ if (!rdma::IsRdmaAvailable()) {
+ return storage->allocate(size);
+ }
+ // SingleIOBuf normally uses the registered IOBuf pool. Its largest block
+ // class (type 2) is 2 MiB, including the IOBuf block header. Larger
buffers
+ // and failed pool allocations fall back to separately registered storage.
+ if (static_cast<size_t>(size) + sizeof(butil::IOBuf::Block) <=
rdma::GetBlockSize(2)) {
+ void* data = storage->allocate(size);
+ if (data != nullptr) {
+ return data;
+ }
+ }
+
+ void* data = malloc(size);
+ if (data == nullptr) {
+ return nullptr;
+ }
+ // Registration failure must not prevent TCP use in an RDMA-enabled
+ // process. An RDMA send of this unregistered buffer will fail with
ERDMAMEM.
+ const uint32_t lkey = rdma::RegisterMemoryForRdma(data, size);
+ auto free_storage = [lkey](void* data) {
+ if (lkey != 0) {
+ rdma::DeregisterMemoryForRdma(data);
+ }
+ free(data);
+ };
+ butil::IOBuf buffer;
+ BUTIL_SCOPE_EXIT {
+ if (buffer.empty()) {
+ free_storage(data);
+ } else {
+ // After append, the IOBuf deleter owns the allocation. If
+ // assign fails, dropping this last reference frees it.
+ buffer.clear();
+ }
+ };
+ if (buffer.append_user_data_with_meta(data, size, free_storage, lkey) !=
0) {
+ return nullptr;
+ }
+ // Retain the user-data block, including its lkey and deleter, through
+ // builder growth, Message aliases and outstanding socket writes.
+ if (!storage->assign(buffer, size)) {
+ return nullptr;
+ }
+ return data;
+#else
+ return storage->allocate(size);
+#endif // BRPC_WITH_RDMA
+}
+
uint8_t* AlignPayload(uint8_t* data) {
const uintptr_t address = reinterpret_cast<uintptr_t>(data);
const size_t padding = (kBufferAlignment - address % kBufferAlignment) %
@@ -57,7 +116,8 @@ uint8_t* SlabAllocator::allocate(size_t size) {
butil::SingleIOBuf storage;
const uint32_t allocation_size = static_cast<uint32_t>(
size + kDefaultMetaSize + kBufferAlignment - 1);
- uint8_t* raw = static_cast<uint8_t*>(storage.allocate(allocation_size));
+ uint8_t* raw = static_cast<uint8_t*>(
+ AllocateStorage(&storage, allocation_size));
RELEASE_ASSERT_VERBOSE(raw != nullptr,
"Fail to allocate FlatBuffers storage");
_data = AlignPayload(raw + kDefaultMetaSize);
@@ -158,8 +218,8 @@ bool Message::parse_msg_from_iobuf(const butil::IOBuf& buf,
size_t msg_size,
return false;
}
} else {
- uint8_t* raw = static_cast<uint8_t*>(storage.allocate(
- static_cast<uint32_t>(total + kBufferAlignment - 1)));
+ uint8_t* raw = static_cast<uint8_t*>(AllocateStorage(
+ &storage, static_cast<uint32_t>(total + kBufferAlignment - 1)));
if (!raw) {
return false;
}
diff --git a/src/brpc/rdma/rdma_helper.cpp b/src/brpc/rdma/rdma_helper.cpp
index 05d1c7ead..7853b9476 100644
--- a/src/brpc/rdma/rdma_helper.cpp
+++ b/src/brpc/rdma/rdma_helper.cpp
@@ -26,6 +26,7 @@
#include "butil/fd_guard.h"
#include "butil/fd_utility.h" // butil::make_non_blocking
#include "butil/logging.h"
+#include "butil/scoped_lock.h"
#include "brpc/socket.h"
#include "brpc/rdma/block_pool.h"
#include "brpc/rdma/rdma_endpoint.h"
@@ -108,8 +109,10 @@ static SocketId g_async_socket;
static ibv_pd* g_pd = nullptr;
static std::vector<ibv_mr*>* g_mrs = nullptr; // mr registered by brpc
-static butil::FlatMap<void*, ibv_mr*>* g_user_mrs; // mr registered by user
-static butil::Mutex* g_user_mrs_lock = nullptr;
+// A user buffer can outlive GlobalRelease(). Keep the lock valid for its
+// deleter and hold it through verbs operations before releasing the PD.
+static pthread_mutex_t g_user_mrs_lock = PTHREAD_MUTEX_INITIALIZER;
+static butil::FlatMap<void*, ibv_mr*>* g_user_mrs = nullptr;
// Store the original IOBuf memalloc and memdealloc functions
static void* (*g_mem_alloc)(size_t) = nullptr;
@@ -146,18 +149,16 @@ static void GlobalRelease() {
return;
}
- if (g_user_mrs_lock) {
- BAIDU_SCOPED_LOCK(*g_user_mrs_lock);
- for (butil::FlatMap<void*, ibv_mr*>::iterator it = g_user_mrs->begin();
- it != g_user_mrs->end(); ++it) {
- IbvDeregMr(it->second);
+ {
+ BAIDU_SCOPED_LOCK(g_user_mrs_lock);
+ if (g_user_mrs != nullptr) {
+ for (const auto& entry : *g_user_mrs) {
+ IbvDeregMr(entry.second);
+ }
+ delete g_user_mrs;
+ g_user_mrs = nullptr;
}
- g_user_mrs->clear();
- delete g_user_mrs;
- g_user_mrs = nullptr;
}
- delete g_user_mrs_lock;
- g_user_mrs_lock = nullptr;
if (g_mrs) {
for (size_t i = 0; i < g_mrs->size(); ++i) {
@@ -494,12 +495,16 @@ static void GlobalRdmaInitializeOrDieImpl() {
ExitWithError();
}
- g_user_mrs_lock = new butil::Mutex;
- g_user_mrs = new butil::FlatMap<void*, ibv_mr*>();
- if (g_user_mrs->init(65536) < 0) {
+ auto user_mrs = new butil::FlatMap<void*, ibv_mr*>();
+ if (user_mrs->init(65536) < 0) {
PLOG(WARNING) << "Fail to initialize g_user_mrs";
+ delete user_mrs;
ExitWithError();
}
+ {
+ BAIDU_SCOPED_LOCK(g_user_mrs_lock);
+ g_user_mrs = user_mrs;
+ }
g_mrs = new std::vector<ibv_mr*>;
ibv_device_attr attr;
@@ -561,6 +566,11 @@ void GlobalRdmaInitializeOrDie() {
}
uint32_t RegisterMemoryForRdma(void* buf, size_t len) {
+ BAIDU_SCOPED_LOCK(g_user_mrs_lock);
+ if (!g_user_mrs || !IsRdmaAvailable()) {
+ errno = ENODEV;
+ return 0;
+ }
ibv_mr* mr = IbvRegMr(g_pd, buf, len, IBV_ACCESS_LOCAL_WRITE |
IBV_ACCESS_RELAXED_ORDERING);
if (!mr) {
PLOG(WARNING) << "Do not support IBV_ACCESS_RELAXED_ORDERING for
RDMA!!!";
@@ -570,37 +580,29 @@ uint32_t RegisterMemoryForRdma(void* buf, size_t len) {
return 0;
}
}
- {
- BAIDU_SCOPED_LOCK(*g_user_mrs_lock);
- if (!g_user_mrs->insert(buf, mr)) {
- LOG(WARNING) << "Fail to insert to user mr maps (now there are "
- << g_user_mrs->size() << " mrs already";
- } else {
- return mr->lkey;
- }
+ if (g_user_mrs->insert(buf, mr)) {
+ return mr->lkey;
}
- if(IbvDeregMr(mr)) {
+ LOG(WARNING) << "Fail to insert to user mr maps (now there are "
+ << g_user_mrs->size() << " mrs already";
+ if (IbvDeregMr(mr)) {
PLOG(ERROR) << "Failed to deregister memory";
}
return 0;
}
void DeregisterMemoryForRdma(void* buf) {
- ibv_mr* mr = nullptr;
- {
- BAIDU_SCOPED_LOCK(*g_user_mrs_lock);
- ibv_mr** mr_ptr = g_user_mrs->seek(buf);
- if (mr_ptr) {
- mr = *mr_ptr;
- g_user_mrs->erase(buf);
- }
+ BAIDU_SCOPED_LOCK(g_user_mrs_lock);
+ if (g_user_mrs == nullptr) {
+ return;
}
- if (mr) {
- if (IbvDeregMr(mr)) {
- PLOG(ERROR) << "Failed to deregister memory at: " << mr->addr;
- }
- } else {
+ ibv_mr* mr = nullptr;
+ if (g_user_mrs->erase(buf, &mr) == 0) {
LOG(WARNING) << "Try to deregister a buffer which is not registered";
+ return;
+ }
+ if (IbvDeregMr(mr) != 0) {
+ PLOG(ERROR) << "Failed to deregister memory at: " << buf;
}
}
@@ -629,7 +631,10 @@ ibv_pd* GetRdmaPd() {
}
uint32_t GetLKey(void* buf) {
- BAIDU_SCOPED_LOCK(*g_user_mrs_lock);
+ BAIDU_SCOPED_LOCK(g_user_mrs_lock);
+ if (!g_user_mrs) {
+ return 0;
+ }
ibv_mr** mr_ptr = g_user_mrs->seek(buf);
if (mr_ptr) {
return (*mr_ptr)->lkey;
@@ -669,10 +674,13 @@ void GlobalDisableRdma() {
bool SupportedByRdma(std::string protocol) {
if (protocol.compare("baidu_std") == 0) {
- // Since rdma is used for high performance scenario,
- // we consider baidu_std for the only protocol to support.
return true;
}
+#if BRPC_WITH_FLATBUFFERS
+ if (protocol.compare("fb_rpc") == 0) {
+ return true;
+ }
+#endif // BRPC_WITH_FLATBUFFERS
return false;
}
diff --git a/test/BUILD.bazel b/test/BUILD.bazel
index 948635317..3dc552a16 100644
--- a/test/BUILD.bazel
+++ b/test/BUILD.bazel
@@ -281,6 +281,37 @@ cc_test(
],
)
+config_setting(
+ name = "brpc_with_flatbuffers_and_rdma",
+ define_values = {
+ "BRPC_WITH_FLATBUFFERS": "true",
+ "BRPC_WITH_RDMA": "true",
+ },
+)
+
+# Requires real RDMA hardware; run only when this target is explicitly
selected.
+cc_test(
+ name = "brpc_flatbuffers_rdma_unittest",
+ srcs = [
+ "brpc_flatbuffers_rdma_unittest.cpp",
+ ":flatbuffers_test_messages",
+ ],
+ copts = COPTS,
+ includes = ["."],
+ tags = [
+ "exclusive",
+ "manual",
+ ],
+ target_compatible_with = select({
+ ":brpc_with_flatbuffers_and_rdma": [],
+ "//conditions:default": ["@platforms//:incompatible"],
+ }),
+ deps = [
+ "//:brpc",
+ "@com_google_googletest//:gtest",
+ ],
+)
+
# Textual inclusion fixes the two implementations' initialization order. Static
# linking supplies the remaining brpc objects without duplicate flag
definitions.
cc_library(
@@ -321,6 +352,7 @@ generate_unittests(
"brpc_collector_premain_unittest.cpp",
"brpc_flatbuffers_unittest.cpp",
"brpc_flatbuffers_protocol_unittest.cpp",
+ "brpc_flatbuffers_rdma_unittest.cpp",
],
),
deps = [
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 25b107cf1..8163965b4 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -318,6 +318,16 @@ if(WITH_FLATBUFFERS)
add_test(NAME ${FB_TEST} COMMAND ${FB_TEST})
endforeach()
+ if(WITH_RDMA)
+ # Requires real RDMA hardware; build and run explicitly, outside CTest.
+ add_executable(brpc_flatbuffers_rdma_unittest EXCLUDE_FROM_ALL
+ brpc_flatbuffers_rdma_unittest.cpp "${FLATBUFFERS_TEST_HEADER}")
+ target_include_directories(brpc_flatbuffers_rdma_unittest BEFORE
PRIVATE
+ "${BRPC_GTEST_INCLUDE_DIR}")
+ target_link_libraries(brpc_flatbuffers_rdma_unittest PRIVATE
+ brpc-static brpc_test_config gtest ${DYNAMIC_LIB})
+ endif()
+
# The same probe compiled with the OFF configuration must report the same
# layout; the ON validation runs both and compares their output.
set(WITH_FLATBUFFERS_VAL 0)
@@ -342,7 +352,8 @@ file(GLOB BRPC_UNITTESTS "brpc_*_unittest.cpp")
list(REMOVE_ITEM BRPC_UNITTESTS
"${CMAKE_CURRENT_SOURCE_DIR}/brpc_collector_premain_unittest.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/brpc_flatbuffers_unittest.cpp"
- "${CMAKE_CURRENT_SOURCE_DIR}/brpc_flatbuffers_protocol_unittest.cpp")
+ "${CMAKE_CURRENT_SOURCE_DIR}/brpc_flatbuffers_protocol_unittest.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/brpc_flatbuffers_rdma_unittest.cpp")
foreach(BRPC_UT ${BRPC_UNITTESTS})
get_filename_component(BRPC_UT_WE ${BRPC_UT} NAME_WE)
add_executable(${BRPC_UT_WE} ${BRPC_UT} $<TARGET_OBJECTS:TEST_PROTO_LIB>)
diff --git a/test/Makefile b/test/Makefile
index 7ee0ce33a..e189a70fd 100644
--- a/test/Makefile
+++ b/test/Makefile
@@ -182,6 +182,8 @@ TEST_BTHREAD_SOURCES = $(wildcard bthread_*unittest.cpp)
TEST_BTHREAD_OBJS = $(addsuffix .o, $(basename $(TEST_BTHREAD_SOURCES)))
TEST_BRPC_SOURCES = $(wildcard brpc_*unittest.cpp)
+# Requires real RDMA hardware; build and run this target explicitly.
+TEST_BRPC_SOURCES := $(filter-out
brpc_flatbuffers_rdma_unittest.cpp,$(TEST_BRPC_SOURCES))
ifneq ($(WITH_FLATBUFFERS),1)
TEST_BRPC_SOURCES := $(filter-out brpc_flatbuffers_unittest.cpp
brpc_flatbuffers_protocol_unittest.cpp,$(TEST_BRPC_SOURCES))
endif
@@ -200,11 +202,12 @@ all: $(TEST_BINS)
clean:clean_bins
@echo "> Cleaning"
rm -rf $(TEST_BUTIL_OBJS) $(TEST_BVAR_OBJS) $(TEST_BTHREAD_OBJS)
$(TEST_BRPC_OBJS) $(TEST_PROTO_OBJS) $(TEST_PROTO_SOURCES:.proto=.pb.h)
$(TEST_PROTO_SOURCES:.proto=.pb.cc) flatbuffers_message_generated.h
$(FLATBUFFERS_TEST_GEN_DIR)
+ rm -f brpc_flatbuffers_rdma_unittest.o
$(MAKE) -C.. clean_debug
.PHONY:clean_bins
clean_bins:
- rm -rf $(TEST_BINS)
+ rm -rf $(TEST_BINS) brpc_flatbuffers_rdma_unittest
libbrpc.dbg.$(SOEXT):FORCE
$(MAKE) -C.. test/libbrpc.dbg.$(SOEXT)
@@ -244,16 +247,20 @@ ifeq ($(WITH_FLATBUFFERS),1)
FLATC ?= flatc
FLATBUFFERS_TEST_HEADER =
$(FLATBUFFERS_TEST_GEN_DIR)/flatbuffers_message_generated.h
FLATBUFFERS_TEST_HDRPATHS = -I$(FLATBUFFERS_TEST_GEN_DIR) $(HDRPATHS)
+FLATBUFFERS_TEST_TARGETS = brpc_flatbuffers_unittest
brpc_flatbuffers_protocol_unittest
+ifeq ($(WITH_RDMA),1)
+FLATBUFFERS_TEST_TARGETS += brpc_flatbuffers_rdma_unittest
+endif
$(FLATBUFFERS_TEST_HEADER):flatbuffers_message.fbs
@mkdir -p $(FLATBUFFERS_TEST_GEN_DIR)
$(FLATC) --cpp -o $(FLATBUFFERS_TEST_GEN_DIR) $<
-brpc_flatbuffers_unittest.o brpc_flatbuffers_protocol_unittest.o:%.o:%.cpp
$(FLATBUFFERS_TEST_HEADER) | libbrpc.dbg.$(SOEXT)
+$(FLATBUFFERS_TEST_TARGETS:=.o):%.o:%.cpp $(FLATBUFFERS_TEST_HEADER) |
libbrpc.dbg.$(SOEXT)
@echo "> Compiling $@"
$(CXX) -c $(FLATBUFFERS_TEST_HDRPATHS) $(CXXFLAGS) $< -o $@
-brpc_flatbuffers_unittest brpc_flatbuffers_protocol_unittest: %: %.o |
libbrpc.dbg.$(SOEXT)
+$(FLATBUFFERS_TEST_TARGETS): %: %.o | libbrpc.dbg.$(SOEXT)
@echo "> Linking $@"
ifeq ($(SYSTEM),Linux)
$(CXX) -o $@ $(LIBPATHS) $(SOPATHS) -Xlinker "-(" $^ -Xlinker "-)"
$(STATIC_LINKINGS) $(UT_DYNAMIC_LINKINGS)
@@ -262,6 +269,12 @@ else ifeq ($(SYSTEM),Darwin)
endif
endif
+ifneq ($(WITH_FLATBUFFERS)$(WITH_RDMA),11)
+.PHONY: brpc_flatbuffers_rdma_unittest
+brpc_flatbuffers_rdma_unittest:
+ $(error Configure with --with-flatbuffers --with-rdma to build this
test)
+endif
+
# The pre-main test includes both implementations and needs a static archive to
# avoid loading duplicate flags from the shared test library.
../libbrpc.a:FORCE
diff --git a/test/brpc_flatbuffers_rdma_unittest.cpp
b/test/brpc_flatbuffers_rdma_unittest.cpp
new file mode 100644
index 000000000..44c4225c1
--- /dev/null
+++ b/test/brpc_flatbuffers_rdma_unittest.cpp
@@ -0,0 +1,503 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "butil/config.h"
+#if BRPC_WITH_FLATBUFFERS
+#if BRPC_WITH_RDMA
+#include <gflags/gflags.h>
+#include <gtest/gtest.h>
+#include <algorithm>
+#include <atomic>
+#include <cerrno>
+#include <cstdlib>
+#include <string>
+#include <vector>
+#include "brpc/channel.h"
+#include "brpc/closure_guard.h"
+#include "brpc/controller.h"
+#include "brpc/details/controller_private_accessor.h"
+#include "brpc/errno.pb.h"
+#include "brpc/flatbuffers/message.h"
+#include "brpc/flatbuffers/service.h"
+#include "brpc/global.h"
+#include "brpc/rdma/rdma_endpoint.h"
+#include "brpc/rdma/rdma_helper.h"
+#include "brpc/rdma_transport.h"
+#include "brpc/server.h"
+#include "brpc/socket.h"
+#include "flatbuffers_message_generated.h"
+
+#if !BRPC_WITH_GLOG
+namespace logging {
+DECLARE_bool(crash_on_fatal_log);
+}
+#endif
+
+namespace brpc {
+namespace rdma {
+extern ibv_mr* (*IbvRegMr)(ibv_pd*, void*, size_t, int);
+} // namespace rdma
+} // namespace brpc
+
+namespace {
+
+using brpc::flatbuffers::Message;
+using brpc::flatbuffers::MessageBuilder;
+using brpc::flatbuffers::MethodDescriptor;
+using brpc::flatbuffers::ServiceDescriptor;
+using brpc_fbtest::Payload;
+
+thread_local bool g_fail_pool_allocation = false;
+thread_local bool g_fail_registration = false;
+
+class ScopedAllocationFailures {
+public:
+ ScopedAllocationFailures(bool pool, bool registration) {
+ g_fail_pool_allocation = pool;
+ g_fail_registration = registration;
+ }
+ ~ScopedAllocationFailures() {
+ g_fail_pool_allocation = false;
+ g_fail_registration = false;
+ }
+private:
+ DISALLOW_COPY_AND_ASSIGN(ScopedAllocationFailures);
+};
+
+void InstallAllocationHooks() {
+ // Install once before the tests. Only the allocating test thread injects
+ // failures; background RPC threads continue to use the real allocators.
+ static auto allocate_block = butil::iobuf::blockmem_allocate;
+ butil::iobuf::blockmem_allocate = [](size_t size) -> void* {
+ if (g_fail_pool_allocation) {
+ errno = ENOMEM;
+ return nullptr;
+ }
+ return allocate_block(size);
+ };
+ static auto register_memory = brpc::rdma::IbvRegMr;
+ brpc::rdma::IbvRegMr = [](ibv_pd* pd, void* data, size_t size,
+ int access) -> ibv_mr* {
+ if (g_fail_registration) {
+ errno = ENOMEM;
+ return nullptr;
+ }
+ return register_memory(pd, data, size, access);
+ };
+}
+
+bool IsRdmaOn(const brpc::Socket* socket) {
+ if (socket == nullptr || socket->socket_mode() != brpc::SOCKET_MODE_RDMA) {
+ return false;
+ }
+ const auto* transport =
+ static_cast<const brpc::RdmaTransport*>(socket->_transport.get());
+ return transport->_rdma_ep->_state.load(butil::memory_order_acquire) ==
+ brpc::rdma::RdmaEndpoint::ESTABLISHED &&
+ transport->_rdma_state == brpc::RdmaTransport::RDMA_ON;
+}
+
+std::string Bytes(const Message& message) {
+ return std::string(reinterpret_cast<const char*>(message.data()),
+ message.size());
+}
+
+Message MakePayload(size_t text_size = 16, int64_t value = 123,
+ size_t vector_size = 4) {
+ MessageBuilder builder(8);
+ auto text = builder.CreateString(std::string(text_size, 'x'));
+ std::vector<int32_t> numbers(vector_size);
+ for (size_t i = 0; i < numbers.size(); ++i) {
+ numbers[i] = static_cast<int32_t>(i) * -3;
+ }
+ auto values = builder.CreateVector(numbers);
+ builder.Finish(brpc_fbtest::CreatePayload(builder, value, text, values));
+ return builder.ReleaseMessage();
+}
+
+void ExpectReply(const Message& response, const Message& request,
+ const MethodDescriptor* method) {
+ ASSERT_NE(nullptr, method);
+ ASSERT_TRUE(request.Verify<Payload>());
+ // Framing validation is not schema validation; the caller must do this.
+ ASSERT_TRUE(response.Verify<Payload>());
+ const Payload* in = request.GetRoot<Payload>();
+ const Payload* out = response.GetRoot<Payload>();
+ EXPECT_EQ(in->value() + method->index(), out->value());
+ ASSERT_NE(nullptr, out->message());
+ EXPECT_EQ(method->name() + ":" + in->message()->str(),
+ out->message()->str());
+ ASSERT_NE(nullptr, out->values());
+ ASSERT_EQ(in->values()->size(), out->values()->size());
+ for (size_t i = 0; i < in->values()->size(); ++i) {
+ EXPECT_EQ(in->values()->Get(i), out->values()->Get(i));
+ }
+}
+
+class Completion : public google::protobuf::Closure {
+public:
+ void Run() override { ++_calls; }
+ int calls() const { return _calls.load(); }
+private:
+ std::atomic<int> _calls{0};
+};
+
+class PayloadService : public brpc::flatbuffers::Service {
+public:
+ PayloadService() {
+ EXPECT_EQ(0, _descriptor.init(
+ {"brpc_fbtest", "RdmaService", "Echo", {41}}));
+ }
+ const ServiceDescriptor* GetDescriptor() override { return &_descriptor; }
+ void FBCallMethod(const MethodDescriptor* method,
+ google::protobuf::RpcController* controller,
+ const Message* request, Message* response,
+ google::protobuf::Closure* done) override {
+ brpc::ClosureGuard done_guard(done);
+ brpc::Controller* cntl = static_cast<brpc::Controller*>(controller);
+ if
(IsRdmaOn(brpc::ControllerPrivateAccessor(cntl).get_sending_socket())) {
+ ++rdma_calls;
+ }
+ if (!method || _descriptor.FindMethodByIndex(method->index()) !=
method ||
+ cntl->flatbuffers_method() != method) {
+ cntl->SetFailed(brpc::ENOMETHOD, "Wrong FlatBuffers method
context");
+ return;
+ }
+ if (!request || !request->Verify<Payload>()) {
+ cntl->SetFailed(brpc::EREQUEST, "Invalid Payload schema");
+ return;
+ }
+ const Payload* in = request->GetRoot<Payload>();
+ if (!in->message() || !in->values()) {
+ cntl->SetFailed(brpc::EREQUEST, "Missing application fields");
+ return;
+ }
+ const int failure = fail_next_code.exchange(0);
+ if (failure != 0) {
+ cntl->SetFailed(failure, "Requested one-shot application failure");
+ return;
+ }
+ MessageBuilder builder(8);
+ auto text = builder.CreateString(method->name() + ":" +
+ in->message()->str());
+ const std::vector<int32_t> numbers(in->values()->begin(),
+ in->values()->end());
+ auto values = builder.CreateVector(numbers);
+ builder.Finish(brpc_fbtest::CreatePayload(
+ builder, in->value() + method->index(), text, values));
+ *response = builder.ReleaseMessage();
+ cntl->response_attachment().append(cntl->request_attachment());
+ }
+ std::atomic<int> rdma_calls{0};
+ std::atomic<int> fail_next_code{0};
+private:
+ ServiceDescriptor _descriptor;
+};
+
+class FlatBuffersRdmaTest : public ::testing::Test {
+protected:
+ void StartServer(brpc::SocketMode mode) {
+ ASSERT_EQ(0, server.AddFlatBuffersService(
+ &service, brpc::SERVER_DOESNT_OWN_SERVICE));
+ brpc::ServerOptions options;
+ options.socket_mode = mode;
+ ASSERT_EQ(0, server.Start("127.0.0.1:0", &options));
+ }
+
+ void StartChannel(brpc::SocketMode mode) {
+ brpc::ChannelOptions options;
+ options.protocol = "fb_rpc";
+ options.connection_type = "single";
+ options.socket_mode = mode;
+ options.timeout_ms = 10000;
+ options.connect_timeout_ms = 5000;
+ options.max_retry = 0;
+ ASSERT_EQ(0, channel.Init(server.listen_address(), &options));
+ }
+
+ void TearDown() override {
+ server.Stop(0);
+ server.Join();
+ }
+
+ void CheckTransport(bool expect_rdma) {
+ brpc::SocketUniquePtr socket;
+ ASSERT_EQ(0, brpc::Socket::Address(channel._server_id, &socket));
+ ASSERT_EQ(expect_rdma, IsRdmaOn(socket.get()));
+ if (!expect_rdma && socket->socket_mode() == brpc::SOCKET_MODE_RDMA) {
+ const auto* transport =
+ static_cast<const
brpc::RdmaTransport*>(socket->_transport.get());
+ EXPECT_EQ(brpc::rdma::RdmaEndpoint::FALLBACK_TCP,
+
transport->_rdma_ep->_state.load(butil::memory_order_acquire));
+ EXPECT_EQ(brpc::RdmaTransport::RDMA_OFF, transport->_rdma_state);
+ }
+ }
+
+ void RoundTrips(bool expect_rdma) {
+ const MethodDescriptor* method =
+ service.GetDescriptor()->FindMethodByIndex(41);
+ // The last payload exceeds the RDMA pool's largest block. The tiny
+ // initial builder size also exercises growth, and both peers must
+ // merge multiple receive blocks into an aligned contiguous message.
+ for (size_t size : {0u, 63u, 8193u, 3u * 1024 * 1024 + 17}) {
+ for (bool asynchronous : {false, true}) {
+ SCOPED_TRACE(size);
+ SCOPED_TRACE(asynchronous);
+ const Message request = MakePayload(size, 31, 19);
+ const std::string original = Bytes(request);
+ Message response;
+ brpc::Controller cntl;
+ std::string attachment(std::min<size_t>(size / 3, 131073),
'\0');
+ for (size_t i = 0; i < attachment.size(); ++i) {
+ attachment[i] = static_cast<char>(i % 251);
+ }
+ cntl.request_attachment().append(attachment);
+ Completion done;
+ const int calls_before = service.rdma_calls.load();
+ channel.FBCallMethod(method, &cntl, &request, &response,
+ asynchronous ? &done : nullptr);
+ if (asynchronous) {
+ brpc::Join(cntl.call_id());
+ EXPECT_EQ(1, done.calls());
+ }
+ ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
+ ASSERT_NO_FATAL_FAILURE(CheckTransport(expect_rdma));
+ EXPECT_EQ(calls_before + (expect_rdma ? 1 : 0),
+ service.rdma_calls.load());
+ ExpectReply(response, request, method);
+ EXPECT_EQ(attachment, cntl.response_attachment().to_string());
+ EXPECT_EQ(original, Bytes(request));
+ }
+ }
+
+ // Error responses have no application payload. They must complete
+ // sync and async calls over the negotiated transport as well.
+ for (bool asynchronous : {false, true}) {
+ SCOPED_TRACE(asynchronous);
+ const Message request = MakePayload();
+ Message response;
+ brpc::Controller cntl;
+ Completion done;
+ service.fail_next_code = EACCES;
+ const int calls_before = service.rdma_calls.load();
+ channel.FBCallMethod(method, &cntl, &request, &response,
+ asynchronous ? &done : nullptr);
+ if (asynchronous) {
+ brpc::Join(cntl.call_id());
+ EXPECT_EQ(1, done.calls());
+ }
+ ASSERT_EQ(EACCES, cntl.ErrorCode()) << cntl.ErrorText();
+ EXPECT_EQ(0u, response.size());
+ ASSERT_NO_FATAL_FAILURE(CheckTransport(expect_rdma));
+ EXPECT_EQ(calls_before + (expect_rdma ? 1 : 0),
+ service.rdma_calls.load());
+ }
+ }
+
+ PayloadService service;
+ brpc::Server server;
+ brpc::Channel channel;
+};
+
+TEST_F(FlatBuffersRdmaTest, PoolExhaustionFallsBackToRegisteredStorage) {
+ Message request;
+ {
+ ScopedAllocationFailures failures(true, false);
+ request = MakePayload(256 * 1024);
+ }
+ ASSERT_TRUE(request.Verify<Payload>());
+ const auto* block = request._iobuf.get_cur_ref().block;
+ ASSERT_TRUE(block->is_user_data());
+ void* data = block->data;
+ const uint32_t lkey = brpc::rdma::GetLKey(data);
+ ASSERT_NE(0u, lkey);
+ butil::IOBuf wire;
+ ASSERT_TRUE(request.append_msg_to_iobuf(wire));
+ EXPECT_EQ(lkey, wire.get_first_data_meta());
+
+ Message alias;
+ alias.CopyFrom(request);
+ request.Clear();
+ EXPECT_TRUE(alias.Verify<Payload>());
+ EXPECT_EQ(lkey, brpc::rdma::GetLKey(data));
+ alias.Clear();
+ EXPECT_EQ(lkey, brpc::rdma::GetLKey(data));
+ wire.clear();
+ EXPECT_EQ(0u, brpc::rdma::GetLKey(data));
+}
+
+// Its destructor runs after the RDMA atexit handler installed in main().
+Message g_late_message;
+
+class FlatBuffersRdmaDeathTest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ // Re-exec with a fresh RDMA context and its own exit handlers.
+ GTEST_FLAG_SET(death_test_style, "threadsafe");
+ }
+};
+
+TEST_F(FlatBuffersRdmaDeathTest, MessageOutlivesRdmaCleanup) {
+ ASSERT_EXIT({
+ g_late_message = MakePayload(3 * 1024 * 1024);
+ void* data = g_late_message._iobuf.get_cur_ref().block->data;
+ ASSERT_NE(0u, brpc::rdma::GetLKey(data));
+ std::exit(0); // Run RDMA cleanup, then the Message destructor.
+ }, ::testing::ExitedWithCode(0), "");
+}
+
+#if !BRPC_WITH_GLOG
+TEST_F(FlatBuffersRdmaDeathTest, ReleasesRegisteredMessageAfterRdmaDisable) {
+ ASSERT_EXIT({
+ Message message = MakePayload(3 * 1024 * 1024);
+ void* data = message._iobuf.get_cur_ref().block->data;
+ const uint32_t lkey = brpc::rdma::GetLKey(data);
+ ASSERT_NE(0u, lkey);
+ logging::FLAGS_crash_on_fatal_log = false;
+ brpc::rdma::GlobalDisableRdma();
+ ASSERT_FALSE(brpc::rdma::IsRdmaAvailable());
+ ASSERT_EQ(lkey, brpc::rdma::GetLKey(data));
+ message.Clear();
+ ASSERT_EQ(0u, brpc::rdma::GetLKey(data));
+ std::exit(0);
+ }, ::testing::ExitedWithCode(0), "");
+}
+#endif // !BRPC_WITH_GLOG
+
+TEST_F(FlatBuffersRdmaTest, RegistrationFailureStillSupportsTcp) {
+ ASSERT_NO_FATAL_FAILURE(StartServer(brpc::SOCKET_MODE_TCP));
+ ASSERT_NO_FATAL_FAILURE(StartChannel(brpc::SOCKET_MODE_TCP));
+ const MethodDescriptor* method =
+ service.GetDescriptor()->FindMethodByIndex(41);
+ for (size_t size : {256u * 1024, 3u * 1024 * 1024}) {
+ SCOPED_TRACE(size);
+ Message request;
+ {
+ ScopedAllocationFailures failures(true, true);
+ request = MakePayload(size);
+ }
+ ASSERT_TRUE(request.Verify<Payload>());
+ const auto* block = request._iobuf.get_cur_ref().block;
+ ASSERT_TRUE(block->is_user_data());
+ EXPECT_EQ(0u, brpc::rdma::GetLKey(block->data));
+ butil::IOBuf wire;
+ ASSERT_TRUE(request.append_msg_to_iobuf(wire));
+ EXPECT_EQ(0u, wire.get_first_data_meta());
+
+ // Receive-side reassembly must also tolerate pool and MR failures.
+ const std::string original = Bytes(request);
+ butil::IOBuf fragmented;
+ ASSERT_EQ(0, fragmented.append(request.data(), request.size()));
+ ASSERT_GT(fragmented.backing_block_num(), 1u);
+ Message parsed;
+ {
+ ScopedAllocationFailures failures(true, true);
+ ASSERT_TRUE(parsed.parse_msg_from_iobuf(
+ fragmented, request.size(), 0));
+ }
+ ASSERT_EQ(original, Bytes(parsed));
+ ASSERT_TRUE(parsed._iobuf.get_cur_ref().block->is_user_data());
+ EXPECT_EQ(0u, brpc::rdma::GetLKey(
+ parsed._iobuf.get_cur_ref().block->data));
+ request.Clear();
+ wire.clear();
+
+ Message response;
+ brpc::Controller cntl;
+ channel.FBCallMethod(method, &cntl, &parsed, &response, nullptr);
+ ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
+ ASSERT_NO_FATAL_FAILURE(CheckTransport(false));
+ ExpectReply(response, parsed, method);
+ EXPECT_EQ(original, Bytes(parsed));
+ }
+}
+
+TEST_F(FlatBuffersRdmaTest, RegistrationFailureReturnsRdmaMemoryError) {
+ ASSERT_NO_FATAL_FAILURE(StartServer(brpc::SOCKET_MODE_RDMA));
+ ASSERT_NO_FATAL_FAILURE(StartChannel(brpc::SOCKET_MODE_RDMA));
+ const MethodDescriptor* method =
+ service.GetDescriptor()->FindMethodByIndex(41);
+ const Message warmup = MakePayload();
+ Message response;
+ brpc::Controller cntl;
+ channel.FBCallMethod(method, &cntl, &warmup, &response, nullptr);
+ ASSERT_FALSE(cntl.Failed()) << cntl.ErrorText();
+ ASSERT_NO_FATAL_FAILURE(CheckTransport(true));
+
+ Message request;
+ {
+ ScopedAllocationFailures failures(true, true);
+ request = MakePayload(256 * 1024);
+ }
+ ASSERT_TRUE(request.Verify<Payload>());
+ const int calls_before = service.rdma_calls.load();
+ cntl.Reset();
+ response.Clear();
+ channel.FBCallMethod(method, &cntl, &request, &response, nullptr);
+ EXPECT_EQ(brpc::ERDMAMEM, cntl.ErrorCode()) << cntl.ErrorText();
+ EXPECT_EQ(calls_before, service.rdma_calls.load());
+ EXPECT_TRUE(request.Verify<Payload>());
+}
+
+TEST_F(FlatBuffersRdmaTest, ProtocolAdmissionAndChannelOptions) {
+ EXPECT_TRUE(brpc::rdma::SupportedByRdma("fb_rpc"));
+ EXPECT_TRUE(brpc::rdma::SupportedByRdma("baidu_std"));
+ EXPECT_FALSE(brpc::rdma::SupportedByRdma("http"));
+ ASSERT_NO_FATAL_FAILURE(StartServer(brpc::SOCKET_MODE_TCP));
+ for (const char* connection_type : {"single", "pooled", "short"}) {
+ SCOPED_TRACE(connection_type);
+ brpc::Channel candidate;
+ brpc::ChannelOptions options;
+ options.protocol = "fb_rpc";
+ options.connection_type = connection_type;
+ options.socket_mode = brpc::SOCKET_MODE_RDMA;
+ ASSERT_EQ(0, candidate.Init(server.listen_address(), &options));
+ }
+}
+
+TEST_F(FlatBuffersRdmaTest, RdmaClientFallsBackToTcpServer) {
+ ASSERT_NO_FATAL_FAILURE(StartServer(brpc::SOCKET_MODE_TCP));
+ ASSERT_NO_FATAL_FAILURE(StartChannel(brpc::SOCKET_MODE_RDMA));
+ ASSERT_NO_FATAL_FAILURE(RoundTrips(false));
+}
+
+TEST_F(FlatBuffersRdmaTest, TcpClientCallsRdmaServer) {
+ ASSERT_NO_FATAL_FAILURE(StartServer(brpc::SOCKET_MODE_RDMA));
+ ASSERT_NO_FATAL_FAILURE(StartChannel(brpc::SOCKET_MODE_TCP));
+ ASSERT_NO_FATAL_FAILURE(RoundTrips(false));
+}
+
+TEST_F(FlatBuffersRdmaTest, HardwareRdmaRoundTrips) {
+ ASSERT_TRUE(brpc::rdma::IsRdmaAvailable());
+ ASSERT_NO_FATAL_FAILURE(StartServer(brpc::SOCKET_MODE_RDMA));
+ ASSERT_NO_FATAL_FAILURE(StartChannel(brpc::SOCKET_MODE_RDMA));
+ ASSERT_NO_FATAL_FAILURE(RoundTrips(true));
+}
+
+} // namespace
+
+int main(int argc, char* argv[]) {
+ testing::InitGoogleTest(&argc, argv);
+ GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
+ // RDMA must initialize before any test allocates IOBuf storage.
+ brpc::GlobalInitializeOrDie();
+ brpc::rdma::GlobalRdmaInitializeOrDie();
+ InstallAllocationHooks();
+ return RUN_ALL_TESTS();
+}
+#endif // BRPC_WITH_RDMA
+#endif // BRPC_WITH_FLATBUFFERS
diff --git a/test/brpc_rdma_unittest.cpp b/test/brpc_rdma_unittest.cpp
index 5255d2315..bf3aff279 100644
--- a/test/brpc_rdma_unittest.cpp
+++ b/test/brpc_rdma_unittest.cpp
@@ -4439,6 +4439,18 @@ TEST(RdmaInlineDataTest, create_qp_reuses_inline_size) {
rdma::g_inline_data_request.store(UINT32_MAX);
}
+TEST(RdmaProtocolTest, supported_protocols) {
+ EXPECT_TRUE(rdma::SupportedByRdma("baidu_std"));
+#if BRPC_WITH_FLATBUFFERS
+ EXPECT_TRUE(rdma::SupportedByRdma("fb_rpc"));
+#else
+ EXPECT_FALSE(rdma::SupportedByRdma("fb_rpc"));
+#endif
+ EXPECT_FALSE(rdma::SupportedByRdma("http"));
+ EXPECT_FALSE(rdma::SupportedByRdma("h2"));
+ EXPECT_FALSE(rdma::SupportedByRdma("unknown_protocol"));
+}
+
// The send-path decision of CutFromIOBufList(), which itself needs an
// initialized RDMA device.
TEST(RdmaInlineDataTest, should_post_inline) {
diff --git a/test/run_tests.sh b/test/run_tests.sh
index daebf6f4a..dd1c0d1a4 100755
--- a/test/run_tests.sh
+++ b/test/run_tests.sh
@@ -26,6 +26,10 @@ test_bins="test_butil test_bvar bthread*unittest
brpc*unittest"
export ASAN_OPTIONS="detect_leaks=1:detect_stack_use_after_return=1"
# Keep the original stdin on fd 3 for asynchronous test processes.
for test_bin in $test_bins; do
+ # This hardware test must be invoked explicitly on an RDMA host.
+ if [ "$test_bin" = "brpc_flatbuffers_rdma_unittest" ]; then
+ continue
+ fi
test_num=$((test_num + 1))
>&2 echo "[runtest] $test_bin"
# A passing death test may leave a core behind. Keep only cores from the
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]