From dcc85c28f474d66127cbcbecb549657a14e3ed25 Mon Sep 17 00:00:00 2001 From: xtkuang <87661715@qq.com> Date: Fri, 4 Dec 2026 13:47:05 +0800 Subject: [PATCH] feat(management): add independent configuration and process manager --- CMakeLists.txt | 14 +- cmvr-es/management/CMakeLists.txt | 22 +++ cmvr-es/management/README.md | 109 +++++++++++++ cmvr-es/management/manager_ctl.cpp | 23 +++ cmvr-es/management/manager_main.cpp | 223 +++++++++++++++++++++++++++ cmvr-es/management/manager_test.cpp | 48 ++++++ cmvr-es/management/start_all.sh | 38 +++++ cmvr-es/management/test_manager.py | 20 +++ protos/cmvr/management/manager.proto | 35 +++++ scripts/start_hardware.sh | 109 +++++++++++++ 10 files changed, 637 insertions(+), 4 deletions(-) create mode 100644 cmvr-es/management/CMakeLists.txt create mode 100644 cmvr-es/management/README.md create mode 100644 cmvr-es/management/manager_ctl.cpp create mode 100644 cmvr-es/management/manager_main.cpp create mode 100644 cmvr-es/management/manager_test.cpp create mode 100755 cmvr-es/management/start_all.sh create mode 100644 cmvr-es/management/test_manager.py create mode 100644 protos/cmvr/management/manager.proto create mode 100755 scripts/start_hardware.sh diff --git a/CMakeLists.txt b/CMakeLists.txt index ba3ddc0e..0b4d40ae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) \ No newline at end of file diff --git a/cmvr-es/management/CMakeLists.txt b/cmvr-es/management/CMakeLists.txt new file mode 100644 index 00000000..10a1e626 --- /dev/null +++ b/cmvr-es/management/CMakeLists.txt @@ -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") diff --git a/cmvr-es/management/README.md b/cmvr-es/management/README.md new file mode 100644 index 00000000..cfa6cd7d --- /dev/null +++ b/cmvr-es/management/README.md @@ -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. diff --git a/cmvr-es/management/manager_ctl.cpp b/cmvr-es/management/manager_ctl.cpp new file mode 100644 index 00000000..3e7e0c3e --- /dev/null +++ b/cmvr-es/management/manager_ctl.cpp @@ -0,0 +1,23 @@ +#include "cmvr/management/manager.grpc.pb.h" +#include +#include +#include +#include +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;iGetStatus(&query,api::Empty(),&status); + if(!result.ok()){std::cerr<Control(&context,request,&status); + if(!result.ok()){std::cerr< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +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(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< 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 parse(const std::string& text,std::string& error) { + std::string candidateError; + for(auto* type:types_){ + std::unique_ptr message(factory_.GetPrototype(type)->New()); + ParseErrors errors;google::protobuf::TextFormat::Parser parser;parser.RecordErrorsTo(&errors); + if(parser.ParseFromString(text,message.get())){ + std::vector fields; + message->GetReflection()->ListFields(*message,&fields); + if(!fields.empty())return message; + } + for(int i=0;ifield_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 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;iis_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;imessage_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 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 lock(mutex_); + try{std::vector 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 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 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 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(offsettext().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(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 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 +#include +#include +#include +#include +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();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="<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="<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<&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 &- & + 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.' diff --git a/cmvr-es/management/test_manager.py b/cmvr-es/management/test_manager.py new file mode 100644 index 00000000..15edda17 --- /dev/null +++ b/cmvr-es/management/test_manager.py @@ -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()) diff --git a/protos/cmvr/management/manager.proto b/protos/cmvr/management/manager.proto new file mode 100644 index 00000000..c7666d59 --- /dev/null +++ b/protos/cmvr/management/manager.proto @@ -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; +} diff --git a/scripts/start_hardware.sh b/scripts/start_hardware.sh new file mode 100755 index 00000000..f642b710 --- /dev/null +++ b/scripts/start_hardware.sh @@ -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