Compare commits

...

5 Commits

Author SHA1 Message Date
dcc85c28f4 feat(management): add independent configuration and process manager 2026-12-04 13:47:05 +08:00
c8b71b2b38 Merge dev into linbo_dev; retain disabled real-device defaults 2026-11-25 11:13:27 +08:00
3d8391f3c6 chore(config): sync dev real and simulation device profiles
Sync configuration-related changes from dev 7d230fa5, including profile-aware readiness helpers and test paths. Keep linbo_dev legacy/minimal arm and Lingkong templates so existing references remain valid. Disable repository device defaults in both real and simulation profiles. Preserve the SocketCAN fix. Validate full Release all-target build, ten readiness tests and fifteen protobuf configurations.
2026-11-20 09:43:35 +08:00
70bd28fe4e fix(socketcan): restore bounded receive and adapt regression tests
Keep the poll-based receive implementation and explicit timeout overload. Bound default receive to 100 ms for idle-bus shutdown, clear stale output frames, and adapt the test peer to the current API. Validate complete Release all-target build, seven SocketCAN cases, and eleven offline regression executables.
2026-11-19 17:29:28 +08:00
173a5cbf7d feat(huayan): control cabinet CO IO with Aubo-compatible JSON parameters 2026-11-19 12:50:42 +08:00
18 changed files with 823 additions and 9 deletions

View File

@ -163,10 +163,16 @@ target_link_libraries(cmvr_es PRIVATE
)
install(TARGETS cmvr_es RUNTIME DESTINATION bin)
# Preserve deployed configuration; install only missing defaults.
install(CODE "set(CMVR_DEFAULT_CONFIG \"${CMAKE_CURRENT_SOURCE_DIR}/cmvr-es/config\")")
install(CODE [[
file(REMOVE_RECURSE
"${CMAKE_INSTALL_PREFIX}/bin/config"
"${CMAKE_INSTALL_PREFIX}/bin/model")
file(GLOB_RECURSE defaults RELATIVE "${CMVR_DEFAULT_CONFIG}" "${CMVR_DEFAULT_CONFIG}/*")
foreach(relative IN LISTS defaults)
if(NOT EXISTS "${CMAKE_INSTALL_PREFIX}/bin/config/${relative}")
get_filename_component(parent "${relative}" DIRECTORY)
file(INSTALL "${CMVR_DEFAULT_CONFIG}/${relative}" DESTINATION "${CMAKE_INSTALL_PREFIX}/bin/config/${parent}")
endif()
endforeach()
]])
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/cmvr-es/config DESTINATION bin)
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/model DESTINATION bin)
add_subdirectory(cmvr-es/management)

View File

@ -203,21 +203,21 @@ device_manager {
id: "xiaozhao_tchl_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/xiaozhao_tchl_motors.pb.txt"
enable: true
enable: false
}
devices {
id: "xiaozhao_tchl_right_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/xiaozhao_tchl_arm.pb.txt"
enable: true
enable: false
}
devices {
id: "xiaozhao_tchl_left_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/xiaozhao_tchl_arm.pb.txt"
enable: true
enable: false
}
devices {

View File

@ -21,6 +21,7 @@ target_link_libraries(huayan_arm
cmvr_es::proto
PRIVATE
HR_Pro
jsoncpp
glog
Threads::Threads
)
@ -29,3 +30,10 @@ add_library(cmvr_es::device::huayan_arm ALIAS huayan_arm)
install(TARGETS huayan_arm LIBRARY DESTINATION lib)
install(FILES ${HUAYAN_ARM_SDK_DIR}/lib/libHR_Pro.so DESTINATION lib)
if(BUILD_TESTING)
add_executable(huayan_cabinet_io_test tests/huayan_cabinet_io_test.cpp)
set_target_properties(huayan_cabinet_io_test PROPERTIES ENABLE_EXPORTS ON)
target_link_libraries(huayan_cabinet_io_test PRIVATE cmvr_es::device::huayan_arm jsoncpp gtest gtest_main)
add_test(NAME huayan_cabinet_io_test COMMAND huayan_cabinet_io_test)
endif()

View File

@ -0,0 +1,31 @@
# Cabinet CI/CO IO
Use `cmvr.api.ArmService.ExecuteJsonCommand`, with the same parameter names as Aubo.
The request header selects the Huayan arm device. The following object is serialized
as the `request_json` string:
```json
{"command":"cabinet_io","operation":"set_do","index":0,"value":true}
```
`index: 0` selects **CO0**, not DO0. `true` writes 1, `false` writes 0.
Writing calls `HRIF_SetBoxCO`; reading uses `HRIF_ReadBoxCO`.
For readback, use:
```json
{"command":"cabinet_io","operation":"get_do","index":0}
```
`get_di` reads the corresponding configurable **CI** input.
The SDK supplies the available CI/CO count; channel numbers start at zero.
`value` must be a JSON boolean for writes. No motion enable is performed.
The gRPC response uses the existing `header` and `response_json` fields.
The JSON response contains `success`, `command`, `operation`, `index`, `count`,
`io_type` (CI or CO), and `sdk_return_code`. Reads return `value`; successful
writes return `requested_value`, which indicates SDK command success and does not
claim physical readback. Failures return `error_code` and `error_message`.
Aubo-specific `runstate` fields are not fabricated for Huayan.
Build `huayan_cabinet_io_test` with `BUILD_TESTING=ON` for offline verification.
The test executable replaces the IO SDK symbols and does not connect to hardware.

View File

@ -1,6 +1,8 @@
#include "huayan_arm.h"
#include <algorithm>
#include <cctype>
#include <json/json.h>
#include <array>
#include <chrono>
#include <cmath>
@ -112,6 +114,88 @@ HuayanRobot::~HuayanRobot()
(void)disconnect();
}
bool HuayanRobot::executeJsonCommand(const std::string& request_json, std::string& response_json)
{
Json::Value response(Json::objectValue);
const auto put = [&](const char* key) -> Json::Value& {
return *response.demand(key, key + std::char_traits<char>::length(key));
};
const auto serialize = [&]() {
Json::StreamWriterBuilder writer;
writer[std::string("indentation")] = "";
response_json = Json::writeString(writer, response);
};
put("success") = false;
const auto fail = [&](const std::string& code, const std::string& message) {
put("error_code") = code; put("error_message") = message; serialize();
CMVR_LOG(ERROR) << "[HuayanRobot] cabinet_io: " << message;
return false;
};
Json::Value root; Json::CharReaderBuilder builder;
std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
std::string error;
if (!reader->parse(request_json.data(), request_json.data() + request_json.size(), &root, &error))
return fail("invalid_json", "invalid json: " + error);
if (!root.isObject()) return fail("invalid_json", "invalid json: root must be an object");
const auto member = [&](const char* key) { return root.find(key, key + std::char_traits<char>::length(key)); };
const auto text = [&](const char* key) {
const auto* v = member(key);
std::string value = v && v->isString() ? v->asString() : std::string{};
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); });
return value;
};
const auto command = text("command");
if (command.empty()) return fail("invalid_argument", "field 'command' is required and must be a non-empty string");
if (command != "cabinet_io") return fail("unsupported_command", "unsupported json command: " + command);
put("command") = command;
const auto operation = text("operation");
if (operation.empty()) return fail("invalid_argument", "field 'operation' is required and must be a non-empty string");
if (operation != "get_di" && operation != "get_do" && operation != "set_do")
return fail("invalid_operation", "unsupported cabinet_io operation: " + operation);
put("operation") = operation;
const auto* index_value = member("index");
if (!index_value || !index_value->isInt() || index_value->asInt() < 0)
return fail("invalid_argument", "field 'index' is required and must be a non-negative JSON integer");
const int index = index_value->asInt(); put("index") = index;
const auto* value = member("value");
if (operation == "set_do" && (!value || !value->isBool()))
return fail("invalid_argument", "field 'value' is required for set_do and must be a JSON boolean");
std::lock_guard<std::mutex> lock(mutex_);
const auto ready = ensureConnected_("cabinet_io");
if (!ready.ok()) return fail("not_connected", ready.message);
try {
// Same request shape as Aubo; Huayan configurable cabinet ports are CI/CO.
// CO0 is index 0, not the separate general-purpose DO0 terminal.
std::vector<int> ports;
const bool input = operation == "get_di";
int ret = input ? HRIF_ReadAllBoxCI(box_id_, ports) : HRIF_ReadAllBoxCO(box_id_, ports);
put("io_type") = input ? "CI" : "CO"; put("sdk_return_code") = ret;
if (ret != 0) return fail("sdk_command_failed", "failed to read IO count: sdk ret=" + std::to_string(ret));
put("count") = static_cast<int>(ports.size());
if (static_cast<std::size_t>(index) >= ports.size())
return fail("index_out_of_range", "cabinet_io index out of range: index=" + std::to_string(index) + ", count=" + std::to_string(ports.size()));
if (operation == "set_do") {
ret = HRIF_SetBoxCO(box_id_, index, value->asBool() ? 1 : 0);
put("sdk_return_code") = ret;
if (ret != 0) return fail("sdk_command_failed", "cabinet_io set_do failed: sdk ret=" + std::to_string(ret));
put("requested_value") = value->asBool();
} else {
int actual = -1;
ret = input ? HRIF_ReadBoxCI(box_id_, index, actual) : HRIF_ReadBoxCO(box_id_, index, actual);
put("sdk_return_code") = ret;
if (ret != 0) return fail("sdk_command_failed", "cabinet_io read failed: sdk ret=" + std::to_string(ret));
if (actual != 0 && actual != 1) return fail("invalid_io_value", "cabinet_io returned a non-digital value");
put("value") = actual != 0;
}
put("success") = true; serialize();
CMVR_LOG(INFO) << "[HuayanRobot] cabinet_io: operation=" << operation << ", index=" << index << ", sdk ret=" << ret;
return true;
} catch (const std::exception& e) {
return fail("sdk_exception", std::string("[HuayanRobot] cabinet_io failed: ") + e.what());
}
}
bool HuayanRobot::init()
{
if (ip_.empty()) {

View File

@ -28,6 +28,7 @@ public:
~HuayanRobot() override;
std::string typeName() const override { return "HuayanRobot"; }
bool executeJsonCommand(const std::string& request_json, std::string& response_json) override;
bool init() override;
bool stop() override;
@ -107,6 +108,7 @@ public:
bool busy() const override { return busy_.load(); }
private:
friend struct HuayanIoTestAccess;
struct HrState {
int moving{0};
int enabled{0};

View File

@ -0,0 +1,53 @@
// Executable SDK symbol overrides: no connection to hardware and no physical IO writes.
#include "huayan_arm.h"
#include <gtest/gtest.h>
#include <json/json.h>
#include <sstream>
#include <vector>
namespace { int calls=0, written=-1, channel=-1, result=0, actual=1; }
extern "C" bool HRIF_IsConnected(unsigned int) { return true; }
extern "C" int HRIF_ReadAllBoxCO(unsigned int,std::vector<int>& v) { ++calls;v={0,0,0,0};return result; }
extern "C" int HRIF_ReadAllBoxCI(unsigned int,std::vector<int>& v) { ++calls;v={0,0};return result; }
extern "C" int HRIF_SetBoxCO(unsigned int,int bit,int value) { ++calls;channel=bit;written=value;return result; }
extern "C" int HRIF_ReadBoxCO(unsigned int,int bit,int& value) { ++calls;channel=bit;value=actual;return result; }
extern "C" int HRIF_ReadBoxCI(unsigned int,int bit,int& value) { ++calls;channel=bit;value=actual;return result; }
namespace cmvr::device {
const Json::Value& get(const Json::Value& r,const char* key) {const auto* p=r.find(key,key+std::char_traits<char>::length(key));if(!p)throw std::runtime_error("missing response field");return *p;}
struct HuayanIoTestAccess {static void connected(HuayanRobot& arm,bool value){arm.connected_=value;}};
class HuayanCabinetIo : public ::testing::Test {
protected:
config::RobotArmConfig cfg;
std::unique_ptr<HuayanRobot> arm;
void SetUp()override {calls=0;written=-1;channel=-1;result=0;actual=1;cfg.set_id("fake_huayan");arm=std::make_unique<HuayanRobot>(cfg);HuayanIoTestAccess::connected(*arm,true);}
void TearDown()override {HuayanIoTestAccess::connected(*arm,false);arm.reset();}
Json::Value invoke(const std::string& request,bool success) {std::string response;EXPECT_EQ(arm->executeJsonCommand(request,response),success);Json::Value value;Json::CharReaderBuilder reader;std::string error;std::istringstream in(response);EXPECT_TRUE(Json::parseFromStream(reader,in,&value,&error));return value;}
};
TEST_F(HuayanCabinetIo, SameAuboParametersSetCO0HighAndLow) {
auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",true);
EXPECT_EQ(channel,0);EXPECT_EQ(written,1);EXPECT_TRUE(get(r,"requested_value").asBool());EXPECT_EQ(get(r,"io_type").asString(),"CO");
invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":false})",true);EXPECT_EQ(written,0);
}
TEST_F(HuayanCabinetIo, ReadActualCOAndCI) {
auto r=invoke(R"({"command":"cabinet_io","operation":"get_do","index":0})",true);EXPECT_TRUE(get(r,"value").asBool());EXPECT_EQ(channel,0);
actual=0;r=invoke(R"({"command":"cabinet_io","operation":"get_di","index":1})",true);EXPECT_FALSE(get(r,"value").asBool());EXPECT_EQ(get(r,"io_type").asString(),"CI");
}
TEST_F(HuayanCabinetIo, RejectInvalidWithoutSdkCalls) {
for(auto request:{"{","[]",R"({"command":"other"})",R"({"command":"cabinet_io","operation":"set_do","index":0,"value":1})",R"({"command":"cabinet_io","operation":"set_do","index":-1,"value":true})",R"({"command":"cabinet_io","operation":"get_do","index":0.5})"})invoke(request,false);
EXPECT_EQ(calls,0);
}
TEST_F(HuayanCabinetIo, RejectOutOfRangeWithoutWriting) {
auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":4,"value":true})",false);
EXPECT_EQ(get(r,"error_code").asString(),"index_out_of_range");EXPECT_EQ(written,-1);
}
TEST_F(HuayanCabinetIo, PropagateSdkFailure) {
result=123;auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",false);
EXPECT_EQ(get(r,"sdk_return_code").asInt(),123);EXPECT_EQ(written,-1);
}
TEST_F(HuayanCabinetIo, DisconnectedNeverCallsSdk) {
HuayanIoTestAccess::connected(*arm,false);auto r=invoke(R"({"command":"cabinet_io","operation":"set_do","index":0,"value":true})",false);
EXPECT_EQ(get(r,"error_code").asString(),"not_connected");EXPECT_EQ(calls,0);
}
TEST_F(HuayanCabinetIo, InvalidFeedbackIsNotReportedAsTrue) {
actual=7;auto r=invoke(R"({"command":"cabinet_io","operation":"get_do","index":0})",false);EXPECT_EQ(get(r,"error_code").asString(),"invalid_io_value");
}
}

View File

@ -200,7 +200,8 @@ namespace cmvr {
ErrorCode SocketCanClientRaw::receive(std::vector<CanFrame> *const frames,
int32_t *const frame_num) {
return receive(frames, frame_num, std::chrono::milliseconds{-1});
// Periodically return to CanReceiver stop checks, even on an idle bus.
return receive(frames, frame_num, std::chrono::milliseconds{100});
}
ErrorCode SocketCanClientRaw::receive(std::vector<CanFrame> *const frames,
@ -214,6 +215,7 @@ namespace cmvr {
if (frames == nullptr) {
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
frames->clear();
if (!is_started_) {
CMVR_LOG(ERROR) << "Nvidia can client is not init! Please init first!";
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;

View File

@ -54,7 +54,7 @@ namespace cmvr {
int32_t *const frame_num) override;
/**
* @brief Receive messages
* @brief Receive messages with a bounded 100 ms wait so receivers can stop
* @param frames The messages to receive.
* @param frame_num The amount of messages to receive.
* @return The status of the receiving action
@ -78,6 +78,7 @@ namespace cmvr {
*/
std::string getErrorString(const int32_t status) override;
private:
friend class SocketCanClientRawTestPeer;
int dev_handler_ = -1;
cmvr::msgs::CANCardParameter::CANChannelId port_;
cmvr::msgs::CANCardParameter::CANInterface interface_;

View File

@ -0,0 +1,22 @@
add_executable(cmvr_manager manager_main.cpp)
target_compile_definitions(cmvr_manager PRIVATE _GNU_SOURCE)
target_link_libraries(cmvr_manager PRIVATE cmvr_es::proto pthread)
# Bundled gRPC's indirect shared dependencies also live in output/lib.
# DT_RPATH applies to those dependencies without relying on the launch shell.
target_link_options(cmvr_manager PRIVATE "-Wl,--disable-new-dtags")
file(GLOB_RECURSE _config_protos RELATIVE "${PROTO_IMPORT_DIR}" "${PROTO_IMPORT_DIR}/cmvr/config/*.proto")
set(_config_registry "")
foreach(_file IN LISTS _config_protos)
string(APPEND _config_registry "CMVR_CONFIG_FILE(\"${_file}\")\n")
endforeach()
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/config_types.inc" "${_config_registry}")
target_include_directories(cmvr_manager PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")
install(TARGETS cmvr_manager RUNTIME DESTINATION bin)
add_executable(cmvr_manager_ctl manager_ctl.cpp)
target_link_libraries(cmvr_manager_ctl PRIVATE cmvr_es::proto pthread)
target_link_options(cmvr_manager_ctl PRIVATE "-Wl,--disable-new-dtags")
install(TARGETS cmvr_manager_ctl RUNTIME DESTINATION bin)
install(PROGRAMS start_all.sh DESTINATION bin)
add_executable(cmvr_manager_test EXCLUDE_FROM_ALL manager_test.cpp)
target_link_libraries(cmvr_manager_test PRIVATE cmvr_es::proto pthread)
target_link_options(cmvr_manager_test PRIVATE "-Wl,--disable-new-dtags")

View File

@ -0,0 +1,109 @@
# Independent cmvr-es management
`cmvr_manager` is a separate gRPC process. Device RPCs remain in `cmvr_es`.
It uses the existing executable and configuration layout:
```
output/bin/cmvr_es
output/bin/cmvr_manager
output/bin/config/...
output/lib/...
```
Build with the existing CMake build directory:
```
cmake --build cmake-build-debug --target cmvr_manager
cmake --install cmake-build-debug/cmvr-es/management
```
When first installing a newly generated management protocol, install the matching
`libproto.so` in `output/lib` as well. A normal full project install does this.
Installing defaults now preserves existing deployed configuration files and adds
only missing files. Models retain their existing install location.
Run as the ordinary deployment user:
```
cd output/bin
./cmvr_manager --listen 0.0.0.0:50053
```
To start both programs together, run `output/bin/start_all.sh` as the deployment
user. It starts/reuses the matching management endpoint and requests cmvr_es
startup over gRPC, so cmvr_es remains owned by the manager. Repeated execution
does not restart either process. `CMVR_MANAGEMENT_PORT` overrides port 50053.
Logs append to the existing `output/bin/cmvr_manager.log`.
`output/bin/cmvr_manager_ctl status` queries status; `start`, `stop`, and `restart`
use the same typed management gRPC interface. An application started outside the
manager must first be stopped through its original launcher.
Initialize bus hardware before starting cmvr_es, using the existing repository
layout:
```
./scripts/start_hardware.sh --ethercat-iface enp2s0 --check
./scripts/start_hardware.sh --ethercat-iface enp2s0
./output/bin/start_all.sh
```
The hardware script is installed in the repository's existing `scripts` directory.
It discovers currently present CAN interfaces, uses the existing CAN script's
1 Mbps default. EtherCAT always requires an explicit `--ethercat-iface IFACE`,
including in `--check` mode; there is no fallback from configuration or environment.
`--can-only` does not need an EtherCAT interface. `--ethercat-only`, repeatable
`--can-iface`, and `--bitrate` are available. It requests sudo only for actual
initialization. It refuses a normal-network interface and refuses hardware
reinitialization while cmvr_es is running. Existing CAN links at the requested
rate and an existing EtherCAT master on the selected MAC are kept running.
Changing a running CAN link's bitrate requires `--reconfigure-can`.
In these examples `enp2s0` is only an example: pass the actual dedicated port.
On 234, the existing EtherCAT config names `enp2s0`; both Ethernet ports use IgH's
igc driver. At script creation there were no CAN interfaces and both Ethernet
ports had no carrier. The script was checked without altering network interfaces;
real bus communication requires connecting the hardware and confirming the
dedicated EtherCAT port. No drive enable or movement is performed by this script.
The default executable and working directory are the manager's own directory.
`--bin-dir` selects another existing deployment directory for isolated testing.
No shell commands, executable paths or arbitrary filenames are accepted over RPC.
This is the same trusted-LAN, insecure-gRPC transport as the existing device
service; it does not introduce a public internet endpoint.
`GetStatus` reports process existence/ownership, not device readiness. A running
process started by CLion or another launcher is detected but not stopped or
adopted. Stop it in the original launcher before starting it through the manager.
`STOP` sends SIGTERM and waits up to 30 seconds; timeout never escalates to SIGKILL
and cancels `RESTART`. Process startup errors remain visible through management
RPC and the manager's redirected output. Stop the managed child before stopping
the manager itself; this initial implementation does not provide boot autostart
or adopt an orphaned child after the manager is killed.
Configuration RPCs access existing `.pb.txt` files inside the existing `config`
directory. Writes check protobuf syntax, known fields/enums, message type and
configuration-file references. The root config must retain logger, device manager
and task manager references. Writes require the revision returned by `ReadConfig`
and use a flushed temporary file beside the destination followed by rename.
The temporary file is not a server-side draft. The editor stores drafts on the
Windows client in `data/management_drafts.json`, keyed by endpoint and filename.
Saving does not automatically restart the application. File validation does not
certify device parameters or hardware readiness; runtime/device initialization
continues to perform those checks.
Protocol: `protos/cmvr/management/manager.proto`.
Tests:
```
cmake --build cmake-build-debug --target cmvr_manager cmvr_manager_test
python3 cmvr-es/management/test_manager.py
cmake-build-debug/cmvr-es/management/cmvr_manager_test 127.0.0.1:50053 --read-only
```
The fixture test uses a temporary directory and replacement child process. The
`--lifecycle` mode is specifically for a deployment whose cmvr_es is stopped and
whose enabled tasks/devices have been checked first. It saves identical config
bytes, starts/restarts/stops the real program, checks control gRPC on 50052, and
leaves it stopped. Do not use that mode against a deployment in active operation.

View File

@ -0,0 +1,23 @@
#include "cmvr/management/manager.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <chrono>
#include <filesystem>
#include <iostream>
namespace api=cmvr::management;
int main(int argc,char** argv){
std::string endpoint="127.0.0.1:50053",command="status",expected;
for(int i=1;i<argc;++i){std::string arg=argv[i];if(arg=="--endpoint"&&i+1<argc)endpoint=argv[++i];else if(arg=="--expected-executable"&&i+1<argc)expected=argv[++i];else if(arg=="status"||arg=="ensure-running"||arg=="start"||arg=="stop"||arg=="restart")command=arg;else{std::cerr<<"Usage: cmvr_manager_ctl [status|ensure-running|start|stop|restart] [--endpoint HOST:PORT] [--expected-executable PATH]\n";return 2;}}
auto stub=api::ManagerService::NewStub(grpc::CreateChannel(endpoint,grpc::InsecureChannelCredentials()));
api::ProcessStatus status;grpc::ClientContext query;query.set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(2));auto result=stub->GetStatus(&query,api::Empty(),&status);
if(!result.ok()){std::cerr<<result.error_message()<<"\n";return 1;}
if(!expected.empty()&&std::filesystem::weakly_canonical(expected)!=std::filesystem::weakly_canonical(status.executable())){std::cerr<<"Management endpoint belongs to a different deployment: "<<status.executable()<<"\n";return 3;}
if(command!="status"){
if(status.running()&&!status.managed()){std::cerr<<"cmvr_es was started outside this manager. Stop the original launcher first.\n";return 3;}
if(command!="ensure-running"||!status.running()){
api::ProcessRequest request;request.set_action(command=="stop"?api::ProcessRequest::STOP:command=="restart"?api::ProcessRequest::RESTART:api::ProcessRequest::START);grpc::ClientContext context;context.set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(40));result=stub->Control(&context,request,&status);
if(!result.ok()){std::cerr<<result.error_message()<<"\n";return 1;}
}
}
std::cout<<"cmvr_es "<<(status.running()?"running":"stopped")<<" pid="<<status.pid()<<" managed="<<status.managed()<<" executable="<<status.executable()<<"\n";
return 0;
}

View File

@ -0,0 +1,223 @@
#include "cmvr/management/manager.grpc.pb.h"
#include "cmvr/config/cmvr_es_config/cmvr_es_config.pb.h"
#include <grpcpp/grpcpp.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/tokenizer.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <mutex>
#include <thread>
#include <chrono>
#include <vector>
#include <memory>
#include <algorithm>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <cstring>
#include <spawn.h>
#include <signal.h>
#include <unistd.h>
extern char **environ;
namespace fs=std::filesystem;
namespace api=cmvr::management;
using grpc::Status;
using grpc::StatusCode;
using google::protobuf::Message;
struct ParseErrors final:google::protobuf::io::ErrorCollector {
std::string detail;
void RecordError(int line,google::protobuf::io::ColumnNumber col,absl::string_view text) override {
detail+=std::to_string(line+1)+":"+std::to_string(col+1)+" "+std::string(text)+"\n";
}
void RecordWarning(int,google::protobuf::io::ColumnNumber,absl::string_view) override {}
};
static std::string readFile(const fs::path& path) {
std::ifstream file(path,std::ios::binary);
if(!file)throw std::runtime_error("Cannot read "+path.string());
std::string text((std::istreambuf_iterator<char>(file)),{});
if(text.size()>1024*1024)throw std::runtime_error("Configuration exceeds 1 MiB");
return text;
}
// A revision identifies bytes, including formatting. It is not an authorization token.
static std::string revision(const std::string& text) {
uint64_t h=14695981039346656037ULL;
for(unsigned char c:text){h^=c;h*=1099511628211ULL;}
std::ostringstream out;out<<std::hex<<h<<"-"<<text.size();return out.str();
}
class Manager final:public api::ManagerService::Service {
fs::path bin_,root_,exe_;
std::mutex mutex_;
pid_t child_=-1;
int lastExit_=0;
std::vector<const google::protobuf::Descriptor*> types_;
google::protobuf::DynamicMessageFactory factory_;
fs::path configPath(const std::string& name) const {
fs::path input(name);
if(input.empty()||input.is_absolute())throw std::runtime_error("Expected relative configuration path");
for(const auto& part:input)if(part=="..")throw std::runtime_error("Parent traversal is forbidden");
const auto p=fs::canonical(root_/input);
const auto rel=p.lexically_relative(root_);
if(rel.empty()||*rel.begin()==".."||!fs::is_regular_file(p)||p.extension()!=".txt"||p.string().size()<7||p.string().substr(p.string().size()-7)!=".pb.txt")
throw std::runtime_error("Only existing .pb.txt files inside config are accessible");
return p;
}
void reap() {
if(child_<=0)return;
int code=0;const auto result=waitpid(child_,&code,WNOHANG);
if(result==child_){lastExit_=WIFEXITED(code)?WEXITSTATUS(code):128+WTERMSIG(code);child_=-1;}
}
pid_t existingProcess() {
reap();if(child_>0)return child_;
for(const auto& item:fs::directory_iterator("/proc")){
const auto name=item.path().filename().string();
if(name.empty()||!std::all_of(name.begin(),name.end(),[](char c){return c>='0'&&c<='9';}))continue;
std::error_code error;const auto executable=fs::read_symlink(item.path()/"exe",error);
if(!error&&executable==exe_)return std::stoi(name);
}return -1;
}
void status(api::ProcessStatus* result,const std::string& detail={}) {
auto pid=existingProcess();result->set_running(pid>0);result->set_pid(pid>0?pid:0);
result->set_managed(pid>0&&pid==child_);result->set_executable(exe_.string());
result->set_working_directory(bin_.string());result->set_last_exit_code(lastExit_);
result->set_detail(detail.empty()?(pid>0?(pid==child_?"Process running (not a device readiness check)":"Process started outside manager; stop it in its original launcher first"):"Process stopped"):detail);
}
std::unique_ptr<Message> parse(const std::string& text,std::string& error) {
std::string candidateError;
for(auto* type:types_){
std::unique_ptr<Message> message(factory_.GetPrototype(type)->New());
ParseErrors errors;google::protobuf::TextFormat::Parser parser;parser.RecordErrorsTo(&errors);
if(parser.ParseFromString(text,message.get())){
std::vector<const google::protobuf::FieldDescriptor*> fields;
message->GetReflection()->ListFields(*message,&fields);
if(!fields.empty())return message;
}
for(int i=0;i<type->field_count();++i)if(text.find(std::string(type->field(i)->name())+" {")!=std::string::npos&&candidateError.empty())candidateError=errors.detail;
}
error=candidateError.empty()?"No configuration schema matches this document (unknown field, enum, or invalid protobuf text)":candidateError;return {};
}
bool references(const Message& message,std::string& error) {
const auto* reflection=message.GetReflection();std::vector<const google::protobuf::FieldDescriptor*> fields;
reflection->ListFields(message,&fields);
for(auto* field:fields){
if(field->cpp_type()==google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE){
int count=field->is_repeated()?reflection->FieldSize(message,field):1;
for(int i=0;i<count;++i)if(!references(field->is_repeated()?reflection->GetRepeatedMessage(message,field,i):reflection->GetMessage(message,field),error))return false;
}else if(field->cpp_type()==google::protobuf::FieldDescriptor::CPPTYPE_STRING&&field->name().size()>=11&&field->name().substr(field->name().size()-11)=="config_file"){
const auto name=reflection->GetString(message,field);
if(!name.empty())try{configPath(name);}catch(const std::exception& e){error=std::string(field->full_name())+": "+e.what();return false;}
}
}return true;
}
bool validate(const std::string& text,std::string& error) {
if(text.empty()||text.size()>1024*1024){error="Configuration must contain 1 byte to 1 MiB";return false;}
auto parsed=parse(text,error);return parsed&&references(*parsed,error);
}
bool validateFile(const fs::path& path,const std::string& text,std::string& error) {
if(!validate(text,error))return false;
auto replacement=parse(text,error);
std::string previousError;auto previous=parse(readFile(path),previousError);
const auto* expected=path==root_/"cmvr_es.pb.txt"?cmvr::config::CMVRESRootConfig::descriptor():(previous?previous->GetDescriptor():nullptr);
if(expected&&replacement->GetDescriptor()!=expected){error="Configuration message type must remain "+std::string(expected->full_name());return false;}
if(expected==cmvr::config::CMVRESRootConfig::descriptor()){
cmvr::config::CMVRESRootConfig root;root.ParseFromString(replacement->SerializeAsString());
if(root.cmvr_es().logger_config_file().empty()||root.cmvr_es().device_manager_config_file().empty()||root.cmvr_es().task_manager_config_file().empty()){
error="logger_config_file, device_manager_config_file and task_manager_config_file are required";return false;
}
}
return true;
}
Status stop() {
const auto pid=existingProcess();if(pid<=0)return Status::OK;
if(pid!=child_)return {StatusCode::FAILED_PRECONDITION,"Process is not owned by this manager. Stop the original launcher first."};
if(kill(child_,SIGTERM)!=0&&errno!=ESRCH)return {StatusCode::INTERNAL,"Cannot send SIGTERM"};
for(int i=0;i<300;++i){reap();if(child_<=0)return Status::OK;std::this_thread::sleep_for(std::chrono::milliseconds(100));}
return {StatusCode::DEADLINE_EXCEEDED,"Graceful shutdown exceeded 30 seconds; process was not killed. Restart was cancelled."};
}
Status start() {
if(existingProcess()>0)return {StatusCode::FAILED_PRECONDITION,"cmvr_es is already running"};
std::string error;
if(!validateFile(root_/"cmvr_es.pb.txt",readFile(root_/"cmvr_es.pb.txt"),error))return {StatusCode::INVALID_ARGUMENT,error};
posix_spawn_file_actions_t actions;posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_addchdir_np(&actions,bin_.c_str());
posix_spawnattr_t attr;posix_spawnattr_init(&attr);
sigset_t empty;sigemptyset(&empty);posix_spawnattr_setsigmask(&attr,&empty);posix_spawnattr_setflags(&attr,POSIX_SPAWN_SETSIGMASK);
std::string executable=exe_.string();char* argv[]={executable.data(),nullptr};
const auto result=posix_spawn(&child_,exe_.c_str(),&actions,&attr,argv,environ);
posix_spawn_file_actions_destroy(&actions);posix_spawnattr_destroy(&attr);
if(result){child_=-1;return {StatusCode::INTERNAL,"Cannot launch cmvr_es: "+std::string(strerror(result))};}
std::this_thread::sleep_for(std::chrono::milliseconds(800));reap();
if(child_<=0)return {StatusCode::FAILED_PRECONDITION,"cmvr_es exited during startup, exit="+std::to_string(lastExit_)+". Check manager output."};
return Status::OK;
}
public:
explicit Manager(fs::path bin):bin_(fs::canonical(bin)),root_(fs::canonical(bin_/"config")),exe_(fs::canonical(bin_/"cmvr_es")) {
(void)cmvr::config::CMVRESRootConfig::descriptor();
auto* pool=google::protobuf::DescriptorPool::generated_pool();
const auto add=[&](const char* name){if(auto* file=pool->FindFileByName(name))for(int i=0;i<file->message_type_count();++i)types_.push_back(file->message_type(i));};
#define CMVR_CONFIG_FILE(name) add(name);
#include "config_types.inc"
#undef CMVR_CONFIG_FILE
}
Status GetStatus(grpc::ServerContext*,const api::Empty*,api::ProcessStatus* result) override {
std::lock_guard<std::mutex> lock(mutex_);try{status(result);return Status::OK;}catch(const std::exception& e){return {StatusCode::INTERNAL,e.what()};}
}
Status ListConfigs(grpc::ServerContext*,const api::Empty*,api::ConfigList* result) override {
std::lock_guard<std::mutex> lock(mutex_);
try{std::vector<std::string> names;for(const auto& file:fs::recursive_directory_iterator(root_)){
if(file.is_regular_file()){auto name=file.path().lexically_relative(root_).generic_string();try{configPath(name);names.push_back(name);}catch(...) {}}}
std::sort(names.begin(),names.end());for(const auto& name:names)result->add_paths(name);return Status::OK;
}catch(const std::exception& e){return {StatusCode::INTERNAL,e.what()};}
}
Status ReadConfig(grpc::ServerContext*,const api::ConfigPath* request,api::ConfigFile* result) override {
std::lock_guard<std::mutex> lock(mutex_);try{const auto text=readFile(configPath(request->path()));result->set_path(request->path());result->set_text(text);result->set_revision(revision(text));return Status::OK;}catch(const std::exception& e){return {StatusCode::INVALID_ARGUMENT,e.what()};}
}
Status ValidateConfig(grpc::ServerContext*,const api::ConfigFile* request,api::Validation* result) override {
std::lock_guard<std::mutex> lock(mutex_);try{auto path=configPath(request->path());std::string error;result->set_valid(validateFile(path,request->text(),error));result->set_detail(result->valid()?"Protobuf syntax, fields, document type and configuration references validated":error);return Status::OK;}catch(const std::exception& e){return {StatusCode::INVALID_ARGUMENT,e.what()};}
}
Status WriteConfig(grpc::ServerContext*,const api::ConfigFile* request,api::ConfigFile* result) override {
std::lock_guard<std::mutex> lock(mutex_);
try{
const auto path=configPath(request->path());std::string error;
if(!validateFile(path,request->text(),error))return {StatusCode::INVALID_ARGUMENT,error};
const auto old=readFile(path);
if(request->revision().empty()||request->revision()!=revision(old))return {StatusCode::ABORTED,"Configuration changed since it was read. Read it again before saving."};
auto temp=path.string()+".XXXXXX";int fd=mkstemp(temp.data());if(fd<0)return {StatusCode::INTERNAL,"Cannot create temporary file beside configuration"};
bool ok=true;size_t offset=0;while(offset<request->text().size()) {auto n=write(fd,request->text().data()+offset,request->text().size()-offset);if(n<0&&errno==EINTR)continue;if(n<=0){ok=false;break;}offset+=n;}
const auto perms=fs::status(path).permissions();fchmod(fd,static_cast<mode_t>(perms)&0777);if(fsync(fd)!=0)ok=false;if(close(fd)!=0)ok=false;
if(!ok){unlink(temp.c_str());return {StatusCode::INTERNAL,"Failed to flush configuration; original preserved"};}
// Recheck immediately before replacement to catch external edits during validation.
if(readFile(path)!=old){unlink(temp.c_str());return {StatusCode::ABORTED,"Configuration changed while saving"};}
if(rename(temp.c_str(),path.c_str())!=0){unlink(temp.c_str());return {StatusCode::INTERNAL,"Cannot replace configuration"};}
int directory=open(path.parent_path().c_str(),O_RDONLY|O_DIRECTORY);if(directory>=0){fsync(directory);close(directory);}
*result=*request;result->set_revision(revision(request->text()));return Status::OK;
}catch(const std::exception& e){return {StatusCode::INVALID_ARGUMENT,e.what()};}
}
Status Control(grpc::ServerContext*,const api::ProcessRequest* request,api::ProcessStatus* result) override {
std::lock_guard<std::mutex> lock(mutex_);
try{Status outcome;
switch(request->action()){
case api::ProcessRequest::START:outcome=start();break;
case api::ProcessRequest::STOP:outcome=stop();break;
case api::ProcessRequest::RESTART:outcome=stop();if(outcome.ok())outcome=start();break;
default:return {StatusCode::INVALID_ARGUMENT,"Explicit START, STOP or RESTART required"};
}status(result);return outcome;
}catch(const std::exception& e){return {StatusCode::INTERNAL,e.what()};}
}
};
int main(int argc,char** argv) {
try {
fs::path bin=fs::canonical("/proc/self/exe").parent_path();std::string address="0.0.0.0:50053";
for(int i=1;i<argc;++i){std::string arg=argv[i];if(arg=="--bin-dir"&&i+1<argc)bin=argv[++i];else if(arg=="--listen"&&i+1<argc)address=argv[++i];else {std::cerr<<"Usage: cmvr_manager [--listen IP:PORT] [--bin-dir existing-bin-directory]\n";return 2;}}
bin=fs::canonical(bin);int lockfd=open((bin/".cmvr_manager.lock").c_str(),O_CREAT|O_RDWR|O_CLOEXEC,0600);
if(lockfd<0||flock(lockfd,LOCK_EX|LOCK_NB)!=0)throw std::runtime_error("Another manager owns this deployment, or bin is not writable");
Manager manager(bin);grpc::ServerBuilder builder;builder.SetMaxReceiveMessageSize(2*1024*1024);
builder.AddListeningPort(address,grpc::InsecureServerCredentials());builder.RegisterService(&manager);
auto server=builder.BuildAndStart();if(!server)throw std::runtime_error("Cannot bind management gRPC address");
std::cout<<"cmvr_manager listening="<<address<<" bin="<<bin<<std::endl;server->Wait();
}catch(const std::exception& e){std::cerr<<e.what()<<std::endl;return 1;}
}

View File

@ -0,0 +1,48 @@
#include "cmvr/management/manager.grpc.pb.h"
#include "cmvr/api/system_service.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <iostream>
#include <stdexcept>
#include <chrono>
#include <thread>
namespace api=cmvr::management;
static void check(bool ok,const char* why){if(!ok)throw std::runtime_error(why);}
int main(int argc,char** argv){try{
check(argc>=2,"Expected endpoint [--read-only]");bool readOnly=argc>2;
auto stub=api::ManagerService::NewStub(grpc::CreateChannel(argv[1],grpc::InsecureChannelCredentials()));
auto context=[](){auto result=std::make_unique<grpc::ClientContext>();result->set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(40));return result;};
api::Empty empty;api::ProcessStatus status;auto c=context();check(stub->GetStatus(c.get(),empty,&status).ok(),"GetStatus");
std::cout<<"Status running="<<status.running()<<" managed="<<status.managed()<<" pid="<<status.pid()<<"\n";
api::ConfigList list;c=context();check(stub->ListConfigs(c.get(),empty,&list).ok()&&list.paths_size()>0,"ListConfigs");
api::ConfigPath path;path.set_path("cmvr_es.pb.txt");api::ConfigFile file;c=context();check(stub->ReadConfig(c.get(),path,&file).ok()&&!file.revision().empty(),"ReadConfig and revision");
api::Validation validation;c=context();check(stub->ValidateConfig(c.get(),file,&validation).ok()&&validation.valid(),"Validate root configuration");
if(readOnly&&std::string(argv[2])=="--lifecycle"){
check(!status.running(),"Lifecycle test requires initially stopped deployment");
struct Cleanup {api::ManagerService::Stub* stub;~Cleanup(){api::ProcessRequest request;request.set_action(api::ProcessRequest::STOP);api::ProcessStatus status;grpc::ClientContext c;c.set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(35));stub->Control(&c,request,&status);}} cleanup{stub.get()};
auto run=[&](api::ProcessRequest::Action value){api::ProcessRequest action;action.set_action(value);auto ctx=context();auto result=stub->Control(ctx.get(),action,&status);if(!result.ok())throw std::runtime_error("Control: "+result.error_message());};
auto ping=[&]{auto system=cmvr::api::SystemService::NewStub(grpc::CreateChannel("127.0.0.1:50052",grpc::InsecureChannelCredentials()));cmvr::api::GetSystemInfoCommand::Request request;cmvr::api::GetSystemInfoCommand::Feedback reply;auto ctx=context();ctx->set_deadline(std::chrono::system_clock::now()+std::chrono::seconds(10));check(system->GetSystemInfo(ctx.get(),request,&reply).ok(),"Real cmvr-es control gRPC becomes reachable");};
api::ConfigFile saved;c=context();check(stub->WriteConfig(c.get(),file,&saved).ok()&&saved.text()==file.text(),"Save identical real configuration without changing content");
run(api::ProcessRequest::START);check(status.running()&&status.managed(),"Real managed startup");auto first=status.pid();ping();
run(api::ProcessRequest::RESTART);check(status.running()&&status.pid()!=first,"Real restart changes PID");ping();
run(api::ProcessRequest::STOP);check(!status.running(),"Real graceful stop");
c=context();check(stub->GetStatus(c.get(),empty,&status).ok(),"Management remains reachable while real service stopped");
std::cout<<"REAL CMVR-ES START / CONTROL GRPC / RESTART / STOP PASS\n";return 0;
}
if(readOnly){std::cout<<"REAL DEPLOYMENT READ-ONLY PASS files="<<list.paths_size()<<"\n";return 0;}
auto initial=file;
file.set_text(file.text()+"\n# management integration test\n");api::ConfigFile saved;c=context();check(stub->WriteConfig(c.get(),file,&saved).ok(),"Write valid configuration");
check(saved.revision()!=initial.revision(),"Revision changes");
c=context();check(stub->WriteConfig(c.get(),initial,&file).error_code()==grpc::StatusCode::ABORTED,"Stale writes rejected");
auto bad=saved;bad.set_text("cmvr_es { invented_parameter: true }");c=context();check(stub->ValidateConfig(c.get(),bad,&validation).ok()&&!validation.valid(),"Unknown field rejected");
c=context();check(stub->WriteConfig(c.get(),bad,&file).error_code()==grpc::StatusCode::INVALID_ARGUMENT,"Invalid configuration never saved");
bad=saved;bad.set_text("device_manager { name: \"wrong type\" }");c=context();check(stub->ValidateConfig(c.get(),bad,&validation).ok()&&!validation.valid(),"Cannot replace root configuration with another message type");
bad=saved;bad.set_text("cmvr_es { logger_config_file: \"missing.pb.txt\" }");c=context();check(stub->ValidateConfig(c.get(),bad,&validation).ok()&&!validation.valid(),"Missing reference rejected");
for(const auto& invalid:{"../outside.pb.txt","/etc/passwd","escape.pb.txt"}){path.set_path(invalid);c=context();check(!stub->ReadConfig(c.get(),path,&file).ok(),"Traversal, absolute paths, symlink escape rejected");}
api::ProcessRequest action;action.set_action(api::ProcessRequest::START);c=context();check(stub->Control(c.get(),action,&status).ok()&&status.running()&&status.managed(),"Start managed child");auto first=status.pid();
c=context();check(stub->Control(c.get(),action,&status).error_code()==grpc::StatusCode::FAILED_PRECONDITION,"Duplicate start rejected");
action.set_action(api::ProcessRequest::RESTART);c=context();check(stub->Control(c.get(),action,&status).ok()&&status.running()&&status.pid()!=first,"Graceful restart changes PID");
action.set_action(api::ProcessRequest::STOP);c=context();check(stub->Control(c.get(),action,&status).ok()&&!status.running(),"Graceful stop");
c=context();check(stub->GetStatus(c.get(),empty,&status).ok()&&!status.running(),"Manager survives child shutdown");
saved.set_text(initial.text());c=context();check(stub->WriteConfig(c.get(),saved,&file).ok(),"Restore configuration");
std::cout<<"MANAGEMENT INTEGRATION PASS\n";return 0;
}catch(const std::exception& e){std::cerr<<e.what()<<"\n";return 1;}}

38
cmvr-es/management/start_all.sh Executable file
View File

@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
# Run as the deployment user, not sudo. The manager owns the cmvr_es child.
BIN_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
PORT="${CMVR_MANAGEMENT_PORT:-50053}"
if [[ "${1:-}" == --help || "${1:-}" == -h ]]; then
echo 'Usage: ./start_all.sh (optional CMVR_MANAGEMENT_PORT=50053)'
exit 0
fi
[[ $# -eq 0 ]] || { echo 'Unexpected arguments; use --help.' >&2; exit 2; }
[[ "$PORT" =~ ^[0-9]{1,5}$ ]] && (( 10#$PORT > 0 && 10#$PORT < 65536 )) || { echo 'Invalid management port.' >&2; exit 2; }
if (( EUID == 0 )); then echo 'Run this script as the normal deployment user; hardware setup has a separate sudo script.' >&2; exit 1; fi
for name in cmvr_es cmvr_manager cmvr_manager_ctl; do
[[ -x "$BIN_DIR/$name" ]] || { echo "Missing executable: $BIN_DIR/$name" >&2; exit 1; }
done
cd "$BIN_DIR"
exec 9>"$BIN_DIR/.cmvr_start.lock"
flock -w 15 9 || { echo 'Another startup is in progress.' >&2; exit 1; }
CTL=("$BIN_DIR/cmvr_manager_ctl" --endpoint "127.0.0.1:$PORT" --expected-executable "$BIN_DIR/cmvr_es")
if ! "${CTL[@]}" status >/dev/null 2>&1; then
# FD 9 must not leak into the long-lived manager/child.
nohup "$BIN_DIR/cmvr_manager" --listen "0.0.0.0:$PORT" >>"$BIN_DIR/cmvr_manager.log" 2>&1 </dev/null 9>&- &
manager_pid=$!
ready=0
for ((i=0;i<10;i++)); do
if "${CTL[@]}" status >/dev/null 2>&1; then ready=1; break; fi
kill -0 "$manager_pid" 2>/dev/null || break
sleep 0.5
done
if (( ready == 0 )); then
echo "Management service failed to become ready; see $BIN_DIR/cmvr_manager.log" >&2
tail -15 "$BIN_DIR/cmvr_manager.log" >&2
exit 1
fi
fi
"${CTL[@]}" ensure-running
echo "Management gRPC: $PORT; log: $BIN_DIR/cmvr_manager.log"
echo 'Process started. Device/control-service readiness is reported separately by cmvr_es.'

View File

@ -0,0 +1,20 @@
"""Run on the Linux device. Fixtures never replace deployed device configuration."""
import pathlib, subprocess, tempfile, shutil, time, os, signal
repo=pathlib.Path(__file__).resolve().parents[2]
build=repo/'cmake-build-debug/cmvr-es/management'
with tempfile.TemporaryDirectory(prefix='cmvr-manager-test-') as temp:
root=pathlib.Path(temp)
shutil.copytree(repo/'output/bin/config',root/'config')
(root/'outside.pb.txt').write_text('outside')
(root/'config/escape.pb.txt').symlink_to(root/'outside.pb.txt')
fake=root/'cmvr_es'
fake.write_text('#!/usr/bin/python3\nimport signal,time\nsignal.signal(signal.SIGTERM,lambda *_:exit(0))\nwhile True: time.sleep(0.05)\n')
fake.chmod(0o755)
log=open(root/'manager.log','w+')
proc=subprocess.Popen([str(build/'cmvr_manager'),'--bin-dir',temp,'--listen','127.0.0.1:50054'],stdout=log,stderr=log)
try:
time.sleep(1)
subprocess.run([str(build/'cmvr_manager_test'),'127.0.0.1:50054'],check=True,timeout=80)
finally:
proc.terminate();proc.wait(timeout=5)
log.seek(0);print(log.read())

View File

@ -0,0 +1,35 @@
syntax = "proto3";
package cmvr.management;
// Independent process. This service remains available while cmvr_es is stopped.
service ManagerService {
rpc GetStatus(Empty) returns (ProcessStatus);
rpc ListConfigs(Empty) returns (ConfigList);
rpc ReadConfig(ConfigPath) returns (ConfigFile);
rpc ValidateConfig(ConfigFile) returns (Validation);
rpc WriteConfig(ConfigFile) returns (ConfigFile);
rpc Control(ProcessRequest) returns (ProcessStatus);
}
message Empty {}
message ProcessStatus {
bool running = 1;
int64 pid = 2;
bool managed = 3;
string executable = 4;
string working_directory = 5;
string detail = 6;
int32 last_exit_code = 7;
}
message ConfigPath { string path = 1; }
message ConfigList { repeated string paths = 1; }
message ConfigFile {
string path = 1;
string text = 2;
// Opaque revision returned by ReadConfig; required for optimistic writes.
string revision = 3;
}
message Validation { bool valid = 1; string detail = 2; }
message ProcessRequest {
enum Action { UNSPECIFIED = 0; START = 1; STOP = 2; RESTART = 3; }
Action action = 1;
}

109
scripts/start_hardware.sh Executable file
View File

@ -0,0 +1,109 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
CAN=1; EC=1; CHECK=0; RECONFIGURE=0
BITRATE="${CAN_BITRATE:-1000000}"
IFACE=""; CAN_IFACES=()
IGH_ROOT="${IGH_ROOT:-$ROOT/dependency/x86/third_party/ethercat/v1.7.0}"
CONF="${ETHERCAT_CONF:-$IGH_ROOT/etc/ethercat.conf}"
usage(){ cat <<'EOF'
Usage: scripts/start_hardware.sh --ethercat-iface IFACE [--can-iface can0 ...]
[--bitrate 1000000] [--can-only|--ethercat-only] [--check] [--reconfigure-can]
scripts/start_hardware.sh --can-only [--can-iface can0 ...] [--check]
--check only checks prerequisites and prints the plan; no sudo or changes.
Without --can-iface, select existing CAN interfaces. Default bitrate: 1000000.
EtherCAT requires --ethercat-iface on every invocation, including --check.
No interface is selected from configuration or environment. Normal execution needs sudo.
No motor enable or motion commands are issued.
EOF
}
while (( $# )); do
case "$1" in
--ethercat-iface) [[ $# -ge 2 ]] || exit 2; IFACE="$2"; shift 2;;
--can-iface) [[ $# -ge 2 ]] || exit 2; CAN_IFACES+=("$2"); shift 2;;
--bitrate) [[ $# -ge 2 ]] || exit 2; BITRATE="$2"; shift 2;;
--can-only) EC=0; shift;;
--ethercat-only) CAN=0; shift;;
--check) CHECK=1; shift;;
--reconfigure-can) RECONFIGURE=1; shift;;
--help|-h) usage; exit 0;;
*) usage >&2; exit 2;;
esac
done
(( CAN || EC )) || { echo 'Select at least one bus.' >&2; exit 2; }
if (( EC )) && [[ -z "$IFACE" ]]; then
echo 'EtherCAT: --ethercat-iface IFACE is required (for example --ethercat-iface enp2s0).' >&2
exit 2
fi
[[ "$BITRATE" =~ ^[0-9]{1,8}$ ]] && (( 10#$BITRATE > 0 )) || { echo 'Invalid CAN bitrate' >&2; exit 2; }
for command in ip python3 modinfo; do command -v "$command" >/dev/null || { echo "Missing command: $command" >&2; exit 1; }; done
if (( CAN && ${#CAN_IFACES[@]} == 0 )); then
for path in /sys/class/net/*; do
if [[ "$(cat "$path/type")" == 280 ]]; then CAN_IFACES+=("${path##*/}"); fi
done
fi
failed=0
if (( CAN )); then
if (( ${#CAN_IFACES[@]} == 0 )); then
echo 'CAN: no CAN interface detected. Check the adapter and driver; no interface was created or marked ready.' >&2
failed=1
fi
for interface in "${CAN_IFACES[@]}"; do
if [[ ! -f "/sys/class/net/$interface/type" ]] || [[ "$(cat "/sys/class/net/$interface/type")" != 280 ]]; then
echo "CAN: not a CAN interface: $interface" >&2; failed=1
else echo "CAN plan: $interface, bitrate=$BITRATE"; fi
done
fi
if (( EC )); then
if [[ -z "$IFACE" || ! "$IFACE" =~ ^[[:alnum:]_.:-]+$ || ! -d "/sys/class/net/$IFACE" ]]; then
echo 'EtherCAT: specify an existing dedicated Ethernet port using --ethercat-iface.' >&2; failed=1
elif [[ "$IFACE" == lo || -d "/sys/class/net/$IFACE/wireless" ]] || ip route show default | grep -qE " dev $IFACE( |$)" || [[ -n "$(ip -o addr show dev "$IFACE" scope global)" ]]; then
echo "EtherCAT: $IFACE carries normal networking; refusing to disconnect or flush it." >&2; failed=1
else
echo "EtherCAT plan: $IFACE, MAC=$(cat "/sys/class/net/$IFACE/address"), existing config=$CONF"
if [[ "$(cat "/sys/class/net/$IFACE/carrier" 2>/dev/null || echo 0)" != 1 ]]; then
echo "EtherCAT: $IFACE has no link; a connected slave cannot be verified." >&2
fi
fi
for module in ec_master ec_igc; do
modinfo "$module" >/dev/null 2>&1 || { echo "EtherCAT: missing kernel module $module" >&2; failed=1; }
done
[[ -x "$IGH_ROOT/sbin/ethercatctl" && -x "$IGH_ROOT/bin/ethercat" ]] || { echo "EtherCAT: incomplete IgH tools in $IGH_ROOT" >&2; failed=1; }
fi
(( failed == 0 )) || exit 1
(( CHECK == 0 )) || { echo 'Prerequisite checks passed; no changes made.'; exit 0; }
if (( EUID != 0 )); then
args=(); (( CAN )) || args+=(--ethercat-only); (( EC )) || args+=(--can-only)
[[ -z "$IFACE" ]] || args+=(--ethercat-iface "$IFACE")
for interface in "${CAN_IFACES[@]}"; do args+=(--can-iface "$interface"); done
(( RECONFIGURE == 0 )) || args+=(--reconfigure-can)
exec sudo env "IGH_ROOT=$IGH_ROOT" "ETHERCAT_CONF=$CONF" bash "$ROOT/scripts/start_hardware.sh" "${args[@]}" --bitrate "$BITRATE"
fi
# Do not reinitialize a bus while the application may be using it.
if pgrep -x cmvr_es >/dev/null; then echo 'Stop cmvr_es through its manager before initializing hardware.' >&2; exit 1; fi
if (( CAN )); then
modprobe can; modprobe can_raw
for interface in "${CAN_IFACES[@]}"; do
read -r up current_rate < <(ip -details -json link show dev "$interface" | python3 -c 'import sys,json; d=json.load(sys.stdin)[0]; print(int("UP" in d.get("flags",[])),d.get("linkinfo",{}).get("info_data",{}).get("bitrate",0))')
if (( up )); then
if [[ "$current_rate" == "$BITRATE" ]]; then echo "CAN: $interface already up at $BITRATE; kept running."; continue; fi
(( RECONFIGURE )) || { echo "CAN: $interface already up at $current_rate; use --reconfigure-can to change bitrate." >&2; exit 1; }
ip link set dev "$interface" down
fi
ip link set dev "$interface" type can bitrate "$BITRATE"
ip link set dev "$interface" up
echo "CAN: $interface started, bitrate=$BITRATE"
done
fi
if (( EC )); then
mac="$(cat "/sys/class/net/$IFACE/address")"
if [[ -e /dev/EtherCAT0 ]] && "$IGH_ROOT/bin/ethercat" master 2>/dev/null | grep -qi "$mac"; then
echo "EtherCAT: master already uses $IFACE; kept running."
else
IGH_ROOT="$IGH_ROOT" ETHERCAT_CONF="$CONF" DEVICE_MODULES=igc bash "$ROOT/scripts/ethercat/start_ethercat.sh" "$IFACE"
fi
[[ -e /dev/EtherCAT0 ]] || { echo 'EtherCAT: /dev/EtherCAT0 was not created.' >&2; exit 1; }
"$IGH_ROOT/bin/ethercat" master
"$IGH_ROOT/bin/ethercat" slaves
fi