Skip to content

Commit

Permalink
Close the Zenoh session after destroying the last node
Browse files Browse the repository at this point in the history
Signed-off-by: Yadunund <[email protected]>
  • Loading branch information
Yadunund committed Sep 19, 2024
1 parent 09c5cbc commit 3ac3ec2
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
7 changes: 7 additions & 0 deletions rmw_zenoh_cpp/src/detail/rmw_data_types.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <optional>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <variant>
#include <vector>
Expand Down Expand Up @@ -52,6 +53,12 @@ class rmw_context_impl_s final
// An owned session.
z_owned_session_t session;

// This is a temporary workaround for the unsoundness of rmw_shutdown
// reported in https://github.com/ros2/rmw_zenoh/issues/170.
// We keep track of all the nodes created in this session and only close
// the Zenoh session once the last node is destroyed.
std::unordered_set<const rmw_node_t *> session_nodes_;

std::optional<z_owned_shm_provider_t> shm_provider;

z_owned_subscriber_t graph_subscriber;
Expand Down
5 changes: 0 additions & 5 deletions rmw_zenoh_cpp/src/rmw_init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -412,11 +412,6 @@ rmw_shutdown(rmw_context_t * context)
if (context->impl->shm_provider.has_value()) {
z_drop(z_move(context->impl->shm_provider.value()));
}
// Close the zenoh session
if (z_close(z_move(context->impl->session), NULL) != Z_OK) {
RMW_SET_ERROR_MSG("Error while closing zenoh session");
return RMW_RET_ERROR;
}

context->impl->is_shutdown = true;

Expand Down
14 changes: 14 additions & 0 deletions rmw_zenoh_cpp/src/rmw_zenoh.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,9 @@ rmw_create_node(
node->context = context;
node->data = node_data;

// Add this node to the set of session_nodes.
context->impl->session_nodes_.insert(node);

free_token.cancel();
free_node_data.cancel();
destruct_node_data.cancel();
Expand Down Expand Up @@ -320,6 +323,17 @@ rmw_destroy_node(rmw_node_t * node)
allocator->deallocate(node_data, allocator->state);
}

// Erase the node from the set of session_nodes and close the Zenoh
// session if this is the last node.
node->context->impl->session_nodes_.erase(node);
if (node->context->impl->session_nodes_.empty()) {
// Close the zenoh session
if (z_close(z_move(node->context->impl->session), NULL) != Z_OK) {
RMW_SET_ERROR_MSG("Error while closing zenoh session");
return RMW_RET_ERROR;
}
}

allocator->deallocate(const_cast<char *>(node->namespace_), allocator->state);
allocator->deallocate(const_cast<char *>(node->name), allocator->state);
allocator->deallocate(node, allocator->state);
Expand Down

0 comments on commit 3ac3ec2

Please sign in to comment.