From 52f9fc376f9c3de49b4f53bdf201f801d6878fce Mon Sep 17 00:00:00 2001 From: linbo <1034003879@qq.com> Date: Thu, 12 Nov 2026 10:24:11 +0800 Subject: [PATCH] fix(shutdown): bound RPC shutdown and unblock motor status readers Cancel persistent gRPC streams after a 500 ms grace period and serialize server lifecycle operations without holding the status mutex during shutdown. Snapshot motors before disabling drives so acknowledgement waits do not hold the registry lock. On unhealthy EtherCAT transport, queue a best-effort TCHL disable and return an unconfirmed result without waiting for stale feedback. Add hardware-free regressions for open client streams, immediate/repeated server shutdown, and status reads during a stalled drive acknowledgement. Keep all device entries disabled in version control. --- .../src/vendor/tchl/tchl_motor_adapter.cpp | 7 ++ .../motor/manager/src/motor_manager.cpp | 8 +- .../src/motor_manager_shutdown_test.cpp | 39 ++++++++++ cmvr-es/service/CMakeLists.txt | 6 ++ .../service/grpc/tests/grpc_shutdown_test.cpp | 78 +++++++++++++++++++ .../include/grpc_server_task.h | 1 + .../grpc_server_task/src/grpc_server_task.cpp | 22 ++++-- 7 files changed, 154 insertions(+), 7 deletions(-) create mode 100644 cmvr-es/service/grpc/tests/grpc_shutdown_test.cpp diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_adapter.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_adapter.cpp index 36ff9ab7..0129b1b0 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_adapter.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/tchl/tchl_motor_adapter.cpp @@ -304,6 +304,13 @@ bool TchlMotorAdapter::torqueOff( if (!bus_runtime_ || counts_per_joint_revolution <= 0) { return false; } + if (!bus_runtime_->isHealthy()) { + // Feedback is stale after power/link loss. Queue a best-effort voltage + // disable, but do not wait for state transitions or mailbox replies. + bus_runtime_->writePdo( + node_id, msgs::CIA402_CONTROL_WORD_6040, 0x00, 0); + return false; + } const bool targets_written = writeSafeTargets_(node_id); const bool stopped = targets_written && waitVelocityNearZero_(node_id, counts_per_joint_revolution); diff --git a/cmvr-es/devices/motor/manager/src/motor_manager.cpp b/cmvr-es/devices/motor/manager/src/motor_manager.cpp index 5813123f..283ec85e 100644 --- a/cmvr-es/devices/motor/manager/src/motor_manager.cpp +++ b/cmvr-es/devices/motor/manager/src/motor_manager.cpp @@ -205,9 +205,15 @@ bool MotorManager::init() bool MotorManager::stop() { bool success = true; + std::vector>> motors; { std::lock_guard lock(motors_mutex_); - for (const auto& [joint_name, motor] : motors_by_joint_) { + motors.assign(motors_by_joint_.begin(), motors_by_joint_.end()); + } + // Drive acknowledgements can time out after a power loss. Do not block + // status readers or motor callbacks on the registry lock while waiting. + { + for (const auto& [joint_name, motor] : motors) { if (!motor) continue; try { if (!motor->torqueOff()) { diff --git a/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp b/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp index bf042f52..b2c4b0a2 100644 --- a/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp +++ b/cmvr-es/devices/motor/manager/src/motor_manager_shutdown_test.cpp @@ -83,3 +83,42 @@ TEST(MotorManagerShutdown, LingkongDisabledOrMissingMotorNeverAbortsGroupStop) { } } } + +#include +#include +namespace { +class WaitingShutdownMotor final : public AbstractMotor { +public: + std::promise entered; + std::shared_future release; + explicit WaitingShutdownMotor(std::shared_future ready) : release(std::move(ready)) { + node_id_ = 42; info_.id = 42; info_.joint_name = "waiting_shutdown_joint"; + } + std::string typeName() const override { return "WaitingShutdownMotor"; } + bool setLimitQ(double, double) override { return true; } + bool setLimitQd(double) override { return true; } + bool brakeRelease() override { return true; } + bool calibrateZeroQ() override { return true; } + bool torqueOff() override { + entered.set_value(); + release.wait(); // Simulate waiting for an unpowered drive's reply. + return false; + } +}; +TEST(MotorManagerShutdown, StatusReaderIsNotBlockedByDriveAcknowledgement) { + MotorManager manager("waiting_shutdown", config::MotorConfig{}, "test"); + std::promise release; + auto motor = std::make_shared(release.get_future().share()); + ASSERT_TRUE(manager.addMotor(motor)); + auto entered = motor->entered.get_future(); + auto stopped = std::async(std::launch::async, [&] { return manager.stop(); }); + const auto reached = entered.wait_for(std::chrono::seconds(2)); + auto reader = std::async(std::launch::async, [&] { return manager.getMotor(std::uint8_t{42}); }); + const auto readable = reader.wait_for(std::chrono::milliseconds(200)); + release.set_value(); // Always release before assertions and future destruction. + EXPECT_EQ(reached, std::future_status::ready); + EXPECT_EQ(readable, std::future_status::ready); + EXPECT_EQ(reader.get(), motor); + EXPECT_FALSE(stopped.get()); +} +} // namespace diff --git a/cmvr-es/service/CMakeLists.txt b/cmvr-es/service/CMakeLists.txt index b069fdb6..7ab97be4 100644 --- a/cmvr-es/service/CMakeLists.txt +++ b/cmvr-es/service/CMakeLists.txt @@ -34,7 +34,13 @@ target_link_libraries(service PRIVATE add_library(cmvr_es::service ALIAS service) install(TARGETS service LIBRARY DESTINATION lib) +add_executable(grpc_shutdown_test grpc/tests/grpc_shutdown_test.cpp) +target_include_directories(grpc_shutdown_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es/manager/device_manager) +target_link_libraries(grpc_shutdown_test PRIVATE cmvr_es::service gtest gtest_main pthread) + if(BUILD_TESTING) + add_test(NAME grpc_shutdown_test COMMAND grpc_shutdown_test) + set_tests_properties(grpc_shutdown_test PROPERTIES TIMEOUT 20) add_executable(motor_service_test grpc/tests/motor_service_test.cpp) target_include_directories(motor_service_test PRIVATE ${CMAKE_SOURCE_DIR}/cmvr-es/manager/device_manager) target_link_libraries(motor_service_test PRIVATE cmvr_es::service cmvr_es::device::motor_manager gtest gtest_main pthread) diff --git a/cmvr-es/service/grpc/tests/grpc_shutdown_test.cpp b/cmvr-es/service/grpc/tests/grpc_shutdown_test.cpp new file mode 100644 index 00000000..02493824 --- /dev/null +++ b/cmvr-es/service/grpc/tests/grpc_shutdown_test.cpp @@ -0,0 +1,78 @@ +#include "task/grpc_server_task/include/grpc_server_task.h" +#include "cmvr/api/biohead_service.grpc.pb.h" +#include "manager/device_manager/include/device_manager.h" + +#include +#include +#include +#include +#include +#include + +class GrpcShutdown : public ::testing::Test { +protected: + void SetUp() override { + cmvr::config::DeviceManagerConfig cfg; + cfg.set_name("shutdown_test_no_hardware"); + cmvr::device::DeviceManager::getInstance(cfg); + } + void TearDown() override { + cmvr::device::DeviceManager::destroyInstance(); + } +}; + +TEST_F(GrpcShutdown, CancelsIdleClientStreamBeforeClientDeadline) +{ + // Reserve an ephemeral loopback port without touching a deployed server. + const int fd = socket(AF_INET, SOCK_STREAM, 0); + ASSERT_GE(fd, 0); + sockaddr_in address{}; + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + const int bound = bind(fd, reinterpret_cast(&address), sizeof(address)); + socklen_t length = sizeof(address); + const int named = getsockname(fd, reinterpret_cast(&address), &length); + close(fd); + ASSERT_EQ(bound, 0); + ASSERT_EQ(named, 0); + + cmvr::config::GRPCServerConfig cfg; + cfg.set_id("shutdown_test"); + cfg.set_host("127.0.0.1"); + cfg.set_port(std::to_string(ntohs(address.sin_port))); + cmvr::task::GrpcServerTask task(cfg); + ASSERT_TRUE(task.init()); + ASSERT_TRUE(task.start()); + + auto channel = grpc::CreateChannel(task.address(), grpc::InsecureChannelCredentials()); + ASSERT_TRUE(channel->WaitForConnected(std::chrono::system_clock::now() + std::chrono::seconds(2))); + auto stub = cmvr::api::BioHeadService::NewStub(channel); + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(6)); + auto stream = stub->StreamExpression(&context); + // Send no command: the server stays in Read(), with no hardware accessed. + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + const auto start = std::chrono::steady_clock::now(); + task.stop(); + EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2)); + EXPECT_TRUE(task.isFinished()); + const auto status = stream->Finish(); + EXPECT_FALSE(status.ok()); + task.stop(); // Repeated stop must remain safe. +} + +TEST_F(GrpcShutdown, ImmediateAndRepeatedStopJoinsWaitThread) +{ + cmvr::config::GRPCServerConfig cfg; + cfg.set_id("immediate_shutdown_test"); + cfg.set_host("127.0.0.1"); + cfg.set_port("0"); + for (int i = 0; i < 10; ++i) { + cmvr::task::GrpcServerTask task(cfg); + ASSERT_TRUE(task.init()); + ASSERT_TRUE(task.start()); + task.stop(); + task.stop(); + EXPECT_TRUE(task.isFinished()); + } +} diff --git a/cmvr-es/task/grpc_server_task/include/grpc_server_task.h b/cmvr-es/task/grpc_server_task/include/grpc_server_task.h index e6b4469b..248e6bad 100644 --- a/cmvr-es/task/grpc_server_task/include/grpc_server_task.h +++ b/cmvr-es/task/grpc_server_task/include/grpc_server_task.h @@ -46,6 +46,7 @@ private: std::string id_; mutable std::mutex mutex_; + std::mutex lifecycle_mutex_; TaskState state_{TaskState::UNINITIALIZED}; std::string address_; std::string last_error_; diff --git a/cmvr-es/task/grpc_server_task/src/grpc_server_task.cpp b/cmvr-es/task/grpc_server_task/src/grpc_server_task.cpp index 22d9019b..75f68b26 100644 --- a/cmvr-es/task/grpc_server_task/src/grpc_server_task.cpp +++ b/cmvr-es/task/grpc_server_task/src/grpc_server_task.cpp @@ -1,6 +1,7 @@ #include "task/grpc_server_task/include/grpc_server_task.h" #include +#include #include @@ -70,6 +71,7 @@ GrpcServerTask::~GrpcServerTask() bool GrpcServerTask::start() { + std::lock_guard lifecycle(lifecycle_mutex_); std::lock_guard lock(mutex_); if (state_ == TaskState::RUNNING) { return true; @@ -162,14 +164,22 @@ bool GrpcServerTask::step(const double dt) void GrpcServerTask::stop() { + std::lock_guard lifecycle(lifecycle_mutex_); + grpc::Server* server = nullptr; + service::gRPCSystemServiceImpl* system_service = nullptr; { std::lock_guard lock(mutex_); - if (system_service_) { - system_service_->prepareForShutdown(); - } - if (server_) { - server_->Shutdown(); - } + system_service = system_service_.get(); + server = server_.get(); + } + if (system_service) { + system_service->prepareForShutdown(); + } + if (server) { + // Cancel persistent streams after a short grace period. An unbounded + // Shutdown waits forever for clients that keep their streams open. + // Keep mutex_ free so waitLoop and status readers can finish as well. + server->Shutdown(std::chrono::system_clock::now() + std::chrono::milliseconds(500)); } if (wait_thread_.joinable()) {