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.
This commit is contained in:
linbo 2026-11-12 10:24:11 +08:00
parent 2a5ef98649
commit 52f9fc376f
7 changed files with 154 additions and 7 deletions

View File

@ -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<std::uint16_t>(
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);

View File

@ -205,9 +205,15 @@ bool MotorManager::init()
bool MotorManager::stop()
{
bool success = true;
std::vector<std::pair<std::string, std::shared_ptr<AbstractMotor>>> motors;
{
std::lock_guard<std::mutex> 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()) {

View File

@ -83,3 +83,42 @@ TEST(MotorManagerShutdown, LingkongDisabledOrMissingMotorNeverAbortsGroupStop) {
}
}
}
#include <future>
#include <chrono>
namespace {
class WaitingShutdownMotor final : public AbstractMotor {
public:
std::promise<void> entered;
std::shared_future<void> release;
explicit WaitingShutdownMotor(std::shared_future<void> 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<void> release;
auto motor = std::make_shared<WaitingShutdownMotor>(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

View File

@ -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)

View File

@ -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 <gtest/gtest.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <chrono>
#include <thread>
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<sockaddr*>(&address), sizeof(address));
socklen_t length = sizeof(address);
const int named = getsockname(fd, reinterpret_cast<sockaddr*>(&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());
}
}

View File

@ -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_;

View File

@ -1,6 +1,7 @@
#include "task/grpc_server_task/include/grpc_server_task.h"
#include <exception>
#include <chrono>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
@ -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()) {