Skip to content

Spinning node does not also spin sub nodes #1778

Closed

Description

@jlack1987

Bug report

I'm assuming this is a bug so i'm filing as so but if this is intended behavior then perhaps this is a feature request.
Required Info:

  • Operating System:
    • Ubuntu 20.04
  • Installation type:
    • binaries
  • Version or commit hash:
    • foxy
  • DDS implementation:
    • whatever is default
  • Client library (if applicable):
    • rclcpp

Steps to reproduce issue

Here's some test code i've been playing with. It's nothing great but it should show the behavior. With this what I expect is for each sub node to have its own topics/services/params namespaced by the name of the sub node but that's not what happens.

#include <chrono>
#include <string>

#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/int32.hpp>
#include <std_srvs/srv/trigger.hpp>

using namespace std::chrono_literals;

class IDoRosStuff
{
  public:
    IDoRosStuff(const rclcpp::Node::SharedPtr& node) : n(node), i(0)
    {
    }

    void init()
    {
        pub_a = n->create_publisher<std_msgs::msg::Int32>("~/a", rclcpp::SystemDefaultsQoS());
        pub_b = n->create_publisher<std_msgs::msg::Int32>("~/b", rclcpp::SystemDefaultsQoS());

        srv_a = n->create_service<std_srvs::srv::Trigger>("~/a", std::bind(&IDoRosStuff::serviceACb, this, std::placeholders::_1, std::placeholders::_2));
        srv_b = n->create_service<std_srvs::srv::Trigger>("~/b", std::bind(&IDoRosStuff::serviceBCb, this, std::placeholders::_1, std::placeholders::_2));
    }

    void run()
    {
        std_msgs::msg::Int32 msg;
        msg.data = i;
        pub_a->publish(msg);
        pub_b->publish(msg);
        i++;
    }

    rclcpp::Parameter param_a, param_b, param_c;
    rclcpp::Publisher<std_msgs::msg::Int32>::SharedPtr pub_a, pub_b;
    rclcpp::Service<std_srvs::srv::Trigger>::SharedPtr srv_a, srv_b;
    rclcpp::Node::SharedPtr n;
    unsigned int i;

    void serviceACb(const std::shared_ptr<std_srvs::srv::Trigger::Request> req, std::shared_ptr<std_srvs::srv::Trigger::Response> resp)
    {
        (void)req;
        (void)resp;
        param_a = n->get_parameter("a");
        std::cout << "param_a: " << param_a << std::endl;
    }

    void serviceBCb(const std::shared_ptr<std_srvs::srv::Trigger::Request> req, std::shared_ptr<std_srvs::srv::Trigger::Response> resp)
    {
        (void)req;
        (void)resp;
        param_b = n->get_parameter("b");
        std::cout << "param_b: " << param_b << std::endl;
    }
};

int main(int argc, char* argv[])
{
    rclcpp::init(argc, argv);
    rclcpp::NodeOptions options;
    options.allow_undeclared_parameters(true);
    options.automatically_declare_parameters_from_overrides(true);
    rclcpp::Node::SharedPtr node = rclcpp::Node::make_shared("top_level", "top_level", options);

    std::vector<std::string> sub_node_names = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
    std::vector<std::shared_ptr<IDoRosStuff>> my_classes;
    double iter = 0.;
    for (const std::string& name : sub_node_names)
    {
        // create sub nodes
        rclcpp::Node::SharedPtr n = node->create_sub_node(name);
        // set sub nodes parameters
        n->set_parameter({ "a", 0. * iter });
        n->set_parameter({ "b", 1. * iter });
        n->set_parameter({ "c", 2. * iter });
        iter += 1.;

        std::shared_ptr<IDoRosStuff> a_class(new IDoRosStuff(n));
        a_class->init();
        my_classes.push_back(a_class);
    }

    rclcpp::WallRate loop_rate(500ms);

    while (rclcpp::ok())
    {
        try
        {
            for (std::shared_ptr<IDoRosStuff> ptr : my_classes)
            {
                ptr->run();
            }

            rclcpp::spin_some(node);
        }
        catch (const rclcpp::exceptions::RCLError& e)
        {
            RCLCPP_ERROR(node->get_logger(), "unexpectedly failed with %s", e.what());
        }
        loop_rate.sleep();
    }
    rclcpp::shutdown();
    return 0;
}

Expected behavior

I expected spinning the top level node would also spin the subordinate nodes

Actual behavior

Unless the subordinate nodes are spun individually they do not get spun

Activity

  1. jlack1987 commented on Sep 16, 2021

    @jlack1987
    Author

    Ultimately the use case that i'm trying to understand how to handle is that i'm converting a relatively large chunk of code from ros1 to ros2, and it involves lots of classes who own classes who own classes and so on and so on. In ros1, each of these classes had their own node handles which extended the namespace where they all could put their topics/services/params.

    From the main thread I could simply init the node, create the top level class(or pointer to it), give it the top level nodehandle, and send it on its way ticking periodically and the main thread would periodically call ros::spinOnce() at whatever rate I want ros stuff to happen.

    In attempting to recreate this type of behavior in ros2 it seemed like sub nodes were the way to go and each node could pass a sub node down the branch of classes. But I then found that i'd still have to spin each sub node separately which would mean hundreds of execution threads bc I can't spin nodes from my main RT thread. I then found the Executors but attempting to add sub nodes to an executor results in,

    terminate called after throwing an instance of 'std::runtime_error'
      what():  Node has already been added to an executor.
    

    So the only thing I can think of is to have every class manually create a new non-subordinate node and pass a pointer to an executor around and things can add their nodes to that and have the top level spin the executor. I hope this makes sense and please let me know if I have something incorrect

  2. fujitatomoya commented on Sep 20, 2021

    @fujitatomoya
    Collaborator

    as far as i know, subordinate nodes use shared object from main rclcpp::Node. So when main rclcpp::Node spins, that means subordinate nodes spin. i confirmed with your sample program with ros2 topic info -v, ros2 topic echo and ros2 service call.

    terminate called after throwing an instance of 'std::runtime_error'
    what(): Node has already been added to an executor.

    this is expected because subordinate nodes are on the same executor with main rclcpp::Node.

  3. added
    more-information-needed
    on Sep 20, 2021
  4. jlack1987 commented on Sep 20, 2021

    @jlack1987
    Author

    Ok, I guess then I don't understand what's going on in my example then. When I run it I see,

    ✘  16:24 ~/nautilus_ws # ros2 topic list
    /parameter_events
    /rosout
    /top_level/top_level/a
    /top_level/top_level/b
    

    but I am expecting to see

    /top_level/one/a
    /top_level/one/b
    /top_level/two/a
    /top_level/two/b
      .
      .
      .
    /top_level/ten/a
    /top_level/ten/b
    

    Are you saying when you run it you see all of the topics?

  5. fujitatomoya commented on Sep 20, 2021

    @fujitatomoya
    Collaborator

    Are you saying when you run it you see all of the topics?

    No, i did not mean that. I don't see those topics either. Just saying that sub-nodes are spinning when main node spins. but i understand what you mean. i am not sure original design about the subordinate nodes. any help?

  6. added
    question
    and removed
    more-information-needed
    on Sep 20, 2021
  7. aprotyas commented on Sep 20, 2021

    @aprotyas
    Member

    From #731:

    Currently how parameters and "sub-nodes" interact is not documented and is not consistent or tested. That needs to be documented, audited, and tested.
    Looks like there's some WIP but that issue is also old, so I'm not sure if things changed in between.

    I agree that the expected behavior should be for sub-nodes to also spin, but I don't find it documented anywhere in rclcpp::Node::create_sub_node or rclcpp::Executor::spin_some.

    Also, it looks like the spin_some function only adds the passed-in node (and not any of it's sub-nodes) to an executor.

    void
    Executor::spin_node_some(rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node)
    {
    this->add_node(node, false);
    spin_some();
    this->remove_node(node, false);
    }

  8. fujitatomoya commented on Sep 20, 2021

    @fujitatomoya
    Collaborator

    @aprotyas nice catch for #731 ❗ thanks!

    I agree that the expected behavior should be for sub-nodes to also spin

    they do.

    but I don't find it documented anywhere

    👍 for adding document.

    Also, it looks like the spin_some function only adds the passed-in node (and not any of it's sub-nodes) to an executor.

    i think passed-in node is also sub-node. so that i can spin and take events to execute.

    i guess that we might want to change the subject like it does not extend the namespace of all entities created with subordinate node.?

  9. aprotyas commented on Sep 20, 2021

    @aprotyas
    Member

    i think passed-in node is also sub-node. so that i can spin and take events to execute.

    I didn't understand that. Say, from the example code provided by @jlack1987, when rclcpp::spin_some(node); is executed, does it also add the sub-nodes to the executor?

  10. fujitatomoya commented on Sep 20, 2021

    @fujitatomoya
    Collaborator

    I didn't understand that. Say, from the example code provided by @jlack1987, when rclcpp::spin_some(node); is executed, does it also add the sub-nodes to the executor?

    yes, it takes events(in this sample service request and send response) and publish messages. you can see service servers are responding (also logging messages) for each sub-nodes once you actually send the requests.

  11. aprotyas commented on Sep 21, 2021

    @aprotyas
    Member

    yes, it takes events(in this sample service request and send response) and publish messages. you can see service servers are responding (also logging messages) for each sub-nodes once you actually send the requests.

    Understood!


    In conclusion, it looks like (quoting @fujitatomoya):

    i guess that we might want to change the subject like it does not extend the namespace of all entities created with subordinate node.?

    @jlack1987 if you agree with the assessment above, I think the behavior exhibited by rclcpp is clarified, and we can close this issue. I will probably submit a PR with some documentation about said spinning behavior.

  12. jlack1987 commented on Sep 21, 2021

    @jlack1987
    Author

    @aprotyas i'm still not sure I understand. It's still not clear to me why from my example that I don't see the topics from all the sub nodes as I mentioned here.

    It sounds like you all are saying that it does indeed spin the subordinate nodes which is good and in that case I guess my issue is with some other behavior that I haven't yet been able to describe accurately. I'm expecting those topics/services to show up under the sub nodes but they do not. Also if I need to close this one and open a new one with the actual issue better described I can do that as well once I understand what it is 😆

  13. aprotyas commented on Sep 21, 2021

    @aprotyas
    Member

    @jlack1987 I believe the crux of the issue is captured by #731 (comment) - quoted below:

    So, is this ticket basically tracking that sub nodes do not actually use the sub_namespace in the name of the parameter? For example:

    auto subnode = parent->create_sub_node("controller_name");
    std::string controller_type = subnode->declare_parameter<std::string>("type", "");
    

    I would expect the parameter to be "controller_name/type", but instead "ros2 param list" shows only a parameter named "type"? Is this expected behavior? Is this a bug?

    Essentially, sub-nodes do indeed get added to the executor, and they are spinning - so this part matches all of our expected behavior. The behavior that is not consistent with our expectation is that sub-namespaces are not propagated for entities that belong to/were created by the sub-node. That is an acknowledged bug in #731, but I'm not sure if any progress has been made on that front.

  14. jlack1987 commented on Sep 21, 2021

    @jlack1987
    Author

    oooh ok I see what you mean. Thanks for the clarification. In that case yeah i'll go ahead and close this out and keep an eye on that issue

  15. aprotyas commented on Sep 21, 2021

    @aprotyas
    Member

    I'd encourage you to contribute a fix if you're interested and have the time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions