From 8d494e12611b1b389400e8e50786cf0a7fecd0c2 Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Mon, 23 Nov 2026 23:25:27 -0600 Subject: [PATCH 01/18] Don't go back further than a freshly booted host in the steady clock past tests (#3430) The steady clock counts from boot, and a negative time point cannot be stored in rclcpp::Time. Going back 1000 s therefore throws on hosts that have been up for less than that, e.g. fresh CI VMs. Go back 1 s instead. Signed-off-by: Michael Carroll --- rclcpp/test/rclcpp/test_time.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/rclcpp/test/rclcpp/test_time.cpp b/rclcpp/test/rclcpp/test_time.cpp index a83c16a73d..5b95095259 100644 --- a/rclcpp/test/rclcpp/test_time.cpp +++ b/rclcpp/test/rclcpp/test_time.cpp @@ -500,7 +500,9 @@ TEST_F(TestClockSleep, sleep_until_basic_steady) { TEST_F(TestClockSleep, sleep_until_steady_past_returns_immediately) { rclcpp::Clock clock(RCL_STEADY_TIME); - auto until = clock.now() - rclcpp::Duration(1000, 0); + // The steady clock counts from boot and a negative time point cannot be stored, so don't go back + // further than a host that has just booted can handle. + auto until = clock.now() - rclcpp::Duration(1, 0); // This should return immediately, other possible behavior might be sleep forever and timeout ASSERT_TRUE(clock.sleep_until(until)); } @@ -679,7 +681,8 @@ TEST_F(TestClockSleep, sleep_for_basic_steady) { TEST_F(TestClockSleep, sleep_for_steady_past_returns_immediately) { rclcpp::Clock clock(RCL_STEADY_TIME); - auto rel_time = rclcpp::Duration(-1000, 0); + // Same as above: now() + rel_time must not be negative on a freshly booted host. + auto rel_time = rclcpp::Duration(-1, 0); // This should return immediately ASSERT_TRUE(clock.sleep_for(rel_time)); } From 3d91c3bb4f9f34e7c8e1b5e1febffd0b27c832cb Mon Sep 17 00:00:00 2001 From: Tomoya Fujita Date: Tue, 24 Nov 2026 18:03:09 +0900 Subject: [PATCH 02/18] Make Service::send_response take a const response (#3400) Service::send_response now takes const ServiceT::Response &, and GenericService::send_response takes const SharedResponse &. The response is only forwarded to rcl_send_response, which now takes a const pointer. Existing callers passing non-const responses continue to compile. Companion change for ros2/rmw#437, which makes rmw_send_response take a const void * ros_response. A response only needs to be read to be serialized and sent, so the pointer should be const, consistent with rmw_send_request. Signed-off-by: Tomoya Fujita Co-authored-by: Claude Fable 5.1 --- rclcpp/include/rclcpp/generic_service.hpp | 2 +- rclcpp/include/rclcpp/service.hpp | 2 +- rclcpp/src/rclcpp/generic_service.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/rclcpp/include/rclcpp/generic_service.hpp b/rclcpp/include/rclcpp/generic_service.hpp index 8a4468aa1f..46dc95d5fc 100644 --- a/rclcpp/include/rclcpp/generic_service.hpp +++ b/rclcpp/include/rclcpp/generic_service.hpp @@ -292,7 +292,7 @@ class GenericService RCLCPP_PUBLIC void - send_response(rmw_request_id_t & req_id, SharedResponse & response); + send_response(rmw_request_id_t & req_id, const SharedResponse & response); private: RCLCPP_DISABLE_COPY(GenericService) diff --git a/rclcpp/include/rclcpp/service.hpp b/rclcpp/include/rclcpp/service.hpp index 387f33763c..3afe1d2e81 100644 --- a/rclcpp/include/rclcpp/service.hpp +++ b/rclcpp/include/rclcpp/service.hpp @@ -430,7 +430,7 @@ class Service } void - send_response(rmw_request_id_t & req_id, typename ServiceT::Response & response) + send_response(rmw_request_id_t & req_id, const typename ServiceT::Response & response) { rcl_ret_t ret = rcl_send_response(get_service_handle().get(), &req_id, &response); diff --git a/rclcpp/src/rclcpp/generic_service.cpp b/rclcpp/src/rclcpp/generic_service.cpp index d9975060ab..4a818f3ced 100644 --- a/rclcpp/src/rclcpp/generic_service.cpp +++ b/rclcpp/src/rclcpp/generic_service.cpp @@ -159,7 +159,7 @@ GenericService::handle_request( } void -GenericService::send_response(rmw_request_id_t & req_id, SharedResponse & response) +GenericService::send_response(rmw_request_id_t & req_id, const SharedResponse & response) { rcl_ret_t ret = rcl_send_response(get_service_handle().get(), &req_id, response.get()); From d2759e4523a511b3e73348ca2f9168214eed91cf Mon Sep 17 00:00:00 2001 From: Skyler Medeiros Date: Tue, 24 Nov 2026 08:19:18 -0800 Subject: [PATCH 03/18] fix(scheduler): always wakeup worker threads for ready entities in reentrant groups (#3426) Signed-off-by: Skyler Medeiros Co-authored-by: Skyler Medeiros --- .../events_cbg_executor/scheduler.hpp | 11 ++- .../test_events_cbg_executor_reentrant.cpp | 86 +++++++++++++++++++ 2 files changed, 93 insertions(+), 4 deletions(-) diff --git a/rclcpp/src/rclcpp/executors/events_cbg_executor/scheduler.hpp b/rclcpp/src/rclcpp/executors/events_cbg_executor/scheduler.hpp index fb6241290c..06095a3944 100644 --- a/rclcpp/src/rclcpp/executors/events_cbg_executor/scheduler.hpp +++ b/rclcpp/src/rclcpp/executors/events_cbg_executor/scheduler.hpp @@ -268,16 +268,19 @@ class CBGScheduler fun(); - if(not_ready || !idle) { + // A reentrant group can execute the new entity in parallel to the + // ones already executing, so it must reach the scheduler even if + // the group is not idle. + if(not_ready || (!idle && type != CallbackGroupType::Reentrant)) { return; } idle = false; } - // If we reached this point, we were idle and now have work, - // therefore we need to move this callback group into the list - // of ready callback groups. + // If we reached this point, we were idle (or are reentrant) and + // now have work, therefore we need to move this callback group into + // the list of ready callback groups. scheduler.callback_group_ready(this, true); } diff --git a/rclcpp/test/rclcpp/executors/test_events_cbg_executor_reentrant.cpp b/rclcpp/test/rclcpp/executors/test_events_cbg_executor_reentrant.cpp index 94ade49e25..93703fc93c 100644 --- a/rclcpp/test/rclcpp/executors/test_events_cbg_executor_reentrant.cpp +++ b/rclcpp/test/rclcpp/executors/test_events_cbg_executor_reentrant.cpp @@ -126,3 +126,89 @@ TEST_F(TestEventsCBGExecutorReentrant, reentract_callback_group_runs_concurrentl EXPECT_FALSE(sub2_timed_out.load()) << "sub 2 timed out waiting for sub 1 to start running -- " "the reentrant callback group appears to be serialized"; } + +/* + * Test that an entity of a reentrant callback group which becomes ready while + * another entity of the same group is already executing gets executed + * concurrently, instead of waiting for the executing one to finish. + * + * The second message is only published once the first callback is running, + * so the event for the second subscription always arrives while the group + * is busy. + * + * Related issue: https://github.com/ros2/rclcpp/issues/3328 + */ +TEST_F(TestEventsCBGExecutorReentrant, entity_ready_during_execution_runs_concurrently) +{ + auto node = std::make_shared("test_events_cbg_executor_reentrant_busy"); + + std::mutex mutex; + std::condition_variable cv; + bool sub_a_started = false; + bool sub_b_started = false; + std::atomic_bool sub_a_timed_out{false}; + + rclcpp::SubscriptionOptions sub_opt; + sub_opt.callback_group = node->create_callback_group(rclcpp::CallbackGroupType::Reentrant); + + auto sub_a = node->create_subscription( + "reentrant_busy_a", 10, + [&](test_msgs::msg::Empty) { + std::unique_lock lock(mutex); + sub_a_started = true; + cv.notify_all(); + if (!cv.wait_for(lock, 5s, [&]() {return sub_b_started;})) { + sub_a_timed_out = true; + } + }, + sub_opt); + + auto sub_b = node->create_subscription( + "reentrant_busy_b", 10, + [&](test_msgs::msg::Empty) { + std::lock_guard lock(mutex); + sub_b_started = true; + cv.notify_all(); + }, + sub_opt); + + auto pub_a = node->create_publisher("reentrant_busy_a", 10); + auto pub_b = node->create_publisher("reentrant_busy_b", 10); + + auto discovery_deadline = std::chrono::steady_clock::now() + 5s; + while ((pub_a->get_subscription_count() == 0 || pub_b->get_subscription_count() == 0) && + std::chrono::steady_clock::now() < discovery_deadline) + { + std::this_thread::sleep_for(10ms); + } + ASSERT_EQ(pub_a->get_subscription_count(), 1u); + ASSERT_EQ(pub_b->get_subscription_count(), 1u); + + rclcpp::executors::EventsCBGExecutor executor(rclcpp::ExecutorOptions(), 2u); + executor.add_node(node); + std::thread spin_thread([&executor]() {executor.spin();}); + + pub_a->publish(test_msgs::msg::Empty()); + bool a_started; + { + std::unique_lock lock(mutex); + a_started = cv.wait_for(lock, 5s, [&]() {return sub_a_started;}); + } + if (a_started) { + pub_b->publish(test_msgs::msg::Empty()); + } + + bool b_started; + { + std::unique_lock lock(mutex); + b_started = cv.wait_for(lock, 10s, [&]() {return sub_b_started;}); + } + + executor.cancel(); + spin_thread.join(); + + ASSERT_TRUE(a_started) << "sub a never ran"; + EXPECT_TRUE(b_started) << "sub b never ran"; + EXPECT_FALSE(sub_a_timed_out.load()) << + "sub b only ran after sub a finished -- the reentrant callback group appears to be serialized"; +} From 0c8d39f34319476b8c1a3fe885690ad701b7a01a Mon Sep 17 00:00:00 2001 From: Skyler Medeiros Date: Wed, 25 Nov 2026 10:11:02 -0800 Subject: [PATCH 04/18] perf: look up EventsCBGExecutor timers by an id instead of weak_ptr (#3424) * fix: look up timers in EventsCBGExecutor timer manager by ID instead of weak ptr Signed-off-by: Skyler Medeiros * test: wait until the node's default callback group is removed before readding Signed-off-by: Skyler Medeiros --------- Signed-off-by: Skyler Medeiros Co-authored-by: Skyler Medeiros --- .../events_cbg_executor/timer_manager.hpp | 69 ++++++++++--------- ...test_events_cbg_executor_timer_removal.cpp | 41 +++++++++++ 2 files changed, 77 insertions(+), 33 deletions(-) diff --git a/rclcpp/src/rclcpp/executors/events_cbg_executor/timer_manager.hpp b/rclcpp/src/rclcpp/executors/events_cbg_executor/timer_manager.hpp index 6da6f67aaf..e87c4028c8 100644 --- a/rclcpp/src/rclcpp/executors/events_cbg_executor/timer_manager.hpp +++ b/rclcpp/src/rclcpp/executors/events_cbg_executor/timer_manager.hpp @@ -19,9 +19,11 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -122,17 +124,20 @@ class ClockConditionalVariable */ class TimerQueue { - struct TimerData : std::enable_shared_from_this + struct TimerData { TimerData( + uint64_t id, std::shared_ptr rcl_ref, std::weak_ptr timer_ref, rclcpp::Clock::SharedPtr clock, std::function & executed_cb)> timer_ready_callback) - : rcl_ref(std::move(rcl_ref)), timer_ref(std::move(timer_ref)), clock(std::move(clock)), - timer_ready_callback(std::move(timer_ready_callback)) + : id(id), rcl_ref(std::move(rcl_ref)), timer_ref(std::move(timer_ref)), + clock(std::move(clock)), timer_ready_callback(std::move(timer_ready_callback)) {} + // key of this timer in the queue, never reused + const uint64_t id; std::shared_ptr rcl_ref; std::weak_ptr timer_ref; rclcpp::Clock::SharedPtr clock; @@ -173,7 +178,7 @@ class TimerQueue std::scoped_lock l(mutex); - for (auto & tData : all_timers) { + for (auto & [id, tData] : all_timers) { if (auto shrPtr = tData->timer_ref.lock()) { shrPtr->clear_on_reset_callback(); } @@ -223,13 +228,13 @@ class TimerQueue auto it = std::find_if( all_timers.begin(), all_timers.end(), - [rcl_ref = timer->get_timer_handle()](const std::shared_ptr & d) + [rcl_ref = timer->get_timer_handle()](const auto & e) { - return d->rcl_ref == rcl_ref; + return e.second->rcl_ref == rcl_ref; }); if (it != all_timers.end()) { - const TimerData * data_ptr = it->get(); + const TimerData * data_ptr = it->second.get(); auto it2 = std::find_if( running_timers.begin(), running_timers.end(), [data_ptr](const auto & e) { @@ -239,7 +244,7 @@ class TimerQueue if(it2 != running_timers.end()) { running_timers.erase(it2); } - clear_on_schedule_change_callback(**it); + clear_on_schedule_change_callback(*it->second); all_timers.erase(it); } @@ -275,16 +280,17 @@ class TimerQueue return; } - std::shared_ptr data = std::make_shared( - std::move(handle), timer, timer->get_clock(), timer_ready_callback); + const uint64_t id = next_timer_id.fetch_add(1); + auto data = std::make_unique( + id, std::move(handle), timer, timer->get_clock(), timer_ready_callback); timer->set_on_reset_callback( - [weak_data = data->weak_from_this(), this](size_t) { + [id, this](size_t) { std::scoped_lock l(mutex); // the timer may have been removed concurrently - auto data = weak_data.lock(); - if (data && !remove_if_dropped(data.get())) { - add_timer_to_running_map(data.get()); + auto it = all_timers.find(id); + if (it != all_timers.end() && !remove_if_dropped(it->second.get())) { + add_timer_to_running_map(it->second.get()); } }); @@ -306,7 +312,7 @@ class TimerQueue // this will wake up the timer thread if needed add_timer_to_running_map(data.get()); - all_timers.emplace_back(std::move(data) ); + all_timers.emplace(id, std::move(data)); } } @@ -374,16 +380,9 @@ class TimerQueue } // timer was deleted - auto it = std::find_if( - all_timers.begin(), all_timers.end(), [timer_data](const std::shared_ptr & e) { - return timer_data == e.get(); - } - ); - - if (it != all_timers.end()) { - clear_on_schedule_change_callback(**it); - all_timers.erase(it); - } + clear_on_schedule_change_callback(*timer_data); + const uint64_t id = timer_data->id; + all_timers.erase(id); return true; } return false; @@ -438,7 +437,7 @@ class TimerQueue */ void rekey_pending_timers() { - for (auto & timer_data : all_timers) { + for (auto & [id, timer_data] : all_timers) { if (timer_data->rekey_pending.exchange(false) && timer_data->in_running_list) { add_timer_to_running_map(timer_data.get()); } @@ -467,15 +466,17 @@ class TimerQueue } if (time_until_call <= 0) { - auto timer_done_callback = [weak_data = timer_data->weak_from_this(), this] () + auto timer_done_callback = [id = timer_data->id, this] () { // The timer may have been removed from this queue while its callback - // was executed, e.g. by removing its node or by a shutdown. all_timers - // is the only owner of the timer data and is only modified under the - // mutex, so a successful lock under the mutex means it is still queued. + // was executed, e.g. by removing its node or by a shutdown. Ids are never + // reused, so a removed timer is not found, even if it was added again. + // Capture nothing larger: this is copied on every fire, and has to stay + // in the small buffer of std::function to avoid allocating. std::scoped_lock l(mutex); - if (auto data = weak_data.lock()) { - add_timer_to_running_map(data.get()); + auto it = all_timers.find(id); + if (it != all_timers.end()) { + add_timer_to_running_map(it->second.get()); } }; @@ -565,7 +566,9 @@ class TimerQueue // set by the schedule change callback, consumed by the timer thread std::atomic_bool rekey_pending_any = false; - std::vector> all_timers; + std::atomic next_timer_id = 0; + + std::unordered_map> all_timers; using TimerMap = std::multimap; TimerMap running_timers; diff --git a/rclcpp/test/rclcpp/executors/test_events_cbg_executor_timer_removal.cpp b/rclcpp/test/rclcpp/executors/test_events_cbg_executor_timer_removal.cpp index 427c1c15c6..5aa7c21316 100644 --- a/rclcpp/test/rclcpp/executors/test_events_cbg_executor_timer_removal.cpp +++ b/rclcpp/test/rclcpp/executors/test_events_cbg_executor_timer_removal.cpp @@ -81,6 +81,17 @@ class TestEventsCBGExecutorTimerRemoval : public testing::Test return node->get_node_base_interface()->get_associated_with_executor_atomic().load(); } + bool executor_has_default_callback_group() + { + const auto default_group = node->get_node_base_interface()->get_default_callback_group(); + for (const auto & weak_group : executor->get_all_callback_groups()) { + if (weak_group.lock() == default_group) { + return true; + } + } + return false; + } + bool wait_for_callback() { return callback_entered.get_future().wait_for(5s) == std::future_status::ready; @@ -142,3 +153,33 @@ TEST_F(TestEventsCBGExecutorTimerRemoval, remove_node_during_spin) std::this_thread::sleep_for(50ms); EXPECT_EQ(calls, 1); } + +TEST_F(TestEventsCBGExecutorTimerRemoval, remove_and_readd_node_during_spin) +{ + spin_thread = std::thread([this]() {executor->spin();}); + ASSERT_TRUE(wait_for_callback()); + + // the callback that is still running belongs to the bookkeeping of the removed timer, + // when it returns it must not touch the bookkeeping of the timer that was added again + executor->remove_node(node); + // wait until the executor processed the removal before the node is added again + const auto deadline = std::chrono::steady_clock::now() + 5s; + while (executor_has_default_callback_group() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(1ms); + } + ASSERT_FALSE(executor_has_default_callback_group()); + executor->add_node(node); + ASSERT_FALSE(callback_returned) << "the node was not added again while the callback was running"; + + while (!callback_returned && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(1ms); + } + ASSERT_TRUE(callback_returned); + + // the timer that was added again keeps running after the callback returned + const int calls_after_return = calls; + while (calls < calls_after_return + 10 && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(1ms); + } + EXPECT_GE(calls, calls_after_return + 10); +} From dd1a4f445d78b5bf2747179d5b28f33f8bf82552 Mon Sep 17 00:00:00 2001 From: Christophe Bedard Date: Fri, 27 Nov 2026 00:54:09 -0800 Subject: [PATCH 05/18] Remove deprecated NodeParameters::CallbacksContainerType (#3442) `CallbacksContainerType` has been deprecated since https://github.com/ros2/rclcpp/pull/1947 (Iron) in favor of `OnSetCallbacksHandleContainer`. Signed-off-by: Christophe Bedard --- rclcpp/include/rclcpp/node_interfaces/node_parameters.hpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/rclcpp/include/rclcpp/node_interfaces/node_parameters.hpp b/rclcpp/include/rclcpp/node_interfaces/node_parameters.hpp index 9a8458ec89..17432d736d 100644 --- a/rclcpp/include/rclcpp/node_interfaces/node_parameters.hpp +++ b/rclcpp/include/rclcpp/node_interfaces/node_parameters.hpp @@ -221,8 +221,6 @@ class NodeParameters : public NodeParametersInterface using PreSetCallbacksHandleContainer = std::list; using OnSetCallbacksHandleContainer = std::list; using PostSetCallbacksHandleContainer = std::list; - using CallbacksContainerType [[deprecated("use OnSetCallbacksHandleContainer instead")]] = - OnSetCallbacksHandleContainer; protected: RCLCPP_PUBLIC From 585664e5e5e195721b4648e108959f55202d52ac Mon Sep 17 00:00:00 2001 From: Christophe Bedard Date: Fri, 27 Nov 2026 10:07:42 -0800 Subject: [PATCH 06/18] Pass --ros-args before remap rules in node interface tests (#3443) `TestNodeService` and `TestNodeTopics` passed `-r foo:=bar` without `--ros-args`, so `foo:=bar` was only applied as a remap rule through `rcl`'s deprecated support for remap rules outside of `--ros-args`. Signed-off-by: Christophe Bedard --- rclcpp/test/rclcpp/node_interfaces/test_node_services.cpp | 2 +- rclcpp/test/rclcpp/node_interfaces/test_node_topics.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/rclcpp/test/rclcpp/node_interfaces/test_node_services.cpp b/rclcpp/test/rclcpp/node_interfaces/test_node_services.cpp index 955b5272b1..d9f0380a4e 100644 --- a/rclcpp/test/rclcpp/node_interfaces/test_node_services.cpp +++ b/rclcpp/test/rclcpp/node_interfaces/test_node_services.cpp @@ -65,7 +65,7 @@ class TestNodeService : public ::testing::Test rclcpp::init(0, nullptr); rclcpp::NodeOptions options{}; - options.arguments(std::vector{"-r", "foo:=bar"}); + options.arguments(std::vector{"--ros-args", "-r", "foo:=bar"}); node = std::make_shared("node", "ns", options); // This dynamic cast is not necessary for the unittest itself, but instead is used to ensure diff --git a/rclcpp/test/rclcpp/node_interfaces/test_node_topics.cpp b/rclcpp/test/rclcpp/node_interfaces/test_node_topics.cpp index bd00ae5d0e..ab5d3a3512 100644 --- a/rclcpp/test/rclcpp/node_interfaces/test_node_topics.cpp +++ b/rclcpp/test/rclcpp/node_interfaces/test_node_topics.cpp @@ -119,7 +119,7 @@ class TestNodeTopics : public ::testing::Test { rclcpp::init(0, nullptr); rclcpp::NodeOptions options{}; - options.arguments(std::vector{"-r", "foo:=bar"}); + options.arguments(std::vector{"--ros-args", "-r", "foo:=bar"}); node = std::make_shared("node", "ns", options); // This dynamic cast is not necessary for the unittest itself, but instead is used to ensure From 2e2d11ec2dcb179d1f184c73d09cd0c43877fc15 Mon Sep 17 00:00:00 2001 From: Christophe Bedard Date: Fri, 27 Nov 2026 15:17:24 -0800 Subject: [PATCH 07/18] Remove deprecated component_container_{mt,isolated,event} (#3447) These executables have been deprecated since https://github.com/ros2/rclcpp/pull/3134 (Lyrical), which said that they would be removed in M-turtle, in favor of `component_container` with the `--executor-type` and `--isolated` options. Signed-off-by: Christophe Bedard --- rclcpp_components/CMakeLists.txt | 20 +------ .../src/component_container_event.cpp | 44 -------------- .../src/component_container_isolated.cpp | 60 ------------------- .../src/component_container_mt.cpp | 47 --------------- 4 files changed, 1 insertion(+), 170 deletions(-) delete mode 100644 rclcpp_components/src/component_container_event.cpp delete mode 100644 rclcpp_components/src/component_container_isolated.cpp delete mode 100644 rclcpp_components/src/component_container_mt.cpp diff --git a/rclcpp_components/CMakeLists.txt b/rclcpp_components/CMakeLists.txt index 4e52378246..7e212cd3bc 100644 --- a/rclcpp_components/CMakeLists.txt +++ b/rclcpp_components/CMakeLists.txt @@ -62,29 +62,11 @@ add_executable( ) target_link_libraries(component_container PRIVATE component_manager rclcpp::rclcpp) -add_executable( - component_container_event - src/component_container_event.cpp -) -target_link_libraries(component_container_event PRIVATE component_manager rclcpp::rclcpp) - set(node_main_template_install_dir "share/${PROJECT_NAME}") install(FILES src/node_main.cpp.in DESTINATION ${node_main_template_install_dir}) -add_executable( - component_container_mt - src/component_container_mt.cpp -) -target_link_libraries(component_container_mt PRIVATE component_manager rclcpp::rclcpp) - -add_executable( - component_container_isolated - src/component_container_isolated.cpp -) -target_link_libraries(component_container_isolated PRIVATE component_manager rclcpp::rclcpp) - if(BUILD_TESTING) find_package(ament_lint_auto REQUIRED) find_package(ament_cmake_google_benchmark REQUIRED) @@ -149,7 +131,7 @@ install( # Install executables install( - TARGETS component_container component_container_mt component_container_isolated component_container_event + TARGETS component_container RUNTIME DESTINATION lib/${PROJECT_NAME} ) diff --git a/rclcpp_components/src/component_container_event.cpp b/rclcpp_components/src/component_container_event.cpp deleted file mode 100644 index a396ededcd..0000000000 --- a/rclcpp_components/src/component_container_event.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2025 Open Source Robotics Foundation, Inc. -// -// Licensed 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 - -#include "rcpputils/compile_warnings.hpp" -#include "rclcpp/utilities.hpp" -#include "rclcpp/experimental/executors/events_executor/events_executor.hpp" - -#include "rclcpp_components/component_manager.hpp" - -int main(int argc, char * argv[]) -{ - RCUTILS_LOG_WARN_NAMED("component_container_event", - "This executable is deprecated and will be removed in M-turtle.\n" - "Use 'component_container --executor-type events-cbg' instead."); - - /// Component container with an events executor. - rclcpp::init(argc, argv); - - // Disable deprecation warnings while maintaining the EventsExecutor - RCPPUTILS_DEPRECATION_WARNING_OFF_START - auto exec = std::make_shared(); - RCPPUTILS_DEPRECATION_WARNING_OFF_STOP - - auto node = std::make_shared(exec); - exec->add_node(node); - exec->spin(); - - rclcpp::shutdown(); - - return 0; -} diff --git a/rclcpp_components/src/component_container_isolated.cpp b/rclcpp_components/src/component_container_isolated.cpp deleted file mode 100644 index 5fb93bfac7..0000000000 --- a/rclcpp_components/src/component_container_isolated.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2021 Open Source Robotics Foundation, Inc. -// -// Licensed 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 -#include -#include - -#include "rclcpp/executors/single_threaded_executor.hpp" -#include "rclcpp/executors/multi_threaded_executor.hpp" -#include "rclcpp/node.hpp" -#include "rclcpp/utilities.hpp" - -#include "rclcpp_components/component_manager_isolated.hpp" - -int main(int argc, char * argv[]) -{ - RCUTILS_LOG_WARN_NAMED("component_container_isolated", - "This executable is deprecated and will be removed in M-turtle.\n" - "Use 'component_container --executor-type single-threaded --isolated' instead.\n" - "For a multi-threaded isolated setup," - " use 'component_container --executor-type multi-threaded --isolated'."); - - /// Component container with dedicated single-threaded executors for each components. - rclcpp::init(argc, argv); - // parse arguments - bool use_multi_threaded_executor{false}; - std::vector args = rclcpp::remove_ros_arguments(argc, argv); - for (auto & arg : args) { - if (arg == std::string("--use_multi_threaded_executor")) { - use_multi_threaded_executor = true; - } - } - // create executor and component manager - auto exec = std::make_shared(); - rclcpp::Node::SharedPtr node; - if (use_multi_threaded_executor) { - using ComponentManagerIsolated = - rclcpp_components::ComponentManagerIsolated; - node = std::make_shared(exec); - } else { - using ComponentManagerIsolated = - rclcpp_components::ComponentManagerIsolated; - node = std::make_shared(exec); - } - exec->add_node(node); - exec->spin(); - - return 0; -} diff --git a/rclcpp_components/src/component_container_mt.cpp b/rclcpp_components/src/component_container_mt.cpp deleted file mode 100644 index bb2efe3e3c..0000000000 --- a/rclcpp_components/src/component_container_mt.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2019 Open Source Robotics Foundation, Inc. -// -// Licensed 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 - -#include "rclcpp/executor_options.hpp" -#include "rclcpp/executors/multi_threaded_executor.hpp" -#include "rclcpp/utilities.hpp" - -#include "rclcpp_components/component_manager.hpp" - -int main(int argc, char * argv[]) -{ - RCUTILS_LOG_WARN_NAMED("component_container_mt", - "This executable is deprecated and will be removed in M-turtle.\n" - "Use 'component_container --executor-type multi-threaded' instead."); - /// Component container with a multi-threaded executor. - rclcpp::init(argc, argv); - - rclcpp::executors::MultiThreadedExecutor::SharedPtr exec = nullptr; - const auto node = std::make_shared(); - if (node->has_parameter("thread_num")) { - const auto thread_num = node->get_parameter("thread_num").as_int(); - exec = std::make_shared( - rclcpp::ExecutorOptions{}, thread_num); - } else { - exec = std::make_shared(); - } - node->set_executor(exec); - exec->add_node(node); - exec->spin(); - - rclcpp::shutdown(); - - return 0; -} From e4e9ad12fddb9b2f61ac77fb53394b1ffe3bdf70 Mon Sep 17 00:00:00 2001 From: Christophe Bedard Date: Fri, 27 Nov 2026 16:08:06 -0800 Subject: [PATCH 08/18] Remove deprecated free spin_some() and spin_all() functions (#3448) `rclcpp::spin_some()` and `rclcpp::spin_all()` have been deprecated since https://github.com/ros2/rclcpp/pull/2848 (Lyrical), since they create a new executor and add the node to it on every call. Use the methods with the same names on an executor instead. Signed-off-by: Christophe Bedard --- rclcpp/include/rclcpp/executors.hpp | 80 ----------------------------- rclcpp/src/rclcpp/executors.cpp | 37 ------------- 2 files changed, 117 deletions(-) diff --git a/rclcpp/include/rclcpp/executors.hpp b/rclcpp/include/rclcpp/executors.hpp index bdd6a13ef8..05cf37ebdf 100644 --- a/rclcpp/include/rclcpp/executors.hpp +++ b/rclcpp/include/rclcpp/executors.hpp @@ -29,86 +29,6 @@ namespace rclcpp { -/** - * @brief Create a default single-threaded executor and execute all available work exhaustively. - * @param node_ptr Shared pointer to the base interface of the node to spin. - * @param max_duration max duration to spin - * - * This method is deprecated because it can lead to very bad performance if used in a loop: - * each call will create a new executor and register the node, which is an expensive operation. - * It's recommended to always manually instantiate an executor and call the methods with - * the same name on it. - * For example: - * SingleThreadedExecutor executor; - * executor.add_node(node_ptr); - * executor.spin_all(max_duration); - * If you are using a non-default context, this should be passed to the executor's constructor. - */ -[[deprecated("use SingleThreadedExecutor::spin_all instead")]] -RCLCPP_PUBLIC -void -spin_all( - const rclcpp::node_interfaces::NodeBaseInterface::SharedPtr & node_ptr, - std::chrono::nanoseconds max_duration); - -/** - * @brief Create a default single-threaded executor and execute all available work exhaustively. - * @param node_ptr Shared pointer to the node to spin. - * @param max_duration max duration to spin - * - * This method is deprecated because it can lead to very bad performance if used in a loop: - * each call will create a new executor and register the node, which is an expensive operation. - * It's recommended to always manually instantiate an executor and call the methods with - * the same name on it. - * For example: - * SingleThreadedExecutor executor; - * executor.add_node(node_ptr); - * executor.spin_all(max_duration); - * If you are using a non-default context, this should be passed to the executor's constructor. - */ -[[deprecated("use SingleThreadedExecutor::spin_all instead")]] -RCLCPP_PUBLIC -void -spin_all(const rclcpp::Node::SharedPtr & node_ptr, std::chrono::nanoseconds max_duration); - -/** - * @brief Create a default single-threaded executor and execute any immediately available work. - * @param node_ptr Shared pointer to the base interface of the node to spin. - * - * This method is deprecated because it can lead to very bad performance if used in a loop: - * each call will create a new executor and register the node, which is an expensive operation. - * It's recommended to always manually instantiate an executor and call the methods with - * the same name on it. - * For example: - * SingleThreadedExecutor executor; - * executor.add_node(node_ptr); - * executor.spin_some(); - * If you are using a non-default context, this should be passed to the executor's constructor. - */ -[[deprecated("use SingleThreadedExecutor::spin_some instead")]] -RCLCPP_PUBLIC -void -spin_some(const rclcpp::node_interfaces::NodeBaseInterface::SharedPtr & node_ptr); - -/** - * @brief Create a default single-threaded executor and execute any immediately available work. - * @param node_ptr Shared pointer to the node to spin. - * - * This method is deprecated because it can lead to very bad performance if used in a loop: - * each call will create a new executor and register the node, which is an expensive operation. - * It's recommended to always manually instantiate an executor and call the methods with - * the same name on it. - * For example: - * SingleThreadedExecutor executor; - * executor.add_node(node_ptr); - * executor.spin_some(); - * If you are using a non-default context, this should be passed to the executor's constructor. - */ -[[deprecated("use SingleThreadedExecutor::spin_some instead")]] -RCLCPP_PUBLIC -void -spin_some(const rclcpp::Node::SharedPtr & node_ptr); - /// Create a default single-threaded executor and spin the specified node. /** \param[in] node_ptr Shared pointer to the node to spin. */ RCLCPP_PUBLIC diff --git a/rclcpp/src/rclcpp/executors.cpp b/rclcpp/src/rclcpp/executors.cpp index 4b1a7be4d0..a71d788390 100644 --- a/rclcpp/src/rclcpp/executors.cpp +++ b/rclcpp/src/rclcpp/executors.cpp @@ -13,27 +13,6 @@ // limitations under the License. #include "rclcpp/executors.hpp" -#include "rcpputils/compile_warnings.hpp" - -void -rclcpp::spin_all( - const rclcpp::node_interfaces::NodeBaseInterface::SharedPtr & node_ptr, - std::chrono::nanoseconds max_duration) -{ - rclcpp::ExecutorOptions options; - options.context = node_ptr->get_context(); - rclcpp::executors::SingleThreadedExecutor exec(options); - exec.spin_node_all(node_ptr, max_duration); -} - -void -rclcpp::spin_some(const rclcpp::node_interfaces::NodeBaseInterface::SharedPtr & node_ptr) -{ - rclcpp::ExecutorOptions options; - options.context = node_ptr->get_context(); - rclcpp::executors::SingleThreadedExecutor exec(options); - exec.spin_node_some(node_ptr); -} void rclcpp::spin(const rclcpp::node_interfaces::NodeBaseInterface::SharedPtr & node_ptr) @@ -51,19 +30,3 @@ rclcpp::spin(const rclcpp::Node::SharedPtr & node_ptr) { rclcpp::spin(node_ptr->get_node_base_interface()); } - -void -rclcpp::spin_all(const rclcpp::Node::SharedPtr & node_ptr, std::chrono::nanoseconds max_duration) -{ - RCPPUTILS_DEPRECATION_WARNING_OFF_START - rclcpp::spin_all(node_ptr->get_node_base_interface(), max_duration); - RCPPUTILS_DEPRECATION_WARNING_OFF_STOP -} - -void -rclcpp::spin_some(const rclcpp::Node::SharedPtr & node_ptr) -{ - RCPPUTILS_DEPRECATION_WARNING_OFF_START - rclcpp::spin_some(node_ptr->get_node_base_interface()); - RCPPUTILS_DEPRECATION_WARNING_OFF_STOP -} From 3dbfe9da5326800d1cdcfc0695c9e3e98658b79c Mon Sep 17 00:00:00 2001 From: Christophe Bedard Date: Fri, 27 Nov 2026 16:15:41 -0800 Subject: [PATCH 09/18] Remove deprecated MemoryStrategy and AllocatorMemoryStrategy (#3444) `MemoryStrategy` and `AllocatorMemoryStrategy` have been deprecated since https://github.com/ros2/rclcpp/pull/3136 (Lyrical), as the executors do not use them anymore, with a note to remove them after Lyrical. Also remove their tests, which were marked for removal after Lyrical, and the `rclcpp.hpp` documentation entries for them and for `rclcpp/memory_strategies.hpp`, which was already removed. Signed-off-by: Christophe Bedard --- rclcpp/CMakeLists.txt | 1 - rclcpp/include/rclcpp/memory_strategy.hpp | 154 --- rclcpp/include/rclcpp/rclcpp.hpp | 3 - .../strategies/allocator_memory_strategy.hpp | 631 ------------ rclcpp/src/rclcpp/memory_strategy.cpp | 230 ----- rclcpp/test/rclcpp/CMakeLists.txt | 11 - .../test_allocator_memory_strategy.cpp | 919 ------------------ rclcpp/test/rclcpp/test_executor.cpp | 1 - rclcpp/test/rclcpp/test_find_weak_nodes.cpp | 98 -- rclcpp/test/rclcpp/test_memory_strategy.cpp | 570 ----------- 10 files changed, 2618 deletions(-) delete mode 100644 rclcpp/include/rclcpp/memory_strategy.hpp delete mode 100644 rclcpp/include/rclcpp/strategies/allocator_memory_strategy.hpp delete mode 100644 rclcpp/src/rclcpp/memory_strategy.cpp delete mode 100644 rclcpp/test/rclcpp/strategies/test_allocator_memory_strategy.cpp delete mode 100644 rclcpp/test/rclcpp/test_find_weak_nodes.cpp delete mode 100644 rclcpp/test/rclcpp/test_memory_strategy.cpp diff --git a/rclcpp/CMakeLists.txt b/rclcpp/CMakeLists.txt index 8d8a77e9b9..f4fb20dcbb 100644 --- a/rclcpp/CMakeLists.txt +++ b/rclcpp/CMakeLists.txt @@ -80,7 +80,6 @@ set(${PROJECT_NAME}_SRCS src/rclcpp/log_directory.cpp src/rclcpp/logger.cpp src/rclcpp/logging_mutex.cpp - src/rclcpp/memory_strategy.cpp src/rclcpp/message_info.cpp src/rclcpp/network_flow_endpoint.cpp src/rclcpp/node.cpp diff --git a/rclcpp/include/rclcpp/memory_strategy.hpp b/rclcpp/include/rclcpp/memory_strategy.hpp deleted file mode 100644 index fd413fe1e5..0000000000 --- a/rclcpp/include/rclcpp/memory_strategy.hpp +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2015 Open Source Robotics Foundation, Inc. -// -// Licensed 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. - -#ifndef RCLCPP__MEMORY_STRATEGY_HPP_ -#define RCLCPP__MEMORY_STRATEGY_HPP_ - -#include -#include - -#include "rcl/allocator.h" -#include "rcl/wait.h" - -#include "rclcpp/any_executable.hpp" -#include "rclcpp/macros.hpp" -#include "rclcpp/node_interfaces/node_base_interface.hpp" -#include "rclcpp/visibility_control.hpp" -#include "rclcpp/waitable.hpp" - -namespace rclcpp -{ -namespace memory_strategy -{ - -/// Delegate for handling memory allocations while the Executor is executing. -/** - * By default, the memory strategy dynamically allocates memory for structures that come in from - * the rmw implementation after the executor waits for work, based on the number of entities that - * come through. - */ -class RCLCPP_PUBLIC [[deprecated("The executor does not used this anymore")]] MemoryStrategy -{ -public: - RCLCPP_SMART_PTR_DEFINITIONS_NOT_COPYABLE(MemoryStrategy) - using WeakCallbackGroupsToNodesMap = std::map>; - - virtual ~MemoryStrategy() = default; - - virtual bool collect_entities(const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) = 0; - - virtual size_t number_of_ready_subscriptions() const = 0; - virtual size_t number_of_ready_services() const = 0; - virtual size_t number_of_ready_clients() const = 0; - virtual size_t number_of_ready_events() const = 0; - virtual size_t number_of_ready_timers() const = 0; - virtual size_t number_of_guard_conditions() const = 0; - virtual size_t number_of_waitables() const = 0; - - virtual void add_waitable_handle(const rclcpp::Waitable::SharedPtr & waitable) = 0; - virtual bool add_handles_to_wait_set(rcl_wait_set_t * wait_set) = 0; - virtual void clear_handles() = 0; - virtual void remove_null_handles(rcl_wait_set_t * wait_set) = 0; - - virtual void - add_guard_condition(const rclcpp::GuardCondition & guard_condition) = 0; - - virtual void - remove_guard_condition(const rclcpp::GuardCondition * guard_condition) = 0; - - virtual void - get_next_subscription( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) = 0; - - virtual void - get_next_service( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) = 0; - - virtual void - get_next_client( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) = 0; - - virtual void - get_next_timer( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) = 0; - - virtual void - get_next_waitable( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) = 0; - - virtual rcl_allocator_t - get_allocator() = 0; - - static rclcpp::SubscriptionBase::SharedPtr - get_subscription_by_handle( - const std::shared_ptr & subscriber_handle, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::ServiceBase::SharedPtr - get_service_by_handle( - const std::shared_ptr & service_handle, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::ClientBase::SharedPtr - get_client_by_handle( - const std::shared_ptr & client_handle, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::TimerBase::SharedPtr - get_timer_by_handle( - const std::shared_ptr & timer_handle, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::node_interfaces::NodeBaseInterface::SharedPtr - get_node_by_group( - const rclcpp::CallbackGroup::SharedPtr & group, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::CallbackGroup::SharedPtr - get_group_by_subscription( - const rclcpp::SubscriptionBase::SharedPtr & subscription, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::CallbackGroup::SharedPtr - get_group_by_service( - const rclcpp::ServiceBase::SharedPtr & service, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::CallbackGroup::SharedPtr - get_group_by_client( - const rclcpp::ClientBase::SharedPtr & client, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::CallbackGroup::SharedPtr - get_group_by_timer( - const rclcpp::TimerBase::SharedPtr & timer, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); - - static rclcpp::CallbackGroup::SharedPtr - get_group_by_waitable( - const rclcpp::Waitable::SharedPtr & waitable, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes); -}; - -} // namespace memory_strategy -} // namespace rclcpp - -#endif // RCLCPP__MEMORY_STRATEGY_HPP_ diff --git a/rclcpp/include/rclcpp/rclcpp.hpp b/rclcpp/include/rclcpp/rclcpp.hpp index 5494419ebf..36b25ecde6 100644 --- a/rclcpp/include/rclcpp/rclcpp.hpp +++ b/rclcpp/include/rclcpp/rclcpp.hpp @@ -148,10 +148,7 @@ * - rclcpp::GenericSubscription * - rclcpp/generic_subscription.hpp * - Memory management tools: - * - rclcpp/memory_strategies.hpp - * - rclcpp/memory_strategy.hpp * - rclcpp/message_memory_strategy.hpp - * - rclcpp/strategies/allocator_memory_strategy.hpp * - rclcpp/strategies/message_pool_memory_strategy.hpp * - Context object which is shared amongst multiple Nodes: * - rclcpp::Context diff --git a/rclcpp/include/rclcpp/strategies/allocator_memory_strategy.hpp b/rclcpp/include/rclcpp/strategies/allocator_memory_strategy.hpp deleted file mode 100644 index dc83d2e44b..0000000000 --- a/rclcpp/include/rclcpp/strategies/allocator_memory_strategy.hpp +++ /dev/null @@ -1,631 +0,0 @@ -// Copyright 2015 Open Source Robotics Foundation, Inc. -// -// Licensed 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. - -#ifndef RCLCPP__STRATEGIES__ALLOCATOR_MEMORY_STRATEGY_HPP_ -#define RCLCPP__STRATEGIES__ALLOCATOR_MEMORY_STRATEGY_HPP_ - -#include -#include - -#include "rcl/allocator.h" - -#include "rclcpp/allocator/allocator_common.hpp" -#include "rclcpp/detail/add_guard_condition_to_rcl_wait_set.hpp" -#include "rclcpp/memory_strategy.hpp" -#include "rclcpp/node.hpp" -#include "rclcpp/visibility_control.hpp" - -#include "rcutils/logging_macros.h" - -#include "rmw/types.h" - -namespace rclcpp -{ -namespace memory_strategies -{ -namespace allocator_memory_strategy -{ - -/// Delegate for handling memory allocations while the Executor is executing. -/** - * By default, the memory strategy dynamically allocates memory for structures that come in from - * the rmw implementation after the executor waits for work, based on the number of entities that - * come through. - * - * This will be removed after lyrical - */ -template> -class [[deprecated("The executor does not used this anymore")]] AllocatorMemoryStrategy : public - memory_strategy::MemoryStrategy -{ -public: - RCLCPP_SMART_PTR_DEFINITIONS(AllocatorMemoryStrategy) - - using VoidAllocTraits = typename allocator::AllocRebind; - using VoidAlloc = typename VoidAllocTraits::allocator_type; - - explicit AllocatorMemoryStrategy(std::shared_ptr allocator) - { - allocator_ = std::make_shared(*allocator.get()); - } - - AllocatorMemoryStrategy() - { - allocator_ = std::make_shared(); - } - - void add_guard_condition(const rclcpp::GuardCondition & guard_condition) override - { - for (const auto & existing_guard_condition : guard_conditions_) { - if (existing_guard_condition == &guard_condition) { - return; - } - } - guard_conditions_.push_back(&guard_condition); - } - - void remove_guard_condition(const rclcpp::GuardCondition * guard_condition) override - { - for (auto it = guard_conditions_.begin(); it != guard_conditions_.end(); ++it) { - if (*it == guard_condition) { - guard_conditions_.erase(it); - break; - } - } - } - - void clear_handles() override - { - subscription_handles_.clear(); - service_handles_.clear(); - client_handles_.clear(); - timer_handles_.clear(); - waitable_handles_.clear(); - } - - void remove_null_handles(rcl_wait_set_t * wait_set) override - { - // TODO(jacobperron): Check if wait set sizes are what we expect them to be? - // e.g. wait_set->size_of_clients == client_handles_.size() - - // Important to use subscription_handles_.size() instead of wait set's size since - // there may be more subscriptions in the wait set due to Waitables added to the end. - // The same logic applies for other entities. - - // Mark corresponding weak_ptr as expired for entities that are null in the wait set - size_t valid_subscription_count = 0; - for (size_t i = 0; i < subscription_handles_.size(); ++i) { - if (valid_subscription_count < wait_set->size_of_subscriptions && - !wait_set->subscriptions[valid_subscription_count]) - { - subscription_handles_[i] = std::weak_ptr{}; - } - if (subscription_handles_[i].lock()) { - ++valid_subscription_count; - } - } - - size_t valid_service_count = 0; - for (size_t i = 0; i < service_handles_.size(); ++i) { - if (valid_service_count < wait_set->size_of_services && - !wait_set->services[valid_service_count]) - { - service_handles_[i] = std::weak_ptr{}; - } - if (service_handles_[i].lock()) { - ++valid_service_count; - } - } - - size_t valid_client_count = 0; - for (size_t i = 0; i < client_handles_.size(); ++i) { - if (valid_client_count < wait_set->size_of_clients && - !wait_set->clients[valid_client_count]) - { - client_handles_[i] = std::weak_ptr{}; - } - if (client_handles_[i].lock()) { - ++valid_client_count; - } - } - - size_t valid_timer_count = 0; - for (size_t i = 0; i < timer_handles_.size(); ++i) { - if (valid_timer_count < wait_set->size_of_timers && - !wait_set->timers[valid_timer_count]) - { - timer_handles_[i] = std::weak_ptr{}; - } - if (timer_handles_[i].lock()) { - ++valid_timer_count; - } - } - - for (size_t i = 0; i < waitable_handles_.size(); ++i) { - if (!waitable_handles_[i]->is_ready(*wait_set)) { - waitable_handles_[i].reset(); - } - } - - // Remove expired weak_ptr instances - subscription_handles_.erase( - std::remove_if(subscription_handles_.begin(), subscription_handles_.end(), - [](const std::weak_ptr & weak_ptr) { - return weak_ptr.expired(); - }), - subscription_handles_.end() - ); - - service_handles_.erase( - std::remove_if(service_handles_.begin(), service_handles_.end(), - [](const std::weak_ptr & weak_ptr) { - return weak_ptr.expired(); - }), - service_handles_.end() - ); - - client_handles_.erase( - std::remove_if(client_handles_.begin(), client_handles_.end(), - [](const std::weak_ptr & weak_ptr) { - return weak_ptr.expired(); - }), - client_handles_.end() - ); - - timer_handles_.erase( - std::remove_if(timer_handles_.begin(), timer_handles_.end(), - [](const std::weak_ptr & weak_ptr) { - return weak_ptr.expired(); - }), - timer_handles_.end() - ); - - waitable_handles_.erase( - std::remove(waitable_handles_.begin(), waitable_handles_.end(), nullptr), - waitable_handles_.end() - ); - } - - bool collect_entities(const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) override - { - bool has_invalid_weak_groups_or_nodes = false; - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - auto node = pair.second.lock(); - if (group == nullptr || node == nullptr) { - has_invalid_weak_groups_or_nodes = true; - continue; - } - if (!group || !group->can_be_taken_from().load()) { - continue; - } - - group->collect_all_ptrs( - [this](const rclcpp::SubscriptionBase::SharedPtr & subscription) { - subscription_handles_.push_back(subscription->get_subscription_handle()); - }, - [this](const rclcpp::ServiceBase::SharedPtr & service) { - service_handles_.push_back(service->get_service_handle()); - }, - [this](const rclcpp::ClientBase::SharedPtr & client) { - client_handles_.push_back(client->get_client_handle()); - }, - [this](const rclcpp::TimerBase::SharedPtr & timer) { - timer_handles_.push_back(timer->get_timer_handle()); - }, - [this](const rclcpp::Waitable::SharedPtr & waitable) { - waitable_handles_.push_back(waitable); - }); - } - - return has_invalid_weak_groups_or_nodes; - } - - void add_waitable_handle(const rclcpp::Waitable::SharedPtr & waitable) override - { - if (nullptr == waitable) { - throw std::runtime_error("waitable object unexpectedly nullptr"); - } - waitable_handles_.push_back(waitable); - } - - bool add_handles_to_wait_set(rcl_wait_set_t * wait_set) override - { - for (const std::weak_ptr & weak_subscription : - subscription_handles_) - { - auto subscription = weak_subscription.lock(); - if (!subscription) { - continue; // Skip expired handles - } - if (rcl_wait_set_add_subscription(wait_set, subscription.get(), NULL) != RCL_RET_OK) { - RCUTILS_LOG_ERROR_NAMED( - "rclcpp", - "Couldn't add subscription to wait set: %s", rcl_get_error_string().str); - rcl_reset_error(); - return false; - } - } - - for (const std::weak_ptr & weak_client : client_handles_) { - auto client = weak_client.lock(); - if (!client) { - continue; // Skip expired handles - } - if (rcl_wait_set_add_client(wait_set, client.get(), NULL) != RCL_RET_OK) { - RCUTILS_LOG_ERROR_NAMED( - "rclcpp", - "Couldn't add client to wait set: %s", rcl_get_error_string().str); - rcl_reset_error(); - return false; - } - } - - for (const std::weak_ptr & weak_service : service_handles_) { - auto service = weak_service.lock(); - if (!service) { - continue; // Skip expired handles - } - if (rcl_wait_set_add_service(wait_set, service.get(), NULL) != RCL_RET_OK) { - RCUTILS_LOG_ERROR_NAMED( - "rclcpp", - "Couldn't add service to wait set: %s", rcl_get_error_string().str); - rcl_reset_error(); - return false; - } - } - - for (const std::weak_ptr & weak_timer : timer_handles_) { - auto timer = weak_timer.lock(); - if (!timer) { - continue; // Skip expired handles - } - if (rcl_wait_set_add_timer(wait_set, timer.get(), NULL) != RCL_RET_OK) { - RCUTILS_LOG_ERROR_NAMED( - "rclcpp", - "Couldn't add timer to wait set: %s", rcl_get_error_string().str); - rcl_reset_error(); - return false; - } - } - - for (auto guard_condition : guard_conditions_) { - detail::add_guard_condition_to_rcl_wait_set(*wait_set, *guard_condition); - } - - for (const std::shared_ptr & waitable : waitable_handles_) { - waitable->add_to_wait_set(*wait_set); - } - return true; - } - - void - get_next_subscription( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) override - { - auto it = subscription_handles_.begin(); - while (it != subscription_handles_.end()) { - auto subscription_handle = it->lock(); - if (!subscription_handle) { - // Handle expired, remove it and continue - it = subscription_handles_.erase(it); - continue; - } - auto subscription = get_subscription_by_handle(subscription_handle, weak_groups_to_nodes); - if (subscription) { - // Find the group for this handle and see if it can be serviced - auto group = get_group_by_subscription(subscription, weak_groups_to_nodes); - if (!group) { - // Group was not found, meaning the subscription is not valid... - // Remove it from the ready list and continue looking - it = subscription_handles_.erase(it); - continue; - } - if (!group->can_be_taken_from().load()) { - // Group is mutually exclusive and is being used, so skip it for now - // Leave it to be checked next time, but continue searching - ++it; - continue; - } - // Otherwise it is safe to set and return the any_exec - any_exec.subscription = subscription; - any_exec.callback_group = group; - any_exec.node_base = get_node_by_group(group, weak_groups_to_nodes); - subscription_handles_.erase(it); - return; - } - // Else, the subscription is no longer valid, remove it and continue - it = subscription_handles_.erase(it); - } - } - - void - get_next_service( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) override - { - auto it = service_handles_.begin(); - while (it != service_handles_.end()) { - auto service_handle = it->lock(); - if (!service_handle) { - // Handle expired, remove it and continue - it = service_handles_.erase(it); - continue; - } - auto service = get_service_by_handle(service_handle, weak_groups_to_nodes); - if (service) { - // Find the group for this handle and see if it can be serviced - auto group = get_group_by_service(service, weak_groups_to_nodes); - if (!group) { - // Group was not found, meaning the service is not valid... - // Remove it from the ready list and continue looking - it = service_handles_.erase(it); - continue; - } - if (!group->can_be_taken_from().load()) { - // Group is mutually exclusive and is being used, so skip it for now - // Leave it to be checked next time, but continue searching - ++it; - continue; - } - // Otherwise it is safe to set and return the any_exec - any_exec.service = service; - any_exec.callback_group = group; - any_exec.node_base = get_node_by_group(group, weak_groups_to_nodes); - service_handles_.erase(it); - return; - } - // Else, the service is no longer valid, remove it and continue - it = service_handles_.erase(it); - } - } - - void - get_next_client( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) override - { - auto it = client_handles_.begin(); - while (it != client_handles_.end()) { - auto client_handle = it->lock(); - if (!client_handle) { - // Handle expired, remove it and continue - it = client_handles_.erase(it); - continue; - } - auto client = get_client_by_handle(client_handle, weak_groups_to_nodes); - if (client) { - // Find the group for this handle and see if it can be serviced - auto group = get_group_by_client(client, weak_groups_to_nodes); - if (!group) { - // Group was not found, meaning the service is not valid... - // Remove it from the ready list and continue looking - it = client_handles_.erase(it); - continue; - } - if (!group->can_be_taken_from().load()) { - // Group is mutually exclusive and is being used, so skip it for now - // Leave it to be checked next time, but continue searching - ++it; - continue; - } - // Otherwise it is safe to set and return the any_exec - any_exec.client = client; - any_exec.callback_group = group; - any_exec.node_base = get_node_by_group(group, weak_groups_to_nodes); - client_handles_.erase(it); - return; - } - // Else, the service is no longer valid, remove it and continue - it = client_handles_.erase(it); - } - } - - void - get_next_timer( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) override - { - auto it = timer_handles_.begin(); - while (it != timer_handles_.end()) { - auto timer_handle = it->lock(); - if (!timer_handle) { - // Handle expired, remove it and continue - it = timer_handles_.erase(it); - continue; - } - auto timer = get_timer_by_handle(timer_handle, weak_groups_to_nodes); - if (timer) { - // Find the group for this handle and see if it can be serviced - auto group = get_group_by_timer(timer, weak_groups_to_nodes); - if (!group) { - // Group was not found, meaning the timer is not valid... - // Remove it from the ready list and continue looking - it = timer_handles_.erase(it); - continue; - } - if (!group->can_be_taken_from().load()) { - // Group is mutually exclusive and is being used, so skip it for now - // Leave it to be checked next time, but continue searching - ++it; - continue; - } - auto data = timer->call(); - if (!data) { - // timer was cancelled, skip it. - ++it; - continue; - } - // Otherwise it is safe to set and return the any_exec - any_exec.timer = timer; - any_exec.callback_group = group; - any_exec.node_base = get_node_by_group(group, weak_groups_to_nodes); - any_exec.data = data; - timer_handles_.erase(it); - return; - } - // Else, the timer is no longer valid, remove it and continue - it = timer_handles_.erase(it); - } - } - - void - get_next_waitable( - rclcpp::AnyExecutable & any_exec, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) override - { - auto it = waitable_handles_.begin(); - while (it != waitable_handles_.end()) { - std::shared_ptr & waitable = *it; - if (waitable) { - // Find the group for this handle and see if it can be serviced - auto group = get_group_by_waitable(waitable, weak_groups_to_nodes); - if (!group) { - // Group was not found, meaning the waitable is not valid... - // Remove it from the ready list and continue looking - it = waitable_handles_.erase(it); - continue; - } - if (!group->can_be_taken_from().load()) { - // Group is mutually exclusive and is being used, so skip it for now - // Leave it to be checked next time, but continue searching - ++it; - continue; - } - // Otherwise it is safe to set and return the any_exec - any_exec.waitable = waitable; - any_exec.callback_group = group; - any_exec.node_base = get_node_by_group(group, weak_groups_to_nodes); - waitable_handles_.erase(it); - return; - } - // Else, the waitable is no longer valid, remove it and continue - it = waitable_handles_.erase(it); - } - } - - rcl_allocator_t get_allocator() override - { - if constexpr (std::is_same_v>) { - return rcl_get_default_allocator(); - } else { - return rclcpp::allocator::get_rcl_allocator(*allocator_.get()); - } - } - - size_t number_of_ready_subscriptions() const override - { - size_t number_of_subscriptions = 0; - // Count only non-expired weak_ptr references - for (const auto & weak_subscription : subscription_handles_) { - if (!weak_subscription.expired()) { - ++number_of_subscriptions; - } - } - for (const std::shared_ptr & waitable : waitable_handles_) { - number_of_subscriptions += waitable->get_number_of_ready_subscriptions(); - } - return number_of_subscriptions; - } - - size_t number_of_ready_services() const override - { - size_t number_of_services = 0; - // Count only non-expired weak_ptr references - for (const auto & weak_service : service_handles_) { - if (!weak_service.expired()) { - ++number_of_services; - } - } - for (const std::shared_ptr & waitable : waitable_handles_) { - number_of_services += waitable->get_number_of_ready_services(); - } - return number_of_services; - } - - size_t number_of_ready_events() const override - { - size_t number_of_events = 0; - for (const std::shared_ptr & waitable : waitable_handles_) { - number_of_events += waitable->get_number_of_ready_events(); - } - return number_of_events; - } - - size_t number_of_ready_clients() const override - { - size_t number_of_clients = 0; - // Count only non-expired weak_ptr references - for (const auto & weak_client : client_handles_) { - if (!weak_client.expired()) { - ++number_of_clients; - } - } - for (const std::shared_ptr & waitable : waitable_handles_) { - number_of_clients += waitable->get_number_of_ready_clients(); - } - return number_of_clients; - } - - size_t number_of_guard_conditions() const override - { - size_t number_of_guard_conditions = guard_conditions_.size(); - for (const std::shared_ptr & waitable : waitable_handles_) { - number_of_guard_conditions += waitable->get_number_of_ready_guard_conditions(); - } - return number_of_guard_conditions; - } - - size_t number_of_ready_timers() const override - { - size_t number_of_timers = 0; - // Count only non-expired weak_ptr references - for (const auto & weak_timer : timer_handles_) { - if (!weak_timer.expired()) { - ++number_of_timers; - } - } - for (const std::shared_ptr & waitable : waitable_handles_) { - number_of_timers += waitable->get_number_of_ready_timers(); - } - return number_of_timers; - } - - size_t number_of_waitables() const override - { - return waitable_handles_.size(); - } - -private: - template - using VectorRebind = - std::vector::template rebind_alloc>; - - VectorRebind guard_conditions_; - - VectorRebind> subscription_handles_; - VectorRebind> service_handles_; - VectorRebind> client_handles_; - VectorRebind> timer_handles_; - VectorRebind> waitable_handles_; - - std::shared_ptr allocator_; -}; - -} // namespace allocator_memory_strategy -} // namespace memory_strategies -} // namespace rclcpp - -#endif // RCLCPP__STRATEGIES__ALLOCATOR_MEMORY_STRATEGY_HPP_ diff --git a/rclcpp/src/rclcpp/memory_strategy.cpp b/rclcpp/src/rclcpp/memory_strategy.cpp deleted file mode 100644 index cb69dc0d26..0000000000 --- a/rclcpp/src/rclcpp/memory_strategy.cpp +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2015 Open Source Robotics Foundation, Inc. -// -// Licensed 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 "rclcpp/memory_strategy.hpp" -#include - -using rclcpp::memory_strategy::MemoryStrategy; - -rclcpp::SubscriptionBase::SharedPtr -MemoryStrategy::get_subscription_by_handle( - const std::shared_ptr & subscriber_handle, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - if (!group) { - continue; - } - auto match_subscription = group->find_subscription_ptrs_if( - [&subscriber_handle](const rclcpp::SubscriptionBase::SharedPtr & subscription) -> bool { - return subscription->get_subscription_handle() == subscriber_handle; - }); - if (match_subscription) { - return match_subscription; - } - } - return nullptr; -} - -rclcpp::ServiceBase::SharedPtr -MemoryStrategy::get_service_by_handle( - const std::shared_ptr & service_handle, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - if (!group) { - continue; - } - auto service_ref = group->find_service_ptrs_if( - [&service_handle](const rclcpp::ServiceBase::SharedPtr & service) -> bool { - return service->get_service_handle() == service_handle; - }); - if (service_ref) { - return service_ref; - } - } - return nullptr; -} - -rclcpp::ClientBase::SharedPtr -MemoryStrategy::get_client_by_handle( - const std::shared_ptr & client_handle, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - if (!group) { - continue; - } - auto client_ref = group->find_client_ptrs_if( - [&client_handle](const rclcpp::ClientBase::SharedPtr & client) -> bool { - return client->get_client_handle() == client_handle; - }); - if (client_ref) { - return client_ref; - } - } - return nullptr; -} - -rclcpp::TimerBase::SharedPtr -MemoryStrategy::get_timer_by_handle( - const std::shared_ptr & timer_handle, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - if (!group) { - continue; - } - auto timer_ref = group->find_timer_ptrs_if( - [&timer_handle](const rclcpp::TimerBase::SharedPtr & timer) -> bool { - return timer->get_timer_handle() == timer_handle; - }); - if (timer_ref) { - return timer_ref; - } - } - return nullptr; -} - -rclcpp::node_interfaces::NodeBaseInterface::SharedPtr -MemoryStrategy::get_node_by_group( - const rclcpp::CallbackGroup::SharedPtr & group, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - if (!group) { - return nullptr; - } - - rclcpp::CallbackGroup::WeakPtr weak_group_ptr(group); - const auto finder = weak_groups_to_nodes.find(weak_group_ptr); - if (finder != weak_groups_to_nodes.end()) { - rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_ptr = finder->second.lock(); - return node_ptr; - } - return nullptr; -} - -rclcpp::CallbackGroup::SharedPtr -MemoryStrategy::get_group_by_subscription( - const rclcpp::SubscriptionBase::SharedPtr & subscription, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - auto node = pair.second.lock(); - if (!group || !node) { - continue; - } - auto match_sub = group->find_subscription_ptrs_if( - [&subscription](const rclcpp::SubscriptionBase::SharedPtr & sub) -> bool { - return sub == subscription; - }); - if (match_sub) { - return group; - } - } - return nullptr; -} - -rclcpp::CallbackGroup::SharedPtr -MemoryStrategy::get_group_by_service( - const rclcpp::ServiceBase::SharedPtr & service, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - auto node = pair.second.lock(); - if (!group || !node) { - continue; - } - auto service_ref = group->find_service_ptrs_if( - [&service](const rclcpp::ServiceBase::SharedPtr & serv) -> bool { - return serv == service; - }); - if (service_ref) { - return group; - } - } - return nullptr; -} - -rclcpp::CallbackGroup::SharedPtr -MemoryStrategy::get_group_by_client( - const rclcpp::ClientBase::SharedPtr & client, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - auto node = pair.second.lock(); - if (!group || !node) { - continue; - } - auto client_ref = group->find_client_ptrs_if( - [&client](const rclcpp::ClientBase::SharedPtr & cli) -> bool { - return cli == client; - }); - if (client_ref) { - return group; - } - } - return nullptr; -} - -rclcpp::CallbackGroup::SharedPtr -MemoryStrategy::get_group_by_timer( - const rclcpp::TimerBase::SharedPtr & timer, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - auto node = pair.second.lock(); - if (!group || !node) { - continue; - } - auto timer_ref = group->find_timer_ptrs_if( - [&timer](const rclcpp::TimerBase::SharedPtr & time) -> bool { - return time == timer; - }); - if (timer_ref) { - return group; - } - } - return nullptr; -} - -rclcpp::CallbackGroup::SharedPtr -MemoryStrategy::get_group_by_waitable( - const rclcpp::Waitable::SharedPtr & waitable, - const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) -{ - for (const auto & pair : weak_groups_to_nodes) { - auto group = pair.first.lock(); - auto node = pair.second.lock(); - if (!group || !node) { - continue; - } - auto waitable_ref = group->find_waitable_ptrs_if( - [&waitable](const rclcpp::Waitable::SharedPtr & group_waitable) -> bool { - return group_waitable == waitable; - }); - if (waitable_ref) { - return group; - } - } - return nullptr; -} diff --git a/rclcpp/test/rclcpp/CMakeLists.txt b/rclcpp/test/rclcpp/CMakeLists.txt index 270dc46f6e..8714714d7e 100644 --- a/rclcpp/test/rclcpp/CMakeLists.txt +++ b/rclcpp/test/rclcpp/CMakeLists.txt @@ -34,10 +34,6 @@ if(TARGET test_exceptions) target_link_libraries(test_exceptions ${PROJECT_NAME} mimick) endif() -ament_add_ros_isolated_gtest(test_allocator_memory_strategy strategies/test_allocator_memory_strategy.cpp) -if(TARGET test_allocator_memory_strategy) - target_link_libraries(test_allocator_memory_strategy ${PROJECT_NAME} rcpputils::rcpputils test_msgs::test_msgs) -endif() ament_add_ros_isolated_gtest(test_message_pool_memory_strategy strategies/test_message_pool_memory_strategy.cpp) if(TARGET test_message_pool_memory_strategy) target_link_libraries(test_message_pool_memory_strategy ${PROJECT_NAME} test_msgs::test_msgs) @@ -145,9 +141,6 @@ ament_add_ros_isolated_gtest(test_loaned_message test_loaned_message.cpp) ament_add_test_label(test_loaned_message mimick) target_link_libraries(test_loaned_message ${PROJECT_NAME} mimick test_msgs::test_msgs) -ament_add_ros_isolated_gtest(test_memory_strategy test_memory_strategy.cpp) -target_link_libraries(test_memory_strategy ${PROJECT_NAME} test_msgs::test_msgs) - ament_add_ros_isolated_gtest(test_message_memory_strategy test_message_memory_strategy.cpp) target_link_libraries(test_message_memory_strategy ${PROJECT_NAME} test_msgs::test_msgs) @@ -389,10 +382,6 @@ ament_add_ros_isolated_gmock(test_typesupport_helpers test_typesupport_helpers.c if(TARGET test_typesupport_helpers) target_link_libraries(test_typesupport_helpers ${PROJECT_NAME} rcpputils::rcpputils) endif() -ament_add_ros_isolated_gtest(test_find_weak_nodes test_find_weak_nodes.cpp) -if(TARGET test_find_weak_nodes) - target_link_libraries(test_find_weak_nodes ${PROJECT_NAME}) -endif() ament_add_ros_isolated_gtest(test_externally_defined_services test_externally_defined_services.cpp) target_link_libraries(test_externally_defined_services ${PROJECT_NAME} rcl::rcl test_msgs::test_msgs) diff --git a/rclcpp/test/rclcpp/strategies/test_allocator_memory_strategy.cpp b/rclcpp/test/rclcpp/strategies/test_allocator_memory_strategy.cpp deleted file mode 100644 index 16867b9be4..0000000000 --- a/rclcpp/test/rclcpp/strategies/test_allocator_memory_strategy.cpp +++ /dev/null @@ -1,919 +0,0 @@ -// Copyright 2020 Open Source Robotics Foundation, Inc. -// -// Licensed 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 -#include -#include -#include -#include -#include - -#include "gtest/gtest.h" -#include - -// can be removed after the lyrical release -RCPPUTILS_DEPRECATION_WARNING_OFF_START -#include "rclcpp/strategies/allocator_memory_strategy.hpp" -#include "rclcpp/utilities.hpp" -#include "rcpputils/scope_exit.hpp" -#include "test_msgs/msg/empty.hpp" -#include "test_msgs/srv/empty.hpp" - -using rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy; -typedef std::map> WeakCallbackGroupsToNodesMap; - -static bool test_waitable_result = false; - -/** - * Mock Waitable class, with a globally setable boolean result. - */ -class TestWaitable : public rclcpp::Waitable -{ -public: - void add_to_wait_set(rcl_wait_set_t &) override - { - if (!test_waitable_result) { - throw std::runtime_error("TestWaitable add_to_wait_set failed"); - } - } - - bool is_ready(const rcl_wait_set_t &) override - { - return test_waitable_result; - } - - std::shared_ptr take_data() override {return nullptr;} - void execute(const std::shared_ptr &) override {} - - void set_on_ready_callback(std::function) override {} - void clear_on_ready_callback() override {} - - std::shared_ptr take_data_by_entity_id(size_t) override {return nullptr;} - - std::vector> get_timers() const override - { - return {}; - } -}; - -struct RclWaitSetSizes -{ - size_t size_of_subscriptions = 0; - size_t size_of_guard_conditions = 0; - size_t size_of_timers = 0; - size_t size_of_clients = 0; - size_t size_of_services = 0; - size_t size_of_events = 0; - size_t size_of_waitables = 0; -}; - -// For a standard rclcpp node, this should be more than enough capacity for each type. -RclWaitSetSizes SufficientWaitSetCapacities() -{ - return {100, 100, 100, 100, 100, 100, 100}; -} - -class TestAllocatorMemoryStrategy : public ::testing::Test -{ -public: - TestAllocatorMemoryStrategy() - : allocator_memory_strategy_(nullptr) {} - - void SetUp() override - { - rclcpp::init(0, nullptr); - allocator_ = std::make_shared>(); - // Even though this is just using a basic allocator, the custom allocator constructor was - // not covered in general testing. - allocator_memory_strategy_ = std::make_shared>(allocator_); - } - - void TearDown() override - { - allocator_memory_strategy_.reset(); - rclcpp::shutdown(); - } - -protected: - std::shared_ptr> allocator_memory_strategy() - { - return allocator_memory_strategy_; - } - - // - // Convience methods, but it adds entities to vectors so the weak pointers kept by the node - // interfaces remain alive and valid - // - - std::shared_ptr create_node_with_disabled_callback_groups(const std::string & name) - { - auto node = std::make_shared(name, "ns"); - - node->for_each_callback_group( - [](rclcpp::CallbackGroup::SharedPtr group) - { - group->can_be_taken_from() = false; - }); - return node; - } - - std::shared_ptr create_node_with_subscription(const std::string & name) - { - auto subscription_callback = [](test_msgs::msg::Empty::ConstSharedPtr) {}; - const rclcpp::QoS qos(10); - auto node_with_subscription = create_node_with_disabled_callback_groups(name); - - rclcpp::SubscriptionOptions subscription_options; - - auto callback_group = - node_with_subscription->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - - subscription_options.callback_group = callback_group; - callback_groups_.push_back(callback_group); - - auto subscription = node_with_subscription->create_subscription< - test_msgs::msg::Empty, decltype(subscription_callback)>( - "topic", qos, std::move(subscription_callback), subscription_options); - subscriptions_.push_back(subscription); - - return node_with_subscription; - } - - std::shared_ptr create_node_with_service(const std::string & name) - { - auto service_callback = []( - const test_msgs::srv::Empty::Request::SharedPtr, - test_msgs::srv::Empty::Response::SharedPtr) {}; - auto node_with_service = create_node_with_disabled_callback_groups(name); - - auto callback_group = - node_with_service->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - - callback_groups_.push_back(callback_group); - - services_.push_back( - node_with_service->create_service( - "service", std::move(service_callback), rclcpp::ServicesQoS(), callback_group)); - return node_with_service; - } - - std::shared_ptr create_node_with_client(const std::string & name) - { - auto node_with_client = create_node_with_disabled_callback_groups(name); - auto callback_group = - node_with_client->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - - callback_groups_.push_back(callback_group); - - clients_.push_back( - node_with_client->create_client( - "service", rclcpp::ServicesQoS(), callback_group)); - return node_with_client; - } - - std::shared_ptr create_node_with_timer(const std::string & name) - { - auto timer_callback = []() {}; - auto node_with_timer = create_node_with_disabled_callback_groups(name); - - auto callback_group = - node_with_timer->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - callback_groups_.push_back(callback_group); - - timers_.push_back( - node_with_timer->create_wall_timer( - std::chrono::milliseconds(1), timer_callback, callback_group)); - return node_with_timer; - } - - ::testing::AssertionResult TestNumberOfEntitiesAfterCollection( - std::shared_ptr node, - const RclWaitSetSizes & expected) - { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - EXPECT_EQ( - expected.size_of_subscriptions, allocator_memory_strategy()->number_of_ready_subscriptions()); - EXPECT_EQ( - expected.size_of_guard_conditions, allocator_memory_strategy()->number_of_guard_conditions()); - EXPECT_EQ(expected.size_of_timers, allocator_memory_strategy()->number_of_ready_timers()); - EXPECT_EQ(expected.size_of_clients, allocator_memory_strategy()->number_of_ready_clients()); - EXPECT_EQ(expected.size_of_services, allocator_memory_strategy()->number_of_ready_services()); - EXPECT_EQ(expected.size_of_events, allocator_memory_strategy()->number_of_ready_events()); - EXPECT_EQ(expected.size_of_waitables, allocator_memory_strategy()->number_of_waitables()); - if (::testing::Test::HasFailure()) { - return ::testing::AssertionFailure() << - "Expected number of entities did not match actual counts"; - } - return ::testing::AssertionSuccess(); - } - - ::testing::AssertionResult TestAddHandlesToWaitSet( - std::shared_ptr node, - const RclWaitSetSizes & insufficient_capacities) - { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - - auto context = node->get_node_base_interface()->get_context(); - rcl_context_t * rcl_context = context->get_rcl_context().get(); - rcl_wait_set_t wait_set = rcl_get_zero_initialized_wait_set(); - rcl_allocator_t allocator = rcl_get_default_allocator(); - RclWaitSetSizes sufficient_capacities = SufficientWaitSetCapacities(); - - rcl_ret_t ret = rcl_wait_set_init( - &wait_set, - sufficient_capacities.size_of_subscriptions, - sufficient_capacities.size_of_guard_conditions, - sufficient_capacities.size_of_timers, - sufficient_capacities.size_of_clients, - sufficient_capacities.size_of_services, - sufficient_capacities.size_of_events, - rcl_context, - allocator); - if (ret != RCL_RET_OK) { - return ::testing::AssertionFailure() << - "Calling rcl_wait_set_init() with expected sufficient capacities failed"; - } - - RCPPUTILS_SCOPE_EXIT( - { - EXPECT_EQ(RCL_RET_OK, rcl_wait_set_fini(&wait_set)); - }); - - if (!allocator_memory_strategy()->add_handles_to_wait_set(&wait_set)) { - return ::testing::AssertionFailure() << - "Calling add_handles_to_wait_set() with a wait_set with expected sufficient capacities" - " failed"; - } - - rcl_wait_set_t wait_set_no_capacity = rcl_get_zero_initialized_wait_set(); - ret = rcl_wait_set_init( - &wait_set_no_capacity, - insufficient_capacities.size_of_subscriptions, - insufficient_capacities.size_of_guard_conditions, - insufficient_capacities.size_of_timers, - insufficient_capacities.size_of_clients, - insufficient_capacities.size_of_services, - insufficient_capacities.size_of_events, - rcl_context, - allocator); - - if (ret != RCL_RET_OK) { - return ::testing::AssertionFailure() << - "Calling rcl_wait_set_init() with expected insufficient capacities failed"; - } - - RCPPUTILS_SCOPE_EXIT( - { - EXPECT_EQ(RCL_RET_OK, rcl_wait_set_fini(&wait_set_no_capacity)); - }); - - if (allocator_memory_strategy()->add_handles_to_wait_set(&wait_set_no_capacity)) { - return ::testing::AssertionFailure() << - "Calling add_handles_to_wait_set() with a wait_set with insufficient capacities" - " unexpectedly succeeded"; - } - return ::testing::AssertionSuccess(); - } - - ::testing::AssertionResult TestGetNextEntity( - std::shared_ptr node_with_entity1, - std::shared_ptr node_with_entity2, - std::function get_next_entity_func) - { - auto basic_node = create_node_with_disabled_callback_groups("basic_node"); - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - basic_node->for_each_callback_group( - [basic_node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - basic_node->get_node_base_interface())); - }); - node_with_entity1->for_each_callback_group( - [node_with_entity1, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node_with_entity1->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - - rclcpp::AnyExecutable result = get_next_entity_func(weak_groups_to_nodes); - if (result.node_base != node_with_entity1->get_node_base_interface()) { - return ::testing::AssertionFailure() << - "Failed to get expected entity with specified get_next_*() function"; - } - - auto basic_node2 = std::make_shared("basic_node2", "ns"); - WeakCallbackGroupsToNodesMap weak_groups_to_uncollected_nodes; - basic_node2->for_each_callback_group( - [basic_node2, &weak_groups_to_uncollected_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_uncollected_nodes.insert( - std::pair( - group_ptr, - basic_node2->get_node_base_interface())); - }); - node_with_entity2->for_each_callback_group( - [node_with_entity2, - &weak_groups_to_uncollected_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_uncollected_nodes.insert( - std::pair( - group_ptr, - node_with_entity2->get_node_base_interface())); - }); - rclcpp::AnyExecutable failed_result = get_next_entity_func(weak_groups_to_uncollected_nodes); - if (nullptr != failed_result.node_base) { - return ::testing::AssertionFailure() << - "A node was retrieved with the specified get_next_*() function despite" - " none of the nodes that were passed to it were added to the" - " allocator_memory_strategy. Retrieved node: " << failed_result.node_base->get_name(); - } - return ::testing::AssertionSuccess(); - } - - ::testing::AssertionResult TestGetNextEntityMutuallyExclusive( - std::shared_ptr node_with_entity, - std::function get_next_entity_func) - { - auto basic_node = std::make_shared("basic_node", "ns"); - auto basic_node_base = basic_node->get_node_base_interface(); - auto node_base = node_with_entity->get_node_base_interface(); - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - basic_node_base->for_each_callback_group( - [basic_node_base, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - basic_node_base)); - }); - node_base->for_each_callback_group( - [node_base, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node_base)); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - - // It's important that these be set after collect_entities() otherwise collect_entities() will - // not do anything - node_base->get_default_callback_group()->can_be_taken_from() = false; - basic_node_base->get_default_callback_group()->can_be_taken_from() = false; - for (auto & callback_group : callback_groups_) { - callback_group->can_be_taken_from() = false; - } - - rclcpp::AnyExecutable result = get_next_entity_func(weak_groups_to_nodes); - - if (nullptr != result.node_base) { - return ::testing::AssertionFailure() << - "A node was retrieved with the specified get_next_*() function despite" - " setting can_be_taken_from() to false for all nodes and callback_groups"; - } - - return ::testing::AssertionSuccess(); - } - - std::vector> callback_groups_; - -private: - std::shared_ptr> allocator_; - std::shared_ptr> allocator_memory_strategy_; - - // These are generally kept as weak pointers in the rclcpp::Node interfaces, so they need to be - // owned by this class. - std::vector subscriptions_; - std::vector services_; - std::vector clients_; - std::vector timers_; - std::vector waitables_; -}; - -TEST_F(TestAllocatorMemoryStrategy, construct_destruct) { - auto basic_node = create_node_with_disabled_callback_groups("basic_node"); - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - basic_node->for_each_callback_group( - [basic_node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - basic_node->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_ready_subscriptions()); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_ready_services()); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_ready_events()); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_ready_clients()); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_guard_conditions()); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_ready_timers()); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_waitables()); -} - -TEST_F(TestAllocatorMemoryStrategy, add_remove_guard_conditions) { - rclcpp::GuardCondition guard_condition1; - rclcpp::GuardCondition guard_condition2; - rclcpp::GuardCondition guard_condition3; - - EXPECT_NO_THROW(allocator_memory_strategy()->add_guard_condition(guard_condition1)); - EXPECT_NO_THROW(allocator_memory_strategy()->add_guard_condition(guard_condition2)); - EXPECT_NO_THROW(allocator_memory_strategy()->add_guard_condition(guard_condition3)); - EXPECT_EQ(3u, allocator_memory_strategy()->number_of_guard_conditions()); - - // Adding a second time should not add to vector - EXPECT_NO_THROW(allocator_memory_strategy()->add_guard_condition(guard_condition1)); - EXPECT_NO_THROW(allocator_memory_strategy()->add_guard_condition(guard_condition2)); - EXPECT_NO_THROW(allocator_memory_strategy()->add_guard_condition(guard_condition3)); - EXPECT_EQ(3u, allocator_memory_strategy()->number_of_guard_conditions()); - - EXPECT_NO_THROW(allocator_memory_strategy()->remove_guard_condition(&guard_condition1)); - EXPECT_NO_THROW(allocator_memory_strategy()->remove_guard_condition(&guard_condition2)); - EXPECT_NO_THROW(allocator_memory_strategy()->remove_guard_condition(&guard_condition3)); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_guard_conditions()); - - // Removing second time should have no effect - EXPECT_NO_THROW(allocator_memory_strategy()->remove_guard_condition(&guard_condition1)); - EXPECT_NO_THROW(allocator_memory_strategy()->remove_guard_condition(&guard_condition2)); - EXPECT_NO_THROW(allocator_memory_strategy()->remove_guard_condition(&guard_condition3)); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_guard_conditions()); -} - -TEST_F(TestAllocatorMemoryStrategy, add_remove_waitables) { - EXPECT_THROW(allocator_memory_strategy()->add_waitable_handle(nullptr), std::runtime_error); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_waitables()); - - rclcpp::Waitable::SharedPtr waitable = std::make_shared(); - EXPECT_NO_THROW(allocator_memory_strategy()->add_waitable_handle(waitable)); - EXPECT_EQ(1u, allocator_memory_strategy()->number_of_waitables()); - - EXPECT_NO_THROW(allocator_memory_strategy()->clear_handles()); - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_waitables()); -} - -TEST_F(TestAllocatorMemoryStrategy, number_of_entities_with_subscription) { - RclWaitSetSizes expected_sizes = {}; - expected_sizes.size_of_subscriptions = 1; - expected_sizes.size_of_events = 2; - expected_sizes.size_of_waitables = 2; - auto node_with_subscription = create_node_with_subscription("subscription_node"); - EXPECT_TRUE(TestNumberOfEntitiesAfterCollection(node_with_subscription, expected_sizes)); -} - -TEST_F(TestAllocatorMemoryStrategy, number_of_entities_with_service) { - RclWaitSetSizes expected_sizes = {}; - expected_sizes.size_of_services = 1; - auto node_with_service = create_node_with_service("service_node"); - EXPECT_TRUE(TestNumberOfEntitiesAfterCollection(node_with_service, expected_sizes)); -} - -TEST_F(TestAllocatorMemoryStrategy, number_of_entities_with_client) { - RclWaitSetSizes expected_sizes = {}; - expected_sizes.size_of_clients = 1; - auto node_with_client = create_node_with_client("client_node"); - EXPECT_TRUE(TestNumberOfEntitiesAfterCollection(node_with_client, expected_sizes)); -} - -TEST_F(TestAllocatorMemoryStrategy, number_of_entities_with_timer) { - RclWaitSetSizes expected_sizes = {}; - expected_sizes.size_of_timers = 1; - auto node_with_timer = create_node_with_timer("timer_node"); - EXPECT_TRUE(TestNumberOfEntitiesAfterCollection(node_with_timer, expected_sizes)); -} - -TEST_F(TestAllocatorMemoryStrategy, add_handles_to_wait_set_bad_arguments) { - auto node = create_node_with_subscription("subscription_node"); - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - EXPECT_FALSE(allocator_memory_strategy()->add_handles_to_wait_set(nullptr)); - // The error message is collected and already reset. - EXPECT_FALSE(rcl_error_is_set()); -} - -TEST_F(TestAllocatorMemoryStrategy, add_handles_to_wait_set_subscription) { - auto node_with_subscription = create_node_with_subscription("subscription_node"); - RclWaitSetSizes insufficient_capacities = SufficientWaitSetCapacities(); - insufficient_capacities.size_of_subscriptions = 0; - EXPECT_TRUE(TestAddHandlesToWaitSet(node_with_subscription, insufficient_capacities)); -} - -TEST_F(TestAllocatorMemoryStrategy, add_handles_to_wait_set_service) { - auto node_with_service = create_node_with_service("service_node"); - RclWaitSetSizes insufficient_capacities = SufficientWaitSetCapacities(); - insufficient_capacities.size_of_services = 0; - EXPECT_TRUE(TestAddHandlesToWaitSet(node_with_service, insufficient_capacities)); -} - -TEST_F(TestAllocatorMemoryStrategy, add_handles_to_wait_set_client) { - auto node_with_client = create_node_with_client("client_node"); - RclWaitSetSizes insufficient_capacities = SufficientWaitSetCapacities(); - insufficient_capacities.size_of_clients = 0; - EXPECT_TRUE(TestAddHandlesToWaitSet(node_with_client, insufficient_capacities)); -} - -TEST_F(TestAllocatorMemoryStrategy, add_handles_to_wait_set_guard_condition) { - auto node = create_node_with_disabled_callback_groups("node"); - auto context = node->get_node_base_interface()->get_context(); - - rclcpp::GuardCondition guard_condition(context); - - EXPECT_NO_THROW(rclcpp::GuardCondition guard_condition(context);); - - allocator_memory_strategy()->add_guard_condition(guard_condition); - - RclWaitSetSizes insufficient_capacities = SufficientWaitSetCapacities(); - insufficient_capacities.size_of_guard_conditions = 0; - EXPECT_THROW( - (void)TestAddHandlesToWaitSet(node, insufficient_capacities), - std::runtime_error); -} - -TEST_F(TestAllocatorMemoryStrategy, add_handles_to_wait_set_timer) { - auto node_with_timer = create_node_with_timer("timer_node"); - RclWaitSetSizes insufficient_capacities = SufficientWaitSetCapacities(); - insufficient_capacities.size_of_timers = 0; - EXPECT_TRUE(TestAddHandlesToWaitSet(node_with_timer, insufficient_capacities)); -} - -TEST_F(TestAllocatorMemoryStrategy, add_handles_to_wait_set_waitable) { - rcl_reset_error(); - - rclcpp::Waitable::SharedPtr waitable = std::make_shared(); - EXPECT_NO_THROW(allocator_memory_strategy()->add_waitable_handle(waitable)); - EXPECT_EQ(1u, allocator_memory_strategy()->number_of_waitables()); - - test_waitable_result = true; - EXPECT_TRUE(allocator_memory_strategy()->add_handles_to_wait_set(nullptr)); - - test_waitable_result = false; - EXPECT_THROW( - allocator_memory_strategy()->add_handles_to_wait_set(nullptr), - std::runtime_error); - - // This calls TestWaitable's functions, so rcl errors are not set - EXPECT_FALSE(rcl_error_is_set()); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_subscription) { - auto node1 = create_node_with_subscription("node1"); - auto node2 = create_node_with_subscription("node2"); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_subscription(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntity(node1, node2, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_service) { - auto node1 = create_node_with_service("node1"); - auto node2 = create_node_with_service("node2"); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_service(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntity(node1, node2, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_client) { - auto node1 = create_node_with_client("node1"); - auto node2 = create_node_with_client("node2"); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_client(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntity(node1, node2, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_timer) { - auto node1 = create_node_with_timer("node1"); - auto node2 = create_node_with_timer("node2"); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_timer(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntity(node1, node2, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_waitable) { - auto node1 = std::make_shared("waitable_node", "ns"); - auto node2 = std::make_shared("waitable_node2", "ns"); - rclcpp::Waitable::SharedPtr waitable1 = std::make_shared(); - rclcpp::Waitable::SharedPtr waitable2 = std::make_shared(); - node1->get_node_waitables_interface()->add_waitable(waitable1, nullptr); - node2->get_node_waitables_interface()->add_waitable(waitable2, nullptr); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_waitable(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntity(node1, node2, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_subscription_mutually_exclusive) { - auto node = create_node_with_subscription("node"); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_subscription(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntityMutuallyExclusive(node, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_service_mutually_exclusive) { - auto node = create_node_with_service("node"); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_service(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntityMutuallyExclusive(node, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_client_mutually_exclusive) { - auto node = create_node_with_client("node"); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_client(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntityMutuallyExclusive(node, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_timer_mutually_exclusive) { - auto node = create_node_with_timer("node"); - - auto get_next_entity = [this](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_timer(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntityMutuallyExclusive(node, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_waitable_mutually_exclusive) { - auto node = std::make_shared("waitable_node", "ns"); - rclcpp::Waitable::SharedPtr waitable = std::make_shared(); - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - node->get_node_waitables_interface()->add_waitable(waitable, callback_group); - - auto get_next_entity = - [this, callback_group](const WeakCallbackGroupsToNodesMap & weak_groups_to_nodes) { - // This callback group isn't in the base class' callback_group list, so this needs to be done - // before get_next_waitable() is called. - callback_group->can_be_taken_from() = false; - - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_waitable(result, weak_groups_to_nodes); - return result; - }; - - EXPECT_TRUE(TestGetNextEntityMutuallyExclusive(node, get_next_entity)); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_subscription_out_of_scope) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - auto node = create_node_with_disabled_callback_groups("node"); - // Force subscription to go out of scope and cleanup after collecting entities. - { - rclcpp::SubscriptionOptions subscription_options; - - auto callback_group = - node->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - - subscription_options.callback_group = callback_group; - - auto subscription_callback = [](test_msgs::msg::Empty::ConstSharedPtr) {}; - const rclcpp::QoS qos(10); - - auto subscription = node->create_subscription< - test_msgs::msg::Empty, decltype(subscription_callback)>( - "topic", qos, std::move(subscription_callback), subscription_options); - - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - } - EXPECT_EQ(1u, allocator_memory_strategy()->number_of_ready_subscriptions()); - - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_subscription(result, weak_groups_to_nodes); - EXPECT_EQ(nullptr, result.node_base); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_service_out_of_scope) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - auto node = create_node_with_disabled_callback_groups("node"); - // Force service to go out of scope and cleanup after collecting entities. - { - auto callback_group = - node->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - - auto service_callback = []( - const test_msgs::srv::Empty::Request::SharedPtr, - test_msgs::srv::Empty::Response::SharedPtr) {}; - auto service = node->create_service( - "service", std::move(service_callback), rclcpp::ServicesQoS(), callback_group); - - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - } - // service is out of scope here, so should be cleaned up already. - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_ready_services()); - - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_service(result, weak_groups_to_nodes); - EXPECT_EQ(nullptr, result.node_base); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_client_out_of_scope) { - auto node = create_node_with_disabled_callback_groups("node"); - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - // Force client to go out of scope and cleanup after collecting entities. - { - auto callback_group = - node->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - auto client = node->create_client( - "service", rclcpp::ServicesQoS(), callback_group); - - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - node->get_node_base_interface())); - - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - } - // client is out of scope here, so should be cleaned up already. - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_ready_clients()); - - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_client(result, weak_groups_to_nodes); - EXPECT_EQ(nullptr, result.node_base); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_timer_out_of_scope) { - auto node = create_node_with_disabled_callback_groups("node"); - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - // Force timer to go out of scope and cleanup after collecting entities. - { - auto callback_group = - node->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - auto timer = node->create_wall_timer( - std::chrono::seconds(10), []() {}, callback_group); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - } - // timer is out of scope here, so should be cleaned up already. - EXPECT_EQ(0u, allocator_memory_strategy()->number_of_ready_timers()); - - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_timer(result, weak_groups_to_nodes); - EXPECT_EQ(nullptr, result.node_base); -} - -TEST_F(TestAllocatorMemoryStrategy, get_next_waitable_out_of_scope) { - auto node = create_node_with_disabled_callback_groups("node"); - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - // Force waitable to go out of scope and cleanup after collecting entities. - { - auto callback_group = - node->create_callback_group( - rclcpp::CallbackGroupType::MutuallyExclusive); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - allocator_memory_strategy()->collect_entities(weak_groups_to_nodes); - auto waitable = std::make_shared(); - node->get_node_waitables_interface()->add_waitable(waitable, callback_group); - allocator_memory_strategy()->add_waitable_handle(waitable); - } - // Since all callback groups have been locked, except the one we added, this should only be 1 - EXPECT_EQ(1u, allocator_memory_strategy()->number_of_waitables()); - - rclcpp::AnyExecutable result; - allocator_memory_strategy()->get_next_waitable(result, weak_groups_to_nodes); - EXPECT_EQ(nullptr, result.node_base); -} -RCPPUTILS_DEPRECATION_WARNING_OFF_STOP diff --git a/rclcpp/test/rclcpp/test_executor.cpp b/rclcpp/test/rclcpp/test_executor.cpp index 5c70d5cf85..5c057a0379 100644 --- a/rclcpp/test/rclcpp/test_executor.cpp +++ b/rclcpp/test/rclcpp/test_executor.cpp @@ -33,7 +33,6 @@ #include "rclcpp/executor.hpp" #include "rclcpp/executors/single_threaded_executor.hpp" #include "rclcpp/future_return_code.hpp" -#include "rclcpp/memory_strategy.hpp" #include "rclcpp/node.hpp" #include "rclcpp/qos.hpp" #include "rclcpp/subscription.hpp" diff --git a/rclcpp/test/rclcpp/test_find_weak_nodes.cpp b/rclcpp/test/rclcpp/test_find_weak_nodes.cpp deleted file mode 100644 index bd27241e4b..0000000000 --- a/rclcpp/test/rclcpp/test_find_weak_nodes.cpp +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2016 Open Source Robotics Foundation, Inc. -// -// Licensed 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 -#include - -#include - -// can be removed after the lyrical release -RCPPUTILS_DEPRECATION_WARNING_OFF_START -#include "rclcpp/strategies/allocator_memory_strategy.hpp" -RCPPUTILS_DEPRECATION_WARNING_OFF_STOP -#include "rclcpp/memory_strategy.hpp" -#include "rclcpp/node.hpp" -#include "rclcpp/utilities.hpp" - -RCPPUTILS_DEPRECATION_WARNING_OFF_START -class TestFindWeakNodes : public ::testing::Test -{ -protected: - static void SetUpTestCase() - { - rclcpp::init(0, nullptr); - } - - static void TearDownTestCase() - { - rclcpp::shutdown(); - } -}; - -TEST_F(TestFindWeakNodes, allocator_strategy_with_weak_nodes) { - // GIVEN - // A vector of weak pointers to nodes - auto memory_strategy = std::make_shared< - rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy<>>(); - auto existing_node = rclcpp::Node::make_shared("existing_node"); - auto dead_node = rclcpp::Node::make_shared("dead_node"); - auto existing_group = existing_node->get_node_base_interface()->get_default_callback_group(); - auto dead_group = dead_node->get_node_base_interface()->get_default_callback_group(); - rclcpp::memory_strategy::MemoryStrategy::WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - weak_groups_to_nodes[existing_group] = existing_node->get_node_base_interface(); - weak_groups_to_nodes[dead_group] = dead_node->get_node_base_interface(); - - // AND - // Delete dead_node, creating a dangling pointer in weak_nodes - dead_node.reset(); - ASSERT_FALSE(weak_groups_to_nodes[existing_group].expired()); - ASSERT_TRUE(weak_groups_to_nodes[dead_group].expired()); - - // WHEN - bool has_invalid_weak_groups_or_nodes = memory_strategy->collect_entities(weak_groups_to_nodes); - - // THEN - // The result of finding dangling node pointers should be true - ASSERT_TRUE(has_invalid_weak_groups_or_nodes); - - // Prevent memory leak due to the order of destruction - memory_strategy->clear_handles(); -} - -TEST_F(TestFindWeakNodes, allocator_strategy_no_weak_nodes) { - // GIVEN - // A vector of weak pointers to nodes, all valid - auto memory_strategy = std::make_shared< - rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy<>>(); - auto existing_node1 = rclcpp::Node::make_shared("existing_node1"); - auto existing_node2 = rclcpp::Node::make_shared("existing_node2"); - auto existing_group1 = existing_node1->get_node_base_interface()->get_default_callback_group(); - auto existing_group2 = existing_node2->get_node_base_interface()->get_default_callback_group(); - rclcpp::memory_strategy::MemoryStrategy::WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - weak_groups_to_nodes[existing_group1] = existing_node1->get_node_base_interface(); - weak_groups_to_nodes[existing_group2] = existing_node2->get_node_base_interface(); - ASSERT_FALSE(weak_groups_to_nodes[existing_group1].expired()); - ASSERT_FALSE(weak_groups_to_nodes[existing_group2].expired()); - - // WHEN - bool has_invalid_weak_groups_or_nodes = memory_strategy->collect_entities(weak_groups_to_nodes); - - // THEN - // The result of finding dangling node pointers should be false - ASSERT_FALSE(has_invalid_weak_groups_or_nodes); - - // Prevent memory leak due to the order of destruction - memory_strategy->clear_handles(); -} -RCPPUTILS_DEPRECATION_WARNING_OFF_STOP diff --git a/rclcpp/test/rclcpp/test_memory_strategy.cpp b/rclcpp/test/rclcpp/test_memory_strategy.cpp deleted file mode 100644 index 4b6077ea73..0000000000 --- a/rclcpp/test/rclcpp/test_memory_strategy.cpp +++ /dev/null @@ -1,570 +0,0 @@ -// Copyright 2020 Open Source Robotics Foundation, Inc. -// -// Licensed 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 - -#include -#include -#include -#include - -#include - -// can be removed after the lyrical release -RCPPUTILS_DEPRECATION_WARNING_OFF_START -#include "rclcpp/strategies/allocator_memory_strategy.hpp" -#include "rclcpp/memory_strategy.hpp" -#include "rclcpp/utilities.hpp" -#include "test_msgs/msg/empty.hpp" -#include "test_msgs/srv/empty.hpp" - -using rclcpp::memory_strategy::MemoryStrategy; -typedef std::map> WeakCallbackGroupsToNodesMap; - -/** - * Mock Waitable class - */ -class TestWaitable : public rclcpp::Waitable -{ -public: - void add_to_wait_set(rcl_wait_set_t &) override {} - bool is_ready(const rcl_wait_set_t &) override {return true;} - - std::shared_ptr take_data() override {return nullptr;} - void execute(const std::shared_ptr &) override {} - - void set_on_ready_callback(std::function) override {} - void clear_on_ready_callback() override {} - - std::shared_ptr take_data_by_entity_id(size_t) override {return nullptr;} - - std::vector> get_timers() const override - { - return {}; - } -}; - -class TestMemoryStrategy : public ::testing::Test -{ -public: - TestMemoryStrategy() - : memory_strategy_(nullptr) {} - - void SetUp() override - { - rclcpp::init(0, nullptr); - - // This doesn't test AllocatorMemoryStrategy directly, so we cast to the base class. - // AllocatorMemoryStrategy is more commonly used than MessagePoolMemoryStrategy - // so we use this derived class for these tests. - memory_strategy_ = - std::make_shared< - rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy<>>(); - } - - void TearDown() override - { - rclcpp::shutdown(); - } - -protected: - std::shared_ptr memory_strategy() - { - return memory_strategy_; - } - -private: - std::shared_ptr memory_strategy_; -}; - -TEST_F(TestMemoryStrategy, construct_destruct) { - EXPECT_NE(nullptr, memory_strategy()); -} - -TEST_F(TestMemoryStrategy, get_subscription_by_handle) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - std::shared_ptr subscription_handle; - rclcpp::SubscriptionBase::SharedPtr found_subscription = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - auto subscription_callback = [](test_msgs::msg::Empty::ConstSharedPtr) {}; - const rclcpp::QoS qos(10); - - { - auto subscription = node->create_subscription< - test_msgs::msg::Empty, decltype(subscription_callback)>( - "topic", qos, std::move(subscription_callback)); - - subscription_handle = subscription->get_subscription_handle(); - - EXPECT_EQ( - subscription, - memory_strategy()->get_subscription_by_handle(subscription_handle, weak_groups_to_nodes)); - } // subscription goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_subscription_by_handle(subscription_handle, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_subscription_by_handle(subscription_handle, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - } // Node goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_subscription_by_handle(subscription_handle, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_service_by_handle) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - std::shared_ptr service_handle; - rclcpp::ServiceBase::SharedPtr found_service = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - auto service_callback = []( - const test_msgs::srv::Empty::Request::SharedPtr, - test_msgs::srv::Empty::Response::SharedPtr) {}; - const rclcpp::QoS qos(10); - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - node->get_node_base_interface())); - { - auto service = node->create_service( - "service", std::move(service_callback), - rclcpp::ServicesQoS(), callback_group); - - service_handle = service->get_service_handle(); - - EXPECT_EQ( - service, - memory_strategy()->get_service_by_handle(service_handle, weak_groups_to_nodes)); - } // service goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_service_by_handle(service_handle, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_service_by_handle(service_handle, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - } // Node goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_service_by_handle(service_handle, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_client_by_handle) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - std::shared_ptr client_handle; - rclcpp::ClientBase::SharedPtr found_client = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - { - auto client = node->create_client( - "service", rclcpp::ServicesQoS(), callback_group); - - client_handle = client->get_client_handle(); - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - node->get_node_base_interface())); - - EXPECT_EQ( - client, - memory_strategy()->get_client_by_handle(client_handle, weak_groups_to_nodes)); - } // client goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_client_by_handle(client_handle, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_client_by_handle(client_handle, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - // reset client handle before node destruction, otherwise it tries to access node - // via weak_ptr in its deleter - client_handle.reset(); - } // Node goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_client_by_handle(client_handle, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_timer_by_handle) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - std::shared_ptr timer_handle; - rclcpp::TimerBase::SharedPtr found_timer = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - { - auto timer_callback = []() {}; - auto timer = node->create_wall_timer( - std::chrono::milliseconds(1), timer_callback, callback_group); - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - node->get_node_base_interface())); - - timer_handle = timer->get_timer_handle(); - - EXPECT_EQ( - timer, - memory_strategy()->get_timer_by_handle(timer_handle, weak_groups_to_nodes)); - } // timer goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_timer_by_handle(timer_handle, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_timer_by_handle(timer_handle, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - } // Node goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_timer_by_handle(timer_handle, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_node_by_group) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - rclcpp::CallbackGroup::SharedPtr callback_group = nullptr; - { - auto node = std::make_shared("node", "ns"); - auto node_handle = node->get_node_base_interface(); - node_handle->for_each_callback_group( - [node_handle, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node_handle)); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - EXPECT_EQ( - nullptr, - memory_strategy()->get_node_by_group(nullptr, weak_groups_to_nodes)); - - callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - - // Nothing in the weak_groups_to_nodes, so find fails. - EXPECT_EQ( - nullptr, - memory_strategy()->get_node_by_group(callback_group, weak_groups_to_nodes)); - - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - node->get_node_base_interface())); - EXPECT_EQ( - node_handle, - memory_strategy()->get_node_by_group(callback_group, weak_groups_to_nodes)); - // Clear the handles to not hold NodeBase. - memory_strategy()->clear_handles(); - } // Node goes out of scope - // Callback group still exists, so lookup returns nullptr because node is destroyed. - EXPECT_EQ( - nullptr, - memory_strategy()->get_node_by_group(callback_group, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_group_by_subscription) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - rclcpp::SubscriptionBase::SharedPtr subscription = nullptr; - rclcpp::CallbackGroup::SharedPtr callback_group = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - // This group is just used to test that a callback group that is held as a weak pointer - // by node, doesn't confuse get_group_by_subscription() when it goes out of scope - auto non_persistant_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - - callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - auto subscription_callback = [](test_msgs::msg::Empty::ConstSharedPtr) {}; - const rclcpp::QoS qos(10); - - rclcpp::SubscriptionOptions subscription_options; - - // This callback group is held as a shared_ptr in subscription_options, which means it - // stays alive as long as subscription does. - subscription_options.callback_group = callback_group; - - subscription = node->create_subscription< - test_msgs::msg::Empty, decltype(subscription_callback)>( - "topic", qos, std::move(subscription_callback), subscription_options); - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - rclcpp::node_interfaces::NodeBaseInterface::WeakPtr(node->get_node_base_interface()))); - EXPECT_EQ( - callback_group, - memory_strategy()->get_group_by_subscription(subscription, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - callback_group, - memory_strategy()->get_group_by_subscription(subscription, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - } // Node goes out of scope - // NodeBase(SubscriptionBase->rcl_node_t->NodeBase) is still alive. - EXPECT_EQ( - callback_group, - memory_strategy()->get_group_by_subscription(subscription, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_group_by_service) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - rclcpp::ServiceBase::SharedPtr service = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - auto service_callback = []( - const test_msgs::srv::Empty::Request::SharedPtr, - test_msgs::srv::Empty::Response::SharedPtr) {}; - const rclcpp::QoS qos(10); - - service = node->create_service( - "service", std::move(service_callback), - rclcpp::ServicesQoS(), callback_group); - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - rclcpp::node_interfaces::NodeBaseInterface::WeakPtr(node->get_node_base_interface()))); - EXPECT_EQ( - callback_group, - memory_strategy()->get_group_by_service(service, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_group_by_service(service, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - } // Node goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_group_by_service(service, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_group_by_client) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - rclcpp::ClientBase::SharedPtr client = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - - client = node->create_client( - "service", rclcpp::ServicesQoS(), callback_group); - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - rclcpp::node_interfaces::NodeBaseInterface::WeakPtr(node->get_node_base_interface()))); - EXPECT_EQ( - callback_group, - memory_strategy()->get_group_by_client(client, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_group_by_client(client, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - } // Node goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_group_by_client(client, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_group_by_timer) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - rclcpp::TimerBase::SharedPtr timer = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - auto timer_callback = []() {}; - timer = node->create_wall_timer( - std::chrono::milliseconds(1), timer_callback, callback_group); - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - rclcpp::node_interfaces::NodeBaseInterface::WeakPtr(node->get_node_base_interface()))); - EXPECT_EQ( - callback_group, - memory_strategy()->get_group_by_timer(timer, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_group_by_timer(timer, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - } // Node goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_group_by_timer(timer, weak_groups_to_nodes)); -} - -TEST_F(TestMemoryStrategy, get_group_by_waitable) { - WeakCallbackGroupsToNodesMap weak_groups_to_nodes; - rclcpp::Waitable::SharedPtr waitable = nullptr; - { - auto node = std::make_shared("node", "ns"); - node->for_each_callback_group( - [node, &weak_groups_to_nodes](rclcpp::CallbackGroup::SharedPtr group_ptr) - { - weak_groups_to_nodes.insert( - std::pair( - group_ptr, - node->get_node_base_interface())); - }); - memory_strategy()->collect_entities(weak_groups_to_nodes); - { - waitable = std::make_shared(); - auto callback_group = - node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); - node->get_node_waitables_interface()->add_waitable(waitable, callback_group); - weak_groups_to_nodes.insert( - std::pair( - rclcpp::CallbackGroup::WeakPtr(callback_group), - rclcpp::node_interfaces::NodeBaseInterface::WeakPtr(node->get_node_base_interface()))); - EXPECT_EQ( - callback_group, - memory_strategy()->get_group_by_waitable(waitable, weak_groups_to_nodes)); - } // callback_group goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_group_by_waitable(waitable, weak_groups_to_nodes)); - // Clear all handles to cleanup when node is destroyed - memory_strategy()->clear_handles(); - } // Node goes out of scope - EXPECT_EQ( - nullptr, - memory_strategy()->get_group_by_waitable(waitable, weak_groups_to_nodes)); -} -RCPPUTILS_DEPRECATION_WARNING_OFF_STOP From 8e5259b1501e2367d2234f7b2040c94ec7d82647 Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Sat, 28 Nov 2026 11:09:59 -0600 Subject: [PATCH 10/18] test_qos_event: declare event counters before the entities that call them test_on_new_event_callback installed callbacks capturing local atomics by reference on a publisher/subscription whose deadline events fire every few milliseconds on the middleware's thread. The counters were declared after the publisher and subscription, so they were destroyed first and the still-running callbacks wrote to dead stack memory (AddressSanitizer: stack-use-after-scope). Declare them before the entities. Signed-off-by: Michael Carroll --- rclcpp/test/rclcpp/test_qos_event.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/rclcpp/test/rclcpp/test_qos_event.cpp b/rclcpp/test/rclcpp/test_qos_event.cpp index f14cd5878d..d4c3e9417a 100644 --- a/rclcpp/test/rclcpp/test_qos_event.cpp +++ b/rclcpp/test/rclcpp/test_qos_event.cpp @@ -365,6 +365,11 @@ TEST_F(TestQosEvent, test_on_new_event_callback) auto offered_deadline = rclcpp::Duration(std::chrono::milliseconds(1)); auto requested_deadline = rclcpp::Duration(std::chrono::milliseconds(2)); + // The event callbacks keep firing on the middleware's thread until the publisher and subscription + // are destroyed, so the counters they capture must outlive both. + std::atomic c1 {0}; + std::atomic c2 {0}; + rclcpp::QoS qos_profile_publisher(10); qos_profile_publisher.deadline(offered_deadline); rclcpp::PublisherOptions pub_options; @@ -379,7 +384,6 @@ TEST_F(TestQosEvent, test_on_new_event_callback) auto subscription = node->create_subscription( topic_name, qos_profile_subscription, message_callback, sub_options); - std::atomic c1 {0}; auto increase_c1_cb = [&c1](size_t count_events) {c1 += count_events;}; publisher->set_on_new_qos_event_callback(increase_c1_cb, RCL_PUBLISHER_OFFERED_DEADLINE_MISSED); @@ -392,7 +396,6 @@ TEST_F(TestQosEvent, test_on_new_event_callback) EXPECT_GT(c1, 1u); - std::atomic c2 {0}; auto increase_c2_cb = [&c2](size_t count_events) {c2 += count_events;}; subscription->set_on_new_qos_event_callback( increase_c2_cb, From 9d08482ced0b417b2ec694c9d4ea241680a5fdbe Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Sat, 28 Nov 2026 11:09:59 -0600 Subject: [PATCH 11/18] Keep the introspection clock alive for the lifetime of the service/client The introspection publisher stores a raw pointer to the clock's rcl handle and dereferences it when the service or client is finalized. Neither Service nor Client held a reference to the clock passed to configure_introspection(), so destroying the clock first (e.g. the node's clock when the node is destroyed before the service) left rcl_service_fini()/rcl_client_fini() reading freed memory. Found with AddressSanitizer. Signed-off-by: Michael Carroll --- rclcpp/include/rclcpp/client.hpp | 6 ++++++ rclcpp/include/rclcpp/service.hpp | 6 ++++++ rclcpp/test/rclcpp/test_service_introspection.cpp | 14 ++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/rclcpp/include/rclcpp/client.hpp b/rclcpp/include/rclcpp/client.hpp index 491be8c23a..45a88ace27 100644 --- a/rclcpp/include/rclcpp/client.hpp +++ b/rclcpp/include/rclcpp/client.hpp @@ -325,6 +325,10 @@ class ClientBase std::shared_ptr context_; rclcpp::Logger node_logger_; + // The introspection publisher keeps a raw pointer to this clock's rcl handle and uses it while + // finalizing the client. Keep the clock alive until client_handle_ (declared below) is finalized. + rclcpp::Clock::SharedPtr introspection_clock_; + std::recursive_mutex callback_mutex_; // It is important to declare on_new_response_callback_ before // client_handle_, so on destruction the client is @@ -759,6 +763,8 @@ class Client : public ClientBase if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret, "failed to configure client introspection"); } + + introspection_clock_ = clock; } protected: diff --git a/rclcpp/include/rclcpp/service.hpp b/rclcpp/include/rclcpp/service.hpp index 3afe1d2e81..909d10fc6a 100644 --- a/rclcpp/include/rclcpp/service.hpp +++ b/rclcpp/include/rclcpp/service.hpp @@ -212,6 +212,10 @@ class ServiceBase std::shared_ptr node_handle_; + // The introspection publisher keeps a raw pointer to this clock's rcl handle and uses it while + // finalizing the service. Keep the clock alive until service_handle_ (declared below) is finalized. + rclcpp::Clock::SharedPtr introspection_clock_; + std::recursive_mutex callback_mutex_; // It is important to declare on_new_request_callback_ before // service_handle_, so on destruction the service is @@ -475,6 +479,8 @@ class Service if (RCL_RET_OK != ret) { rclcpp::exceptions::throw_from_rcl_error(ret, "failed to configure service introspection"); } + + introspection_clock_ = clock; } private: diff --git a/rclcpp/test/rclcpp/test_service_introspection.cpp b/rclcpp/test/rclcpp/test_service_introspection.cpp index 6d56141031..5e56710ff9 100644 --- a/rclcpp/test/rclcpp/test_service_introspection.cpp +++ b/rclcpp/test/rclcpp/test_service_introspection.cpp @@ -431,3 +431,17 @@ TEST_F(TestServiceIntrospection, service_introspection_enable_disable_event_cont } } } + +TEST_F(TestServiceIntrospection, introspection_keeps_clock_alive) +{ + // The introspection publisher uses the clock while the service/client are finalized, so the + // service/client must keep it alive even if the caller drops its reference first. + auto clock = std::make_shared(RCL_STEADY_TIME); + client->configure_introspection(clock, rclcpp::ServicesQoS(), RCL_SERVICE_INTROSPECTION_METADATA); + service->configure_introspection( + clock, rclcpp::ServicesQoS(), RCL_SERVICE_INTROSPECTION_METADATA); + clock.reset(); + + client.reset(); + service.reset(); +} From 551cb6bfad7b2e8994321bf6bca2b838942b90d7 Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Sat, 28 Nov 2026 14:59:46 -0600 Subject: [PATCH 12/18] test_node_graph: release arrays when the mocked fini fails Tests that make rcl_names_and_types_fini(), rcutils_string_array_fini() or rcl_topic_endpoint_info_array_fini() fail leave the array allocated by the code under test unreleased, which LeakSanitizer reports. Have the replacement functions free the memory before returning the error. Signed-off-by: Michael Carroll --- .../node_interfaces/test_node_graph.cpp | 111 ++++++++++++------ 1 file changed, 75 insertions(+), 36 deletions(-) diff --git a/rclcpp/test/rclcpp/node_interfaces/test_node_graph.cpp b/rclcpp/test/rclcpp/node_interfaces/test_node_graph.cpp index 409ca7af91..3399d0f1e7 100644 --- a/rclcpp/test/rclcpp/node_interfaces/test_node_graph.cpp +++ b/rclcpp/test/rclcpp/node_interfaces/test_node_graph.cpp @@ -34,6 +34,8 @@ #include "rclcpp/qos.hpp" #include "rclcpp/utilities.hpp" #include "rcutils/strdup.h" +#include "rmw/names_and_types.h" +#include "rmw/topic_endpoint_info_array.h" #include "test_msgs/msg/empty.h" #include "test_msgs/msg/empty.hpp" #include "test_msgs/srv/empty.hpp" @@ -44,6 +46,43 @@ namespace { +// Replacement for rcl_names_and_types_fini() that reports a failure. The array is released first, +// as the code under test has no way to do it once the call failed, and the test would leak it. +rcl_ret_t fini_names_and_types_then_fail(rcl_names_and_types_t * names_and_types) +{ + // not rcl_names_and_types_fini(), that is the function being patched + rmw_names_and_types_fini(names_and_types); + return RCL_RET_ERROR; +} + +// Same for rcutils_string_array_fini(), which has no other symbol to call: release the strings by +// hand. +rcutils_ret_t fini_string_array_then_fail(rcutils_string_array_t * string_array) +{ + if (string_array->data) { + for (size_t i = 0; i < string_array->size; ++i) { + string_array->allocator.deallocate(string_array->data[i], string_array->allocator.state); + } + string_array->allocator.deallocate(string_array->data, string_array->allocator.state); + } + *string_array = rcutils_get_zero_initialized_string_array(); + return RCUTILS_RET_ERROR; +} + +rcl_ret_t fini_endpoint_info_array_then_fail( + rmw_topic_endpoint_info_array_t * info_array, rcutils_allocator_t * allocator) +{ + // rcl_topic_endpoint_info_array_fini() is the rmw function under another name, release by hand + if (info_array->info_array) { + for (size_t i = 0; i < info_array->size; ++i) { + rmw_topic_endpoint_info_fini(&info_array->info_array[i], allocator); + } + allocator->deallocate(info_array->info_array, allocator->state); + } + *info_array = rmw_get_zero_initialized_topic_endpoint_info_array(); + return RCL_RET_ERROR; +} + constexpr char node_name[] = "node"; constexpr char node_namespace[] = "ns"; constexpr char absolute_namespace[] = "/ns"; @@ -159,8 +198,8 @@ TEST_F(TestNodeGraph, get_topic_names_and_types_rcl_error) { auto mock_get_topic_names = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_topic_names_and_types, RCL_RET_ERROR); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_topic_names_and_types(), @@ -171,8 +210,8 @@ TEST_F(TestNodeGraph, get_topic_names_and_types_rcl_error) TEST_F(TestNodeGraph, get_topic_names_and_types_rcl_names_and_types_fini_error) { - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_topic_names_and_types(), @@ -188,8 +227,8 @@ TEST_F(TestNodeGraph, get_service_names_and_types_rcl_error) { auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_service_names_and_types, RCL_RET_ERROR); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_service_names_and_types(), std::runtime_error( @@ -199,8 +238,8 @@ TEST_F(TestNodeGraph, get_service_names_and_types_rcl_error) TEST_F(TestNodeGraph, get_service_names_and_types_rcl_names_and_types_fini) { - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_service_names_and_types(), std::runtime_error("could not destroy service names and types: error not set")); @@ -288,8 +327,8 @@ TEST_F(TestNodeGraph, get_service_names_and_types_by_node_rcl_errors) auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_service_names_and_types_by_node, RCL_RET_ERROR); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_service_names_and_types_by_node(node_name, node_namespace), std::runtime_error( @@ -304,8 +343,8 @@ TEST_F(TestNodeGraph, get_client_names_and_types_by_node_rcl_errors) auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_client_names_and_types_by_node, RCL_RET_ERROR); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_client_names_and_types_by_node(node_name, node_namespace), std::runtime_error( @@ -319,8 +358,8 @@ TEST_F(TestNodeGraph, get_service_names_and_types_by_node_names_and_types_fini_e test_msgs::srv::Empty::Response::SharedPtr) {}; auto service = node()->create_service("node1_service", std::move(callback)); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); EXPECT_THROW( node_graph()->get_service_names_and_types_by_node(node_name, absolute_namespace), @@ -330,8 +369,8 @@ TEST_F(TestNodeGraph, get_service_names_and_types_by_node_names_and_types_fini_e TEST_F(TestNodeGraph, get_client_names_and_types_by_node_names_and_types_fini_error) { auto client = node()->create_client("node1_service"); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); EXPECT_NO_THROW( node_graph()->get_client_names_and_types_by_node(node_name, absolute_namespace)); @@ -417,8 +456,8 @@ TEST_F(TestNodeGraph, get_publisher_names_and_types_by_node_rcl_errors) auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_publisher_names_and_types_by_node, RCL_RET_ERROR); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_publisher_names_and_types_by_node(node_name, node_namespace), std::runtime_error( @@ -436,8 +475,8 @@ TEST_F(TestNodeGraph, get_subscriber_names_and_types_by_node_rcl_errors) auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_subscriber_names_and_types_by_node, RCL_RET_ERROR); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_subscriber_names_and_types_by_node(node_name, node_namespace), std::runtime_error( @@ -449,8 +488,8 @@ TEST_F(TestNodeGraph, get_publisher_names_and_types_by_node_names_and_types_fini const rclcpp::QoS publisher_qos(1); auto publisher = node()->create_publisher("topic", publisher_qos); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); EXPECT_NO_THROW( node_graph()->get_publisher_names_and_types_by_node(node_name, absolute_namespace)); @@ -464,8 +503,8 @@ TEST_F(TestNodeGraph, get_subscriber_names_and_types_by_node_names_and_types_fin node()->create_subscription( "topic", subscriber_qos, std::move(callback)); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_names_and_types_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcl_names_and_types_fini, fini_names_and_types_then_fail); EXPECT_NO_THROW( node_graph()->get_subscriber_names_and_types_by_node(node_name, absolute_namespace)); @@ -488,8 +527,8 @@ TEST_F(TestNodeGraph, get_node_names_and_namespaces_rcl_errors) { auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_node_names, RCL_RET_ERROR); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcutils_string_array_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcutils_string_array_fini, fini_string_array_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_node_names_and_namespaces(), std::runtime_error( @@ -501,8 +540,8 @@ TEST_F(TestNodeGraph, get_node_names_with_enclaves_rcl_errors) { auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_node_names_with_enclaves, RCL_RET_ERROR); - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcutils_string_array_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcutils_string_array_fini, fini_string_array_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_node_names_with_enclaves(), std::runtime_error( @@ -513,8 +552,8 @@ TEST_F(TestNodeGraph, get_node_names_with_enclaves_rcl_errors) TEST_F(TestNodeGraph, get_node_names_and_namespaces_fini_errors) { - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcutils_string_array_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcutils_string_array_fini, fini_string_array_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_node_names_and_namespaces(), std::runtime_error( @@ -524,8 +563,8 @@ TEST_F(TestNodeGraph, get_node_names_and_namespaces_fini_errors) TEST_F(TestNodeGraph, get_node_names_with_enclaves_fini_errors) { - auto mock_names_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcutils_string_array_fini, RCL_RET_ERROR); + auto mock_names_fini = mocking_utils::patch( + "lib:rclcpp", rcutils_string_array_fini, fini_string_array_then_fail); RCLCPP_EXPECT_THROW_EQ( node_graph()->get_node_names_with_enclaves(), std::runtime_error( @@ -710,8 +749,8 @@ TEST_F(TestNodeGraph, get_info_by_topic_rcl_errors) auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_publishers_info_by_topic, RCL_RET_ERROR); - auto mock_info_array_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_topic_endpoint_info_array_fini, RCL_RET_ERROR); + auto mock_info_array_fini = mocking_utils::patch( + "lib:rclcpp", rcl_topic_endpoint_info_array_fini, fini_endpoint_info_array_then_fail); EXPECT_THROW( node_graph()->get_publishers_info_by_topic("topic", false), rclcpp::exceptions::RCLError); @@ -734,8 +773,8 @@ TEST_F(TestNodeGraph, get_info_by_topic_endpoint_info_array_fini_error) const rclcpp::QoS publisher_qos(1); auto publisher = node()->create_publisher("topic", publisher_qos); - auto mock_info_array_fini = mocking_utils::patch_and_return( - "lib:rclcpp", rcl_topic_endpoint_info_array_fini, RCL_RET_ERROR); + auto mock_info_array_fini = mocking_utils::patch( + "lib:rclcpp", rcl_topic_endpoint_info_array_fini, fini_endpoint_info_array_then_fail); EXPECT_THROW( node_graph()->get_publishers_info_by_topic("topic", false), rclcpp::exceptions::RCLError); From 5fa8995b85e969d1c47182259d8d8469475061df Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Sat, 28 Nov 2026 15:36:19 -0600 Subject: [PATCH 13/18] Release wait sets and clients that the tests leak test_graph_listener, and the is_ready tests of the action client and generic client, initialize an rcl wait set by hand and never finalize it. construction_and_destruction_rcl_errors replaces rcl_action_client_fini() with a function that only returns an error, so the client is never finalized. Finalize the wait sets, and call the real rcl_action_client_fini() before injecting the error. Found with LeakSanitizer. Signed-off-by: Michael Carroll --- rclcpp/test/rclcpp/test_graph_listener.cpp | 12 ++++++++++-- rclcpp_action/test/test_client.cpp | 3 ++- rclcpp_action/test/test_generic_client.cpp | 1 + 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/rclcpp/test/rclcpp/test_graph_listener.cpp b/rclcpp/test/rclcpp/test_graph_listener.cpp index 2dd8050545..92d0019f86 100644 --- a/rclcpp/test/rclcpp/test_graph_listener.cpp +++ b/rclcpp/test/rclcpp/test_graph_listener.cpp @@ -162,6 +162,8 @@ TEST_F(TestGraphListener, error_run_graph_listener_mock_wait_set_clear) { RCLCPP_EXPECT_THROW_EQ( graph_listener_test->run_protected(), std::runtime_error("failed to clear wait set: error not set")); + // the wait set was initialized by hand, release it + graph_listener_test->mock_cleanup_wait_set(); } TEST_F(TestGraphListener, error_run_graph_listener_mock_wait_set_add_guard_condition) { @@ -174,6 +176,8 @@ TEST_F(TestGraphListener, error_run_graph_listener_mock_wait_set_add_guard_condi RCLCPP_EXPECT_THROW_EQ( graph_listener_test->run_protected(), std::runtime_error("failed to add guard condition to wait set: error not set")); + // the wait set was initialized by hand, release it + graph_listener_test->mock_cleanup_wait_set(); } TEST_F(TestGraphListener, error_run_graph_listener_mock_wait_error) { @@ -186,6 +190,8 @@ TEST_F(TestGraphListener, error_run_graph_listener_mock_wait_error) { RCLCPP_EXPECT_THROW_EQ( graph_listener_test->run_protected(), std::runtime_error("failed to wait on wait set: error not set")); + // the wait set was initialized by hand, release it + graph_listener_test->mock_cleanup_wait_set(); } TEST_F(TestGraphListener, error_run_graph_listener_mock_wait_timeout) { @@ -198,6 +204,8 @@ TEST_F(TestGraphListener, error_run_graph_listener_mock_wait_timeout) { RCLCPP_EXPECT_THROW_EQ( graph_listener_test->run_protected(), std::runtime_error("rcl_wait unexpectedly timed out")); + // the wait set was initialized by hand, release it + graph_listener_test->mock_cleanup_wait_set(); } /* Add/Remove node usage */ @@ -272,14 +280,14 @@ TEST_F(TestGraphListener, test_graph_listener_shutdown_wait_fini_error_throw) { auto graph_listener_test = std::make_shared(global_context); - graph_listener()->start_if_not_started(); + graph_listener_test->start_if_not_started(); { auto mock_wait_set_fini = mocking_utils::patch_and_return( "lib:rclcpp", rcl_wait_set_fini, RCL_RET_ERROR); RCLCPP_EXPECT_THROW_EQ( - graph_listener()->shutdown(), + graph_listener_test->shutdown(), std::runtime_error("failed to finalize wait set: error not set")); } diff --git a/rclcpp_action/test/test_client.cpp b/rclcpp_action/test/test_client.cpp index c461d1eeed..627fd6108e 100644 --- a/rclcpp_action/test/test_client.cpp +++ b/rclcpp_action/test/test_client.cpp @@ -391,7 +391,7 @@ TEST_F(TestClient, construction_and_destruction_callback_group) TEST_F(TestClient, construction_and_destruction_rcl_errors) { { - auto mock = mocking_utils::patch_and_return( + auto mock = mocking_utils::inject_on_return( "lib:rclcpp_action", rcl_action_client_fini, RCL_RET_ERROR); // It just logs an error message and continues EXPECT_NO_THROW( @@ -577,6 +577,7 @@ TEST_F(TestClient, is_ready) { "lib:rclcpp_action", rcl_action_client_wait_set_get_entities_ready, RCL_RET_ERROR); EXPECT_THROW(action_client->is_ready(wait_set), rclcpp::exceptions::RCLError); } + EXPECT_EQ(RCL_RET_OK, rcl_wait_set_fini(&wait_set)); client_node.reset(); // Drop node before action client } diff --git a/rclcpp_action/test/test_generic_client.cpp b/rclcpp_action/test/test_generic_client.cpp index 0bca9acd0b..fc0a61a1bd 100644 --- a/rclcpp_action/test/test_generic_client.cpp +++ b/rclcpp_action/test/test_generic_client.cpp @@ -450,6 +450,7 @@ TEST_F(TestGenericClient, is_ready) { "lib:rclcpp_action", rcl_action_client_wait_set_get_entities_ready, RCL_RET_ERROR); EXPECT_THROW(action_generic_client->is_ready(wait_set), rclcpp::exceptions::RCLError); } + EXPECT_EQ(RCL_RET_OK, rcl_wait_set_fini(&wait_set)); client_node.reset(); // Drop node before action client } From 919bfa02e5ac925a018bb2f3637f4f5c5848ce04 Mon Sep 17 00:00:00 2001 From: Christophe Bedard Date: Sat, 28 Nov 2026 17:41:45 -0800 Subject: [PATCH 14/18] Fix non-const shared_ptr callback deprecation warnings with GCC (#3450) Subscription callbacks taking a `std::shared_ptr` to a non-const message were deprecated in https://github.com/ros2/rclcpp/pull/2975 (Lyrical), but the `[[deprecated]]` function, `AnySubscriptionCallback::set_deprecated()`, is only used inside rclcpp headers. Downstream packages include these as system headers, and GCC does not show warnings located in system headers, even if user code triggered the template instantiation, so only Clang >= 18 shows the warning. Instead, add `[[deprecated]]` overloads of `create_subscription()` and `create_generic_subscription()` (free functions and `Node` and `LifecycleNode` member functions), constrained to the deprecated callback signatures, so that the warning is located at the user's call. Move the `create_generic_subscription()` implementation to `rclcpp::detail` so that both overloads can use it, like `create_subscription()`. Then remove `set_deprecated()` and the `RCLCPP_AVOID_DEPRECATIONS_FOR_UNIT_TESTS` macro. Since GCC users will only see the warning starting with Makoa, add TODOs to remove these overloads and the support for these callback signatures after Makoa. Also update the `rclcpp_action` tests that used a deprecated callback. Part of https://github.com/ros2/rclcpp/issues/3176 Signed-off-by: Christophe Bedard --- .../rclcpp/any_subscription_callback.hpp | 72 ++------------- .../rclcpp/create_generic_subscription.hpp | 88 ++++++++++++++----- rclcpp/include/rclcpp/create_subscription.hpp | 74 ++++++++++++++++ .../subscription_callback_type_helper.hpp | 67 ++++++++++++++ rclcpp/include/rclcpp/node.hpp | 55 ++++++++++++ rclcpp/include/rclcpp/node_impl.hpp | 46 ++++++++++ .../rclcpp/test_any_subscription_callback.cpp | 61 ++++++++++++- .../test/rclcpp/test_create_subscription.cpp | 51 +++++++++++ rclcpp_action/test/test_client.cpp | 2 +- rclcpp_action/test/test_generic_client.cpp | 2 +- .../rclcpp_lifecycle/lifecycle_node.hpp | 54 ++++++++++++ .../rclcpp_lifecycle/lifecycle_node_impl.hpp | 48 ++++++++++ rclcpp_lifecycle/test/test_lifecycle_node.cpp | 29 ++++++ 13 files changed, 559 insertions(+), 90 deletions(-) diff --git a/rclcpp/include/rclcpp/any_subscription_callback.hpp b/rclcpp/include/rclcpp/any_subscription_callback.hpp index d66d7b7cab..dc1910584d 100644 --- a/rclcpp/include/rclcpp/any_subscription_callback.hpp +++ b/rclcpp/include/rclcpp/any_subscription_callback.hpp @@ -138,6 +138,7 @@ struct AnySubscriptionCallbackPossibleTypes const std::shared_ptr &, const rclcpp::MessageInfo &)>; + // TODO(christophebedard): remove after Makoa // Deprecated signatures: using SharedPtrCallback = std::function)>; @@ -378,9 +379,9 @@ class AnySubscriptionCallback /// Generic function for setting the callback. /** - * There are specializations that overload this in order to deprecate some - * callback signatures, and also to fix ambiguity between shared_ptr and - * unique_ptr callback signatures when using them with lambda functions. + * There are specializations that overload this in order to fix ambiguity + * between shared_ptr and unique_ptr callback signatures when using them with + * lambda functions. */ template AnySubscriptionCallback @@ -392,77 +393,14 @@ class AnySubscriptionCallback // converted to one another, e.g. shared_ptr and unique_ptr. using scbth = detail::SubscriptionCallbackTypeHelper; - // Determine if the given CallbackT is a deprecated signature or not. - constexpr auto is_deprecated = - rclcpp::function_traits::same_arguments< - typename scbth::callback_type, - std::function)> - >::value || - rclcpp::function_traits::same_arguments< - typename scbth::callback_type, - std::function, const rclcpp::MessageInfo &)> - >::value || - rclcpp::function_traits::same_arguments< - typename scbth::callback_type, - std::function)> - >::value || - rclcpp::function_traits::same_arguments< - typename scbth::callback_type, - std::function, const rclcpp::MessageInfo &)> - >::value || - rclcpp::function_traits::same_arguments< - typename scbth::callback_type, - std::function)> - >::value || - rclcpp::function_traits::same_arguments< - typename scbth::callback_type, - std::function, const rclcpp::MessageInfo &)> - >::value; - // Use the discovered type to force the type of callback when assigning // into the variant. - if constexpr (is_deprecated) { - // If deprecated, call sub-routine that is deprecated. - set_deprecated(static_cast(callback)); - } else { - // Otherwise just assign it. - callback_variant_ = static_cast(callback); - } + callback_variant_ = static_cast(callback); // Return copy of self for easier testing, normally will be compiled out. return *this; } - /// Function for shared_ptr to non-const MessageT, which is deprecated. - template - // *INDENT-OFF* - #if !defined(RCLCPP_AVOID_DEPRECATIONS_FOR_UNIT_TESTS) - // suppress deprecation warnings in `test_any_subscription_callback.cpp` - [[deprecated("use 'void(std::shared_ptr)' instead")]] - #endif - // *INDENT-ON* - void - set_deprecated(std::function)> callback) - { - callback_variant_ = callback; - } - - /// Function for shared_ptr to non-const MessageT with MessageInfo, which is deprecated. - template - // *INDENT-OFF* - #if !defined(RCLCPP_AVOID_DEPRECATIONS_FOR_UNIT_TESTS) - // suppress deprecation warnings in `test_any_subscription_callback.cpp` - [[deprecated( - "use 'void(std::shared_ptr, const rclcpp::MessageInfo &)' instead" - )]] - #endif - // *INDENT-ON* - void - set_deprecated(std::function, const rclcpp::MessageInfo &)> callback) - { - callback_variant_ = callback; - } - /// Disable the callback from being called during dispatch. void disable() { diff --git a/rclcpp/include/rclcpp/create_generic_subscription.hpp b/rclcpp/include/rclcpp/create_generic_subscription.hpp index 381da45994..90483c4be1 100644 --- a/rclcpp/include/rclcpp/create_generic_subscription.hpp +++ b/rclcpp/include/rclcpp/create_generic_subscription.hpp @@ -22,6 +22,7 @@ #include "rcl/subscription.h" #include "rclcpp/any_subscription_callback.hpp" +#include "rclcpp/detail/subscription_callback_type_helper.hpp" #include "rclcpp/generic_subscription.hpp" #include "rclcpp/node_interfaces/node_topics_interface.hpp" #include "rclcpp/qos.hpp" @@ -32,33 +33,18 @@ namespace rclcpp { -/// Create and return a GenericSubscription. -/** - * The returned pointer will never be empty, but this function can throw various exceptions, for - * instance when the message's package can not be found on the AMENT_PREFIX_PATH. - * - * \param topics_interface NodeTopicsInterface pointer used in parts of the setup. - * \param topic_name Topic name - * \param topic_type Topic type - * \param qos %QoS settings - * \param callback Callback for new messages of serialized form - * \param options %Publisher options. - * Not all publisher options are currently respected, the only relevant options for this - * publisher are `event_callbacks`, `use_default_callbacks`, and `%callback_group`. - */ +namespace detail +{ template< typename CallbackT, - typename AllocatorT = std::allocator> + typename AllocatorT> std::shared_ptr create_generic_subscription( - rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr topics_interface, + const rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr & topics_interface, const std::string & topic_name, const std::string & topic_type, const rclcpp::QoS & qos, CallbackT && callback, - const rclcpp::SubscriptionOptionsWithAllocator & options = ( - rclcpp::SubscriptionOptionsWithAllocator() - ) -) + const rclcpp::SubscriptionOptionsWithAllocator & options) { auto ts_lib = rclcpp::get_typesupport_library( topic_type, "rosidl_typesupport_cpp"); @@ -83,6 +69,68 @@ std::shared_ptr create_generic_subscription( return subscription; } +} // namespace detail + +/// Create and return a GenericSubscription. +/** + * The returned pointer will never be empty, but this function can throw various exceptions, for + * instance when the message's package can not be found on the AMENT_PREFIX_PATH. + * + * \param topics_interface NodeTopicsInterface pointer used in parts of the setup. + * \param topic_name Topic name + * \param topic_type Topic type + * \param qos %QoS settings + * \param callback Callback for new messages of serialized form + * \param options %Publisher options. + * Not all publisher options are currently respected, the only relevant options for this + * publisher are `event_callbacks`, `use_default_callbacks`, and `%callback_group`. + */ +template< + typename CallbackT, + typename AllocatorT = std::allocator> +std::shared_ptr create_generic_subscription( + rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr topics_interface, + const std::string & topic_name, + const std::string & topic_type, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options = ( + rclcpp::SubscriptionOptionsWithAllocator() + ) +) +{ + return rclcpp::detail::create_generic_subscription( + topics_interface, topic_name, topic_type, qos, std::forward(callback), options); +} + +// TODO(christophebedard): remove after Makoa +/// Create and return a GenericSubscription. +/** + * \deprecated Subscription callbacks taking a std::shared_ptr to a non-const + * rclcpp::SerializedMessage are deprecated, use + * std::shared_ptr instead. + */ +template< + typename CallbackT, + typename AllocatorT = std::allocator> +requires rclcpp::detail::deprecated_subscription_callback +[[deprecated( + "subscription callbacks taking a std::shared_ptr to a non-const message are deprecated, " + "use std::shared_ptr instead")]] +std::shared_ptr create_generic_subscription( + rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr topics_interface, + const std::string & topic_name, + const std::string & topic_type, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options = ( + rclcpp::SubscriptionOptionsWithAllocator() + ) +) +{ + return rclcpp::detail::create_generic_subscription( + topics_interface, topic_name, topic_type, qos, std::forward(callback), options); +} } // namespace rclcpp diff --git a/rclcpp/include/rclcpp/create_subscription.hpp b/rclcpp/include/rclcpp/create_subscription.hpp index 84b6be5cb3..2e1741907b 100644 --- a/rclcpp/include/rclcpp/create_subscription.hpp +++ b/rclcpp/include/rclcpp/create_subscription.hpp @@ -23,6 +23,7 @@ #include #include "rclcpp/detail/qos_parameters.hpp" +#include "rclcpp/detail/subscription_callback_type_helper.hpp" #include "rclcpp/node_interfaces/get_node_topics_interface.hpp" #include "rclcpp/node_interfaces/node_parameters_interface.hpp" #include "rclcpp/node_interfaces/node_topics_interface.hpp" @@ -135,6 +136,42 @@ create_subscription( node, node, topic_name, qos, std::forward(callback), options, msg_mem_strat); } +// TODO(christophebedard): remove after Makoa +/// Create and return a subscription of the given MessageT type. +/** + * \deprecated Subscription callbacks taking a std::shared_ptr to a non-const message are + * deprecated, use std::shared_ptr instead. + */ +template< + typename MessageT, + typename CallbackT, + typename AllocatorT = std::allocator, + typename SubscriptionT = rclcpp::Subscription, + typename MessageMemoryStrategyT = typename SubscriptionT::MessageMemoryStrategyType, + typename NodeT> +requires rclcpp::detail::deprecated_subscription_callback +[[deprecated( + "subscription callbacks taking a std::shared_ptr to a non-const message are deprecated, " + "use std::shared_ptr instead")]] +typename std::shared_ptr +create_subscription( + NodeT & node, + const std::string & topic_name, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options = ( + rclcpp::SubscriptionOptionsWithAllocator() + ), + typename MessageMemoryStrategyT::SharedPtr msg_mem_strat = ( + MessageMemoryStrategyT::create_default() + ) +) +{ + return rclcpp::detail::create_subscription< + MessageT, CallbackT, AllocatorT, SubscriptionT, MessageMemoryStrategyT>( + node, node, topic_name, qos, std::forward(callback), options, msg_mem_strat); +} + /// Create and return a subscription of the given MessageT type. /** * See \ref create_subscription(). @@ -166,6 +203,43 @@ create_subscription( std::forward(callback), options, msg_mem_strat); } +// TODO(christophebedard): remove after Makoa +/// Create and return a subscription of the given MessageT type. +/** + * \deprecated Subscription callbacks taking a std::shared_ptr to a non-const message are + * deprecated, use std::shared_ptr instead. + */ +template< + typename MessageT, + typename CallbackT, + typename AllocatorT = std::allocator, + typename SubscriptionT = rclcpp::Subscription, + typename MessageMemoryStrategyT = typename SubscriptionT::MessageMemoryStrategyType> +requires rclcpp::detail::deprecated_subscription_callback +[[deprecated( + "subscription callbacks taking a std::shared_ptr to a non-const message are deprecated, " + "use std::shared_ptr instead")]] +typename std::shared_ptr +create_subscription( + rclcpp::node_interfaces::NodeParametersInterface::SharedPtr & node_parameters, + rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr & node_topics, + const std::string & topic_name, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options = ( + rclcpp::SubscriptionOptionsWithAllocator() + ), + typename MessageMemoryStrategyT::SharedPtr msg_mem_strat = ( + MessageMemoryStrategyT::create_default() + ) +) +{ + return rclcpp::detail::create_subscription< + MessageT, CallbackT, AllocatorT, SubscriptionT, MessageMemoryStrategyT>( + node_parameters, node_topics, topic_name, qos, + std::forward(callback), options, msg_mem_strat); +} + } // namespace rclcpp #endif // RCLCPP__CREATE_SUBSCRIPTION_HPP_ diff --git a/rclcpp/include/rclcpp/detail/subscription_callback_type_helper.hpp b/rclcpp/include/rclcpp/detail/subscription_callback_type_helper.hpp index 0ebe6efd66..db7ba4b6d8 100644 --- a/rclcpp/include/rclcpp/detail/subscription_callback_type_helper.hpp +++ b/rclcpp/include/rclcpp/detail/subscription_callback_type_helper.hpp @@ -15,11 +15,14 @@ #ifndef RCLCPP__DETAIL__SUBSCRIPTION_CALLBACK_TYPE_HELPER_HPP_ #define RCLCPP__DETAIL__SUBSCRIPTION_CALLBACK_TYPE_HELPER_HPP_ +#include #include #include #include "rclcpp/function_traits.hpp" #include "rclcpp/message_info.hpp" +#include "rclcpp/serialized_message.hpp" +#include "rclcpp/type_adapter.hpp" namespace rclcpp { @@ -129,6 +132,7 @@ struct SubscriptionCallbackTypeHelper< std::function &, const rclcpp::MessageInfo &)>; }; +// TODO(christophebedard): remove everything below after Makoa template struct SubscriptionCallbackTypeHelper< MessageT, @@ -160,6 +164,69 @@ struct SubscriptionCallbackTypeHelper< std::function, const rclcpp::MessageInfo &)>; }; +/// Whether CallbackT is a deprecated subscription callback signature for MessageT. +/** + * Subscription callbacks taking a std::shared_ptr to a non-const message (MessageT, the ROS + * message type of a type adapter, or rclcpp::SerializedMessage), with or without + * rclcpp::MessageInfo, are deprecated in favor of the std::shared_ptr signatures. + * + * CallbackT must be supported by rclcpp::function_traits, see deprecated_subscription_callback. + */ +template +struct is_deprecated_subscription_callback +{ +private: + using callback_type = + typename SubscriptionCallbackTypeHelper>::callback_type; + using SubscribedType = typename rclcpp::TypeAdapter::custom_type; + using ROSMessageType = typename rclcpp::TypeAdapter::ros_message_type; + +public: + static constexpr bool value = + rclcpp::function_traits::same_arguments< + callback_type, + std::function)> + >::value || + rclcpp::function_traits::same_arguments< + callback_type, + std::function, const rclcpp::MessageInfo &)> + >::value || + rclcpp::function_traits::same_arguments< + callback_type, + std::function)> + >::value || + rclcpp::function_traits::same_arguments< + callback_type, + std::function, const rclcpp::MessageInfo &)> + >::value || + rclcpp::function_traits::same_arguments< + callback_type, + std::function)> + >::value || + rclcpp::function_traits::same_arguments< + callback_type, + std::function, const rclcpp::MessageInfo &)> + >::value; +}; + +/// Whether rclcpp::function_traits supports CallbackT. +template +concept function_traits_compatible = + std::is_function>::value || + std::is_bind_expression::value || + requires {&CallbackT::operator();}; + +/// Whether CallbackT is a deprecated subscription callback signature for MessageT. +/** + * This can be used to constrain overloads, since it does not instantiate + * is_deprecated_subscription_callback for types that are not supported by + * rclcpp::function_traits, which would be a hard error. + */ +template +concept deprecated_subscription_callback = + (function_traits_compatible>) && + is_deprecated_subscription_callback::value; + } // namespace detail } // namespace rclcpp diff --git a/rclcpp/include/rclcpp/node.hpp b/rclcpp/include/rclcpp/node.hpp index e8a1273c63..8a84b1a8c3 100644 --- a/rclcpp/include/rclcpp/node.hpp +++ b/rclcpp/include/rclcpp/node.hpp @@ -39,6 +39,7 @@ #include "rclcpp/client.hpp" #include "rclcpp/clock.hpp" #include "rclcpp/context.hpp" +#include "rclcpp/detail/subscription_callback_type_helper.hpp" #include "rclcpp/event.hpp" #include "rclcpp/generic_client.hpp" #include "rclcpp/generic_publisher.hpp" @@ -63,6 +64,7 @@ #include "rclcpp/publisher.hpp" #include "rclcpp/publisher_options.hpp" #include "rclcpp/qos.hpp" +#include "rclcpp/serialized_message.hpp" #include "rclcpp/service.hpp" #include "rclcpp/subscription.hpp" #include "rclcpp/subscription_options.hpp" @@ -227,6 +229,35 @@ class Node : public std::enable_shared_from_this ) ); + // TODO(christophebedard): remove after Makoa + /// Create and return a Subscription. + /** + * \deprecated Subscription callbacks taking a std::shared_ptr to a non-const message are + * deprecated, use std::shared_ptr instead. + */ + template< + typename MessageT, + typename CallbackT, + typename AllocatorT = std::allocator, + typename SubscriptionT = rclcpp::Subscription, + typename MessageMemoryStrategyT = typename SubscriptionT::MessageMemoryStrategyType + > + requires rclcpp::detail::deprecated_subscription_callback + [[deprecated( + "subscription callbacks taking a std::shared_ptr to a non-const message are deprecated, " + "use std::shared_ptr instead")]] + std::shared_ptr + create_subscription( + const std::string & topic_name, + const rclcpp::QoS & qos, + CallbackT && callback, + const SubscriptionOptionsWithAllocator & options = + SubscriptionOptionsWithAllocator(), + typename MessageMemoryStrategyT::SharedPtr msg_mem_strat = ( + MessageMemoryStrategyT::create_default() + ) + ); + /// Create a wall timer that uses the wall clock to drive the callback. /** * \param[in] period Time interval between triggers of the callback. @@ -370,6 +401,30 @@ class Node : public std::enable_shared_from_this ) ); + // TODO(christophebedard): remove after Makoa + /// Create and return a GenericSubscription. + /** + * \deprecated Subscription callbacks taking a std::shared_ptr to a non-const + * rclcpp::SerializedMessage are deprecated, use + * std::shared_ptr instead. + */ + template< + typename CallbackT, + typename AllocatorT = std::allocator> + requires rclcpp::detail::deprecated_subscription_callback + [[deprecated( + "subscription callbacks taking a std::shared_ptr to a non-const message are deprecated, " + "use std::shared_ptr instead")]] + std::shared_ptr create_generic_subscription( + const std::string & topic_name, + const std::string & topic_type, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options = ( + rclcpp::SubscriptionOptionsWithAllocator() + ) + ); + /// Declare and initialize a parameter, return the effective value. /** * This method is used to declare that a parameter exists on this node. diff --git a/rclcpp/include/rclcpp/node_impl.hpp b/rclcpp/include/rclcpp/node_impl.hpp index c699e7519e..674adb2efd 100644 --- a/rclcpp/include/rclcpp/node_impl.hpp +++ b/rclcpp/include/rclcpp/node_impl.hpp @@ -98,6 +98,32 @@ Node::create_subscription( msg_mem_strat); } +template< + typename MessageT, + typename CallbackT, + typename AllocatorT, + typename SubscriptionT, + typename MessageMemoryStrategyT> +requires rclcpp::detail::deprecated_subscription_callback +std::shared_ptr +Node::create_subscription( + const std::string & topic_name, + const rclcpp::QoS & qos, + CallbackT && callback, + const SubscriptionOptionsWithAllocator & options, + typename MessageMemoryStrategyT::SharedPtr msg_mem_strat) +{ + return rclcpp::detail::create_subscription< + MessageT, CallbackT, AllocatorT, SubscriptionT, MessageMemoryStrategyT>( + *this, + *this, + extend_name_with_sub_namespace(topic_name, this->get_sub_namespace()), + qos, + std::forward(callback), + options, + msg_mem_strat); +} + template typename rclcpp::WallTimer::SharedPtr Node::create_wall_timer( @@ -219,6 +245,26 @@ Node::create_generic_subscription( ); } +template +requires rclcpp::detail::deprecated_subscription_callback +std::shared_ptr +Node::create_generic_subscription( + const std::string & topic_name, + const std::string & topic_type, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options) +{ + return rclcpp::detail::create_generic_subscription( + node_topics_, + extend_name_with_sub_namespace(topic_name, this->get_sub_namespace()), + topic_type, + qos, + std::forward(callback), + options + ); +} + template auto diff --git a/rclcpp/test/rclcpp/test_any_subscription_callback.cpp b/rclcpp/test/rclcpp/test_any_subscription_callback.cpp index d83580fc7b..31f1cd3ee9 100644 --- a/rclcpp/test/rclcpp/test_any_subscription_callback.cpp +++ b/rclcpp/test/rclcpp/test_any_subscription_callback.cpp @@ -20,8 +20,9 @@ #include #include -#define RCLCPP_AVOID_DEPRECATIONS_FOR_UNIT_TESTS 1 #include "rclcpp/any_subscription_callback.hpp" +#include "rclcpp/detail/subscription_callback_type_helper.hpp" +#include "rclcpp/subscription_options.hpp" #include "test_msgs/msg/empty.hpp" // Type adapter to be used in tests. @@ -83,6 +84,64 @@ class TestAnySubscriptionCallbackTA : public ::testing::Test rclcpp::MessageInfo message_info_; }; +struct DeprecatedSubscriptionCallbackHelper +{ + void callback(const test_msgs::msg::Empty::SharedPtr) {} + void const_callback(const test_msgs::msg::Empty::ConstSharedPtr) {} +}; + +TEST(TestDeprecatedSubscriptionCallback, deprecated_subscription_callback) { + using rclcpp::detail::deprecated_subscription_callback; + using test_msgs::msg::Empty; + + // Deprecated: std::shared_ptr to a non-const message, with or without rclcpp::MessageInfo + auto shared_ptr = [](std::shared_ptr) {}; + auto shared_ptr_info = [](std::shared_ptr, const rclcpp::MessageInfo &) {}; + auto serialized = [](std::shared_ptr) {}; + auto serialized_info = + [](std::shared_ptr, const rclcpp::MessageInfo &) {}; + auto custom = [](std::shared_ptr) {}; + DeprecatedSubscriptionCallbackHelper helper; + auto bind = std::bind( + &DeprecatedSubscriptionCallbackHelper::callback, &helper, std::placeholders::_1); + static_assert(deprecated_subscription_callback); + static_assert(deprecated_subscription_callback); + static_assert(deprecated_subscription_callback); + static_assert(deprecated_subscription_callback); + static_assert(deprecated_subscription_callback); + static_assert(deprecated_subscription_callback); + static_assert(deprecated_subscription_callback), Empty>); + static_assert( + deprecated_subscription_callback)>, Empty>); + static_assert(deprecated_subscription_callback); + static_assert(deprecated_subscription_callback); + static_assert(deprecated_subscription_callback); + + // Not deprecated + auto const_shared_ptr = [](std::shared_ptr) {}; + auto const_shared_ptr_info = [](std::shared_ptr, const rclcpp::MessageInfo &) {}; + auto const_ref = [](const Empty &) {}; + auto unique_ptr = [](std::unique_ptr) {}; + auto const_ref_shared_const_ptr = [](const std::shared_ptr &) {}; + auto const_serialized = [](std::shared_ptr) {}; + auto const_custom = [](std::shared_ptr) {}; + auto const_bind = std::bind( + &DeprecatedSubscriptionCallbackHelper::const_callback, &helper, std::placeholders::_1); + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); + + // Not callable, e.g., when checking an overload that does not match the call + static_assert(!deprecated_subscription_callback); + static_assert(!deprecated_subscription_callback); +} + TEST_F(TestAnySubscriptionCallback, construct_destruct) { // Default constructor. rclcpp::AnySubscriptionCallback asc1; diff --git a/rclcpp/test/rclcpp/test_create_subscription.cpp b/rclcpp/test/rclcpp/test_create_subscription.cpp index d3f14a4ea3..35ecce9808 100644 --- a/rclcpp/test/rclcpp/test_create_subscription.cpp +++ b/rclcpp/test/rclcpp/test_create_subscription.cpp @@ -16,8 +16,10 @@ #include +#include "rclcpp/create_generic_subscription.hpp" #include "rclcpp/create_subscription.hpp" #include "rclcpp/node.hpp" +#include "rclcpp/serialized_message.hpp" #include "test_msgs/msg/empty.hpp" class TestCreateSubscription : public ::testing::Test @@ -89,3 +91,52 @@ TEST_F(TestCreateSubscription, create_with_intra_process_com) { ASSERT_NE(nullptr, subscription); EXPECT_STREQ("/ns/topic_name", subscription->get_topic_name()); } + +TEST_F(TestCreateSubscription, create_with_deprecated_callback) { + auto node = std::make_shared("my_node", "/ns"); + auto sub_node = node->create_sub_node("sub"); + const rclcpp::QoS qos(10); + auto options = rclcpp::SubscriptionOptions(); + auto callback = [](test_msgs::msg::Empty::SharedPtr) {}; + auto serialized_callback = [](std::shared_ptr) {}; + auto node_parameters = node->get_node_parameters_interface(); + auto node_topics = node->get_node_topics_interface(); + +#if !defined(_WIN32) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#else // !defined(_WIN32) +# pragma warning(push) +# pragma warning(disable: 4996) +#endif + auto node_subscription = + node->create_subscription("topic_name", qos, callback); + auto sub_node_subscription = + sub_node->create_subscription("topic_name", qos, callback); + auto subscription = + rclcpp::create_subscription(node, "topic_name", qos, callback, options); + auto separated_subscription = rclcpp::create_subscription( + node_parameters, node_topics, "topic_name", qos, callback, options); + auto node_generic_subscription = node->create_generic_subscription( + "generic_topic_name", "test_msgs/msg/Empty", qos, serialized_callback); + auto generic_subscription = rclcpp::create_generic_subscription( + node_topics, "generic_topic_name", "test_msgs/msg/Empty", qos, serialized_callback); +#if !defined(_WIN32) +# pragma GCC diagnostic pop +#else // !defined(_WIN32) +# pragma warning(pop) +#endif + + ASSERT_NE(nullptr, node_subscription); + EXPECT_STREQ("/ns/topic_name", node_subscription->get_topic_name()); + ASSERT_NE(nullptr, sub_node_subscription); + EXPECT_STREQ("/ns/sub/topic_name", sub_node_subscription->get_topic_name()); + ASSERT_NE(nullptr, subscription); + EXPECT_STREQ("/ns/topic_name", subscription->get_topic_name()); + ASSERT_NE(nullptr, separated_subscription); + EXPECT_STREQ("/ns/topic_name", separated_subscription->get_topic_name()); + ASSERT_NE(nullptr, node_generic_subscription); + EXPECT_STREQ("/ns/generic_topic_name", node_generic_subscription->get_topic_name()); + ASSERT_NE(nullptr, generic_subscription); + EXPECT_STREQ("/ns/generic_topic_name", generic_subscription->get_topic_name()); +} diff --git a/rclcpp_action/test/test_client.cpp b/rclcpp_action/test/test_client.cpp index c461d1eeed..88e0cf38f4 100644 --- a/rclcpp_action/test/test_client.cpp +++ b/rclcpp_action/test/test_client.cpp @@ -242,7 +242,7 @@ class TestClient : public ::testing::Test // to be executed. { auto subscription = client_node->create_subscription( - "test_topic", 10, [](const test_msgs::msg::Empty::SharedPtr) {}); + "test_topic", 10, [](const test_msgs::msg::Empty::ConstSharedPtr) {}); subscription_content_filter_supported_ = subscription->is_cft_supported(); } } diff --git a/rclcpp_action/test/test_generic_client.cpp b/rclcpp_action/test/test_generic_client.cpp index 0bca9acd0b..df3ccb2fa4 100644 --- a/rclcpp_action/test/test_generic_client.cpp +++ b/rclcpp_action/test/test_generic_client.cpp @@ -233,7 +233,7 @@ class TestGenericClient : public ::testing::Test // to be executed. { auto subscription = client_node->create_subscription( - "test_topic", 10, [](const test_msgs::msg::Empty::SharedPtr) {}); + "test_topic", 10, [](const test_msgs::msg::Empty::ConstSharedPtr) {}); subscription_content_filter_supported_ = subscription->is_cft_supported(); } } diff --git a/rclcpp_lifecycle/include/rclcpp_lifecycle/lifecycle_node.hpp b/rclcpp_lifecycle/include/rclcpp_lifecycle/lifecycle_node.hpp index 43ff0e3fa4..31036e89e3 100644 --- a/rclcpp_lifecycle/include/rclcpp_lifecycle/lifecycle_node.hpp +++ b/rclcpp_lifecycle/include/rclcpp_lifecycle/lifecycle_node.hpp @@ -56,6 +56,7 @@ #include "rclcpp/callback_group.hpp" #include "rclcpp/client.hpp" #include "rclcpp/clock.hpp" +#include "rclcpp/detail/subscription_callback_type_helper.hpp" #include "rclcpp/event.hpp" #include "rclcpp/generic_publisher.hpp" #include "rclcpp/generic_subscription.hpp" @@ -78,6 +79,7 @@ #include "rclcpp/publisher.hpp" #include "rclcpp/publisher_options.hpp" #include "rclcpp/qos.hpp" +#include "rclcpp/serialized_message.hpp" #include "rclcpp/service.hpp" #include "rclcpp/subscription.hpp" #include "rclcpp/subscription_options.hpp" @@ -254,6 +256,34 @@ class LifecycleNode : public node_interfaces::LifecycleNodeInterface, ) ); + // TODO(christophebedard): remove after Makoa + /// Create and return a Subscription. + /** + * \deprecated Subscription callbacks taking a std::shared_ptr to a non-const message are + * deprecated, use std::shared_ptr instead. + */ + template< + typename MessageT, + typename CallbackT, + typename AllocatorT = std::allocator, + typename SubscriptionT = rclcpp::Subscription, + typename MessageMemoryStrategyT = typename SubscriptionT::MessageMemoryStrategyType> + requires rclcpp::detail::deprecated_subscription_callback + [[deprecated( + "subscription callbacks taking a std::shared_ptr to a non-const message are deprecated, " + "use std::shared_ptr instead")]] + std::shared_ptr + create_subscription( + const std::string & topic_name, + const rclcpp::QoS & qos, + CallbackT && callback, + const SubscriptionOptionsWithAllocator & options = + create_default_subscription_options(), + typename MessageMemoryStrategyT::SharedPtr msg_mem_strat = ( + MessageMemoryStrategyT::create_default() + ) + ); + /// Create a timer that uses the wall clock to drive the callback. /** * \param[in] period Time interval between triggers of the callback. @@ -337,6 +367,30 @@ class LifecycleNode : public node_interfaces::LifecycleNodeInterface, ) ); + // TODO(christophebedard): remove after Makoa + /// Create and return a GenericSubscription. + /** + * \deprecated Subscription callbacks taking a std::shared_ptr to a non-const + * rclcpp::SerializedMessage are deprecated, use + * std::shared_ptr instead. + */ + template< + typename CallbackT, + typename AllocatorT = std::allocator> + requires rclcpp::detail::deprecated_subscription_callback + [[deprecated( + "subscription callbacks taking a std::shared_ptr to a non-const message are deprecated, " + "use std::shared_ptr instead")]] + std::shared_ptr create_generic_subscription( + const std::string & topic_name, + const std::string & topic_type, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options = ( + rclcpp::SubscriptionOptionsWithAllocator() + ) + ); + /// Declare and initialize a parameter, return the effective value. /** * \sa rclcpp::Node::declare_parameter diff --git a/rclcpp_lifecycle/include/rclcpp_lifecycle/lifecycle_node_impl.hpp b/rclcpp_lifecycle/include/rclcpp_lifecycle/lifecycle_node_impl.hpp index c2de16e3df..d489ec3a36 100644 --- a/rclcpp_lifecycle/include/rclcpp_lifecycle/lifecycle_node_impl.hpp +++ b/rclcpp_lifecycle/include/rclcpp_lifecycle/lifecycle_node_impl.hpp @@ -90,6 +90,32 @@ LifecycleNode::create_subscription( msg_mem_strat); } +template< + typename MessageT, + typename CallbackT, + typename AllocatorT, + typename SubscriptionT, + typename MessageMemoryStrategyT> +requires rclcpp::detail::deprecated_subscription_callback +std::shared_ptr +LifecycleNode::create_subscription( + const std::string & topic_name, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options, + typename MessageMemoryStrategyT::SharedPtr msg_mem_strat) +{ + return rclcpp::detail::create_subscription< + MessageT, CallbackT, AllocatorT, SubscriptionT, MessageMemoryStrategyT>( + *this, + *this, + topic_name, + qos, + std::forward(callback), + options, + msg_mem_strat); +} + template typename rclcpp::WallTimer::SharedPtr LifecycleNode::create_wall_timer( @@ -186,6 +212,28 @@ LifecycleNode::create_generic_subscription( ); } +template +requires rclcpp::detail::deprecated_subscription_callback +std::shared_ptr +LifecycleNode::create_generic_subscription( + const std::string & topic_name, + const std::string & topic_type, + const rclcpp::QoS & qos, + CallbackT && callback, + const rclcpp::SubscriptionOptionsWithAllocator & options) +{ + return rclcpp::detail::create_generic_subscription( + node_topics_, + // TODO(karsten1987): LifecycleNode is currently not supporting subnamespaces + // see https://github.com/ros2/rclcpp/issues/1614 + topic_name, + topic_type, + qos, + std::forward(callback), + options + ); +} + template auto LifecycleNode::declare_parameter( diff --git a/rclcpp_lifecycle/test/test_lifecycle_node.cpp b/rclcpp_lifecycle/test/test_lifecycle_node.cpp index c69219d965..331979bbc9 100644 --- a/rclcpp_lifecycle/test/test_lifecycle_node.cpp +++ b/rclcpp_lifecycle/test/test_lifecycle_node.cpp @@ -39,6 +39,7 @@ #include "rclcpp/node_options.hpp" #include "rclcpp/parameter.hpp" #include "rclcpp/parameter_value.hpp" +#include "rclcpp/serialized_message.hpp" #include "rclcpp/utilities.hpp" #include "rclcpp_lifecycle/lifecycle_node.hpp" @@ -652,6 +653,34 @@ TEST_F(TestDefaultStateMachine, lifecycle_subscriber) { SUCCEED(); } +TEST_F(TestDefaultStateMachine, lifecycle_subscriber_deprecated_callback) { + auto test_node = std::make_shared>("testnode"); + + auto cb = [](std::shared_ptr msg) {(void) msg;}; + auto generic_cb = [](std::shared_ptr msg) {(void) msg;}; +#if !defined(_WIN32) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#else // !defined(_WIN32) +# pragma warning(push) +# pragma warning(disable: 4996) +#endif + auto lifecycle_sub = + test_node->create_subscription("~/empty", 10, cb); + auto lifecycle_generic_sub = test_node->create_generic_subscription( + "~/empty_generic", "lifecycle_msgs/msg/State", 10, generic_cb); +#if !defined(_WIN32) +# pragma GCC diagnostic pop +#else // !defined(_WIN32) +# pragma warning(pop) +#endif + + ASSERT_NE(nullptr, lifecycle_sub); + EXPECT_STREQ("/testnode/empty", lifecycle_sub->get_topic_name()); + ASSERT_NE(nullptr, lifecycle_generic_sub); + EXPECT_STREQ("/testnode/empty_generic", lifecycle_generic_sub->get_topic_name()); +} + // Parameters are tested more thoroughly in rclcpp's test_node.cpp // These are provided for coverage of lifecycle node's API TEST_F(TestDefaultStateMachine, declare_parameters) { From 7a4be044239b0e4a08f1d7489976a291871e4b89 Mon Sep 17 00:00:00 2001 From: Christophe Bedard Date: Sun, 29 Nov 2026 06:05:17 -0800 Subject: [PATCH 15/18] Remove public _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS definition (#3457) https://github.com/ros2/rclcpp/pull/1598 defined it on Windows, along with new uses of `std::allocator`, whose explicit specialization was deprecated in C++17. Since it is public, it silences all of MSVC's C++17 deprecation warnings in every package that depends on `rclcpp`. C++20, which Rolling now uses, removed that specialization. Signed-off-by: Christophe Bedard --- rclcpp/CMakeLists.txt | 4 ---- 1 file changed, 4 deletions(-) diff --git a/rclcpp/CMakeLists.txt b/rclcpp/CMakeLists.txt index f4fb20dcbb..ae60b01bad 100644 --- a/rclcpp/CMakeLists.txt +++ b/rclcpp/CMakeLists.txt @@ -187,10 +187,6 @@ foreach(interface_file ${interface_files}) endforeach() add_library(${PROJECT_NAME} ${${PROJECT_NAME}_SRCS}) -# TODO(wjwwood): address all deprecation warnings and then remove this -if(WIN32) - target_compile_definitions(${PROJECT_NAME} PUBLIC "_SILENCE_ALL_CXX17_DEPRECATION_WARNINGS") -endif() target_include_directories(${PROJECT_NAME} PUBLIC "$" "$" From a1ef7f4d1e0f35ef5341297e4fb7713ffc2bd2cb Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Sun, 29 Nov 2026 16:26:40 -0600 Subject: [PATCH 16/18] Call the real fini function in tests that inject a fini error Tests that replaced rcl_service_fini(), rcl_client_fini(), rcl_network_flow_endpoint_array_fini(), rcutils_string_map_fini(), rcl_lifecycle_transition_fini() and rcl_wait_set_fini() with a function that only returns an error never released the object, which LeakSanitizer reports. Use inject_on_return(), like the surrounding tests already do, so the real function runs before the error is injected. Signed-off-by: Michael Carroll --- rclcpp/test/rclcpp/test_client.cpp | 2 +- rclcpp/test/rclcpp/test_expand_topic_or_service_name.cpp | 4 ++-- rclcpp/test/rclcpp/test_generic_client.cpp | 2 +- rclcpp/test/rclcpp/test_generic_service.cpp | 2 +- rclcpp/test/rclcpp/test_publisher.cpp | 4 ++-- rclcpp/test/rclcpp/test_service.cpp | 2 +- rclcpp/test/rclcpp/test_subscription.cpp | 4 ++-- rclcpp_lifecycle/test/test_transition_wrapper.cpp | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/rclcpp/test/rclcpp/test_client.cpp b/rclcpp/test/rclcpp/test_client.cpp index 0ff7449807..a7ab8dfb8a 100644 --- a/rclcpp/test/rclcpp/test_client.cpp +++ b/rclcpp/test/rclcpp/test_client.cpp @@ -139,7 +139,7 @@ TEST_F(TestClient, construct_with_rcl_error) { } { // reset() is required for this one - auto mock = mocking_utils::patch_and_return("lib:rclcpp", rcl_client_fini, RCL_RET_ERROR); + auto mock = mocking_utils::inject_on_return("lib:rclcpp", rcl_client_fini, RCL_RET_ERROR); EXPECT_NO_THROW(node->create_client("service").reset()); } } diff --git a/rclcpp/test/rclcpp/test_expand_topic_or_service_name.cpp b/rclcpp/test/rclcpp/test_expand_topic_or_service_name.cpp index 841aa8fd1c..51595203d8 100644 --- a/rclcpp/test/rclcpp/test_expand_topic_or_service_name.cpp +++ b/rclcpp/test/rclcpp/test_expand_topic_or_service_name.cpp @@ -123,7 +123,7 @@ TEST(TestExpandTopicOrServiceName, rcl_get_default_topic_name_substitution_fail) TEST(TestExpandTopicOrServiceName, rcl_get_default_topic_name_substitution_and_map_fini_fail) { auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_get_default_topic_name_substitutions, RCL_RET_ERROR); - auto mock2 = mocking_utils::patch_and_return( + auto mock2 = mocking_utils::inject_on_return( "lib:rclcpp", rcutils_string_map_fini, RCUTILS_RET_ERROR); RCLCPP_EXPECT_THROW_EQ( rclcpp::expand_topic_or_service_name("chatter", "node", "/ns"), @@ -131,7 +131,7 @@ TEST(TestExpandTopicOrServiceName, rcl_get_default_topic_name_substitution_and_m } TEST(TestExpandTopicOrServiceName, rcutils_string_map_fini_fail_bad_alloc) { - auto mock = mocking_utils::patch_and_return( + auto mock = mocking_utils::inject_on_return( "lib:rclcpp", rcutils_string_map_fini, RCUTILS_RET_ERROR); RCLCPP_EXPECT_THROW_EQ( rclcpp::expand_topic_or_service_name("chatter", "node", "/ns"), diff --git a/rclcpp/test/rclcpp/test_generic_client.cpp b/rclcpp/test/rclcpp/test_generic_client.cpp index c19a508b41..89bbc45e84 100644 --- a/rclcpp/test/rclcpp/test_generic_client.cpp +++ b/rclcpp/test/rclcpp/test_generic_client.cpp @@ -207,7 +207,7 @@ TEST_F(TestGenericClient, construct_with_rcl_error) { } { // reset() is required for this one - auto mock = mocking_utils::patch_and_return("lib:rclcpp", rcl_client_fini, RCL_RET_ERROR); + auto mock = mocking_utils::inject_on_return("lib:rclcpp", rcl_client_fini, RCL_RET_ERROR); EXPECT_NO_THROW( node->create_generic_client("test_service", "test_msgs/srv/Empty").reset()); } diff --git a/rclcpp/test/rclcpp/test_generic_service.cpp b/rclcpp/test/rclcpp/test_generic_service.cpp index 081db56edd..6b701f38df 100644 --- a/rclcpp/test/rclcpp/test_generic_service.cpp +++ b/rclcpp/test/rclcpp/test_generic_service.cpp @@ -221,7 +221,7 @@ TEST_F(TestGenericService, construction_and_destruction_rcl_errors) { } { // reset() is required for this one - auto mock = mocking_utils::patch_and_return("lib:rclcpp", rcl_service_fini, RCL_RET_ERROR); + auto mock = mocking_utils::inject_on_return("lib:rclcpp", rcl_service_fini, RCL_RET_ERROR); EXPECT_NO_THROW( node->create_generic_service("service", "test_msgs/srv/Empty", callback).reset()); } diff --git a/rclcpp/test/rclcpp/test_publisher.cpp b/rclcpp/test/rclcpp/test_publisher.cpp index dd20e724e9..21a1ea258d 100644 --- a/rclcpp/test/rclcpp/test_publisher.cpp +++ b/rclcpp/test/rclcpp/test_publisher.cpp @@ -582,14 +582,14 @@ TEST_F(TestPublisher, get_network_flow_endpoints_errors) { { auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_publisher_get_network_flow_endpoints, RCL_RET_ERROR); - auto mock_network_flow_endpoint_array_fini = mocking_utils::patch_and_return( + auto mock_network_flow_endpoint_array_fini = mocking_utils::inject_on_return( "lib:rclcpp", rcl_network_flow_endpoint_array_fini, RCL_RET_ERROR); EXPECT_THROW( publisher->get_network_flow_endpoints(), rclcpp::exceptions::RCLError); } { - auto mock_network_flow_endpoint_array_fini = mocking_utils::patch_and_return( + auto mock_network_flow_endpoint_array_fini = mocking_utils::inject_on_return( "lib:rclcpp", rcl_network_flow_endpoint_array_fini, RCL_RET_ERROR); EXPECT_THROW( publisher->get_network_flow_endpoints(), diff --git a/rclcpp/test/rclcpp/test_service.cpp b/rclcpp/test/rclcpp/test_service.cpp index b8f57bb806..11f5f25dad 100644 --- a/rclcpp/test/rclcpp/test_service.cpp +++ b/rclcpp/test/rclcpp/test_service.cpp @@ -154,7 +154,7 @@ TEST_F(TestService, construction_and_destruction_rcl_errors) { } { // reset() is required for this one - auto mock = mocking_utils::patch_and_return("lib:rclcpp", rcl_service_fini, RCL_RET_ERROR); + auto mock = mocking_utils::inject_on_return("lib:rclcpp", rcl_service_fini, RCL_RET_ERROR); EXPECT_NO_THROW(node->create_service("service", callback).reset()); } } diff --git a/rclcpp/test/rclcpp/test_subscription.cpp b/rclcpp/test/rclcpp/test_subscription.cpp index b90db762ff..2f78b81802 100644 --- a/rclcpp/test/rclcpp/test_subscription.cpp +++ b/rclcpp/test/rclcpp/test_subscription.cpp @@ -515,14 +515,14 @@ TEST_F(TestSubscription, get_network_flow_endpoints_errors) { { auto mock = mocking_utils::patch_and_return( "lib:rclcpp", rcl_subscription_get_network_flow_endpoints, RCL_RET_ERROR); - auto mock_network_flow_endpoint_array_fini = mocking_utils::patch_and_return( + auto mock_network_flow_endpoint_array_fini = mocking_utils::inject_on_return( "lib:rclcpp", rcl_network_flow_endpoint_array_fini, RCL_RET_ERROR); EXPECT_THROW( subscription->get_network_flow_endpoints(), rclcpp::exceptions::RCLError); } { - auto mock_network_flow_endpoint_array_fini = mocking_utils::patch_and_return( + auto mock_network_flow_endpoint_array_fini = mocking_utils::inject_on_return( "lib:rclcpp", rcl_network_flow_endpoint_array_fini, RCL_RET_ERROR); EXPECT_THROW( subscription->get_network_flow_endpoints(), diff --git a/rclcpp_lifecycle/test/test_transition_wrapper.cpp b/rclcpp_lifecycle/test/test_transition_wrapper.cpp index 39791d5da2..e19c6a826f 100644 --- a/rclcpp_lifecycle/test/test_transition_wrapper.cpp +++ b/rclcpp_lifecycle/test/test_transition_wrapper.cpp @@ -151,7 +151,7 @@ TEST_F(TestTransitionWrapper, exceptions) { std::runtime_error); } { - auto mock = mocking_utils::patch_and_return( + auto mock = mocking_utils::inject_on_return( "lib:rclcpp_lifecycle", rcl_lifecycle_transition_fini, RCL_RET_ERROR); auto transition1 = std::make_shared(1, "one"); EXPECT_NO_THROW(transition1->expose_reset()); From edb721b04f671c143157b858eb8fb2c4832024eb Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Mon, 30 Nov 2026 07:32:42 -0600 Subject: [PATCH 17/18] Wrap the introspection clock comment to 100 columns Signed-off-by: Michael Carroll --- rclcpp/include/rclcpp/service.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rclcpp/include/rclcpp/service.hpp b/rclcpp/include/rclcpp/service.hpp index 909d10fc6a..0296ae85c3 100644 --- a/rclcpp/include/rclcpp/service.hpp +++ b/rclcpp/include/rclcpp/service.hpp @@ -213,7 +213,8 @@ class ServiceBase std::shared_ptr node_handle_; // The introspection publisher keeps a raw pointer to this clock's rcl handle and uses it while - // finalizing the service. Keep the clock alive until service_handle_ (declared below) is finalized. + // finalizing the service. Keep the clock alive until service_handle_ (declared below) is + // finalized. rclcpp::Clock::SharedPtr introspection_clock_; std::recursive_mutex callback_mutex_; From 7551fc9a27a74ca3a87c2fc1ff1c8c423c1e925e Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Mon, 30 Nov 2026 07:34:24 -0600 Subject: [PATCH 18/18] Keep patch_and_return for rcl_action_client_fini; inject_on_return crashes on RHEL Signed-off-by: Michael Carroll --- rclcpp_action/test/test_client.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rclcpp_action/test/test_client.cpp b/rclcpp_action/test/test_client.cpp index 627fd6108e..54b9426b31 100644 --- a/rclcpp_action/test/test_client.cpp +++ b/rclcpp_action/test/test_client.cpp @@ -391,7 +391,7 @@ TEST_F(TestClient, construction_and_destruction_callback_group) TEST_F(TestClient, construction_and_destruction_rcl_errors) { { - auto mock = mocking_utils::inject_on_return( + auto mock = mocking_utils::patch_and_return( "lib:rclcpp_action", rcl_action_client_fini, RCL_RET_ERROR); // It just logs an error message and continues EXPECT_NO_THROW(