SMACC2
Loading...
Searching...
No Matches
cp_micro_ros_agent.cpp
Go to the documentation of this file.
1// Copyright 2025 Robosoft Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
16
17#include <errno.h>
18#include <fcntl.h>
19#include <signal.h>
20#include <sys/prctl.h>
21#include <sys/types.h>
22#include <sys/wait.h>
23#include <time.h>
24#include <unistd.h>
25#include <chrono>
26#include <system_error>
27#include <thread>
28
29namespace cl_px4_mr
30{
31namespace
32{
33// Reaps the group leader and returns true once no process of the group is left.
34bool waitForGroupExit(pid_t group, bool & leaderReaped, std::chrono::milliseconds limit)
35{
36 const auto deadline = std::chrono::steady_clock::now() + limit;
37 while (true)
38 {
39 if (!leaderReaped)
40 {
41 int status = 0;
42 const pid_t result = waitpid(group, &status, WNOHANG);
43 leaderReaped = result == group || (result == -1 && errno == ECHILD);
44 }
45 if (leaderReaped && kill(-group, 0) == -1 && errno == ESRCH) return true;
46 if (std::chrono::steady_clock::now() >= deadline) return false;
47 std::this_thread::sleep_for(std::chrono::milliseconds(20));
48 }
49}
50
51// Body of the watchdog process: stops the agent's group when the state machine dies without
52// running shutdown(). Runs after fork() in a threaded process, so async-signal-safe calls only.
53[[noreturn]] void runWatchdog(const int * lifePipe, pid_t group)
54{
55 const int lifeFd = lifePipe[0];
56 for (const int sig : {SIGINT, SIGTERM, SIGHUP, SIGQUIT}) signal(sig, SIG_IGN);
57 prctl(PR_SET_NAME, "cp_agent_watch");
58 if (lifeFd > 0) close_range(0, lifeFd - 1, 0);
59 close_range(lifeFd + 1, ~0U, 0);
60
61 // The state machine holds the only write end; end of file means that process is gone
62 char byte = 0;
63 ssize_t count = 0;
64 do
65 {
66 count = read(lifeFd, &byte, 1);
67 } while (count != 0 && !(count == -1 && errno != EINTR));
68
69 kill(-group, SIGTERM);
70 const timespec step{0, 20000000L};
71 for (int i = 0; i < 100 && !(kill(-group, 0) == -1 && errno == ESRCH); ++i)
72 {
73 nanosleep(&step, nullptr);
74 }
75 kill(-group, SIGKILL);
76 _exit(0);
77}
78} // namespace
79
80CpMicroRosAgent::CpMicroRosAgent(std::string command, std::string nodeName)
81: command_(std::move(command)), nodeName_(std::move(nodeName))
82{
83}
84
86
88{
89 std::lock_guard<std::mutex> lock(mutex_);
90
91 if (launched_)
92 {
93 RCLCPP_INFO(getLogger(), "CpMicroRosAgent: already launched, skipping");
94 return;
95 }
96
97 RCLCPP_INFO(getLogger(), "CpMicroRosAgent: launching '%s'", command_.c_str());
98
99 int pipefd[2];
100 if (pipe(pipefd) == -1)
101 {
102 RCLCPP_ERROR(
103 getLogger(), "CpMicroRosAgent: pipe() failed: %s",
104 std::system_category().message(errno).c_str());
105 return;
106 }
107
108 // Held open by this process only; the watchdog reads its other end
109 int lifefd[2];
110 if (pipe2(lifefd, O_CLOEXEC) == -1)
111 {
112 RCLCPP_ERROR(
113 getLogger(), "CpMicroRosAgent: pipe2() failed: %s",
114 std::system_category().message(errno).c_str());
115 close(pipefd[0]);
116 close(pipefd[1]);
117 return;
118 }
119
120 pid_t pid = fork();
121
122 if (pid == 0)
123 {
124 // Child process: its own process group, so shutdown() can signal the shell and all it starts
125 setpgid(0, 0);
126 dup2(pipefd[1], STDOUT_FILENO);
127 dup2(pipefd[1], STDERR_FILENO);
128 // The agent keeps none of this process's descriptors (sockets, DDS shared memory, the pipe)
129 close_range(3, ~0U, 0);
130
131 execl("/bin/sh", "/bin/sh", "-c", command_.c_str(), nullptr);
132
133 // If execl returns, it failed
134 _exit(1);
135 }
136 else if (pid > 0)
137 {
138 // Parent process
139 close(pipefd[1]);
140 setpgid(pid, pid); // also here, so the group exists whichever process runs first
141 agentPid_ = pid;
142 pipeFd_ = pipefd[0];
143
144 // A second child that outlives a crash or SIGKILL of this process and then stops the agent
145 watchdogPid_ = fork();
146 if (watchdogPid_ == 0) runWatchdog(lifefd, pid);
147 close(lifefd[0]);
148 if (watchdogPid_ > 0)
149 {
150 lifeFd_ = lifefd[1];
151 }
152 else
153 {
154 RCLCPP_WARN(
155 getLogger(), "CpMicroRosAgent: no watchdog, fork() failed: %s",
156 std::system_category().message(errno).c_str());
157 close(lifefd[1]);
158 }
159
160 // Set pipe to non-blocking
161 int flags = fcntl(pipeFd_, F_GETFL, 0);
162 fcntl(pipeFd_, F_SETFL, flags | O_NONBLOCK);
163
164 // Reader thread draining the pipe (prevents buffer fill); joined in shutdown()
165 shutdownRequested_ = false;
166 readerThread_ = std::thread(
167 [this]()
168 {
169 char buf[256];
170 while (!shutdownRequested_)
171 {
172 ssize_t n = read(pipeFd_, buf, sizeof(buf) - 1);
173 if (n > 0)
174 {
175 buf[n] = '\0';
176 RCLCPP_DEBUG(getLogger(), "[micro_ros_agent] %s", buf);
177 }
178 else
179 {
180 std::this_thread::sleep_for(std::chrono::milliseconds(100));
181 }
182 }
183 });
184
185 launched_ = true;
186 RCLCPP_INFO(getLogger(), "CpMicroRosAgent: launched with PID %d", agentPid_);
187 }
188 else
189 {
190 RCLCPP_ERROR(
191 getLogger(), "CpMicroRosAgent: fork() failed: %s",
192 std::system_category().message(errno).c_str());
193 close(pipefd[0]);
194 close(pipefd[1]);
195 close(lifefd[0]);
196 close(lifefd[1]);
197 }
198}
199
201{
202 std::lock_guard<std::mutex> lock(mutex_);
203
204 // The reader checks the flag every 100 ms, so the join is bounded; it must happen before the
205 // pipe is closed and before this object is destroyed.
206 shutdownRequested_ = true;
207 if (readerThread_.joinable())
208 {
209 readerThread_.join();
210 }
211
212 if (agentPid_ <= 0)
213 {
214 return;
215 }
216
217 RCLCPP_INFO(getLogger(), "CpMicroRosAgent: shutting down agent (PID %d)", agentPid_);
218
219 // SIGTERM to the whole group, SIGKILL to whatever is left after two seconds
220 bool leaderReaped = false;
221 kill(-agentPid_, SIGTERM);
222 if (!waitForGroupExit(agentPid_, leaderReaped, std::chrono::seconds(2)))
223 {
224 RCLCPP_WARN(getLogger(), "CpMicroRosAgent: agent still running after SIGTERM, sending SIGKILL");
225 kill(-agentPid_, SIGKILL);
226 if (!waitForGroupExit(agentPid_, leaderReaped, std::chrono::seconds(2)))
227 {
228 RCLCPP_ERROR(
229 getLogger(), "CpMicroRosAgent: process group %d still exists after SIGKILL", agentPid_);
230 }
231 }
232
233 // The agent is stopped, so the watchdog has nothing left to do
234 if (watchdogPid_ > 0)
235 {
236 kill(watchdogPid_, SIGKILL);
237 waitpid(watchdogPid_, nullptr, 0);
238 watchdogPid_ = -1;
239 }
240 if (lifeFd_ >= 0)
241 {
242 close(lifeFd_);
243 lifeFd_ = -1;
244 }
245
246 // Close pipe
247 if (pipeFd_ >= 0)
248 {
249 close(pipeFd_);
250 pipeFd_ = -1;
251 }
252
253 agentPid_ = -1;
254 launched_ = false;
255
256 RCLCPP_INFO(getLogger(), "CpMicroRosAgent: shutdown complete");
257}
258
260
262{
263 std::lock_guard<std::mutex> lock(mutex_);
264 return agentPid_;
265}
266
267std::string CpMicroRosAgent::getNodeName() const { return nodeName_; }
268
269} // namespace cl_px4_mr
CpMicroRosAgent(std::string command="ros2 run micro_ros_agent micro_ros_agent udp4 -p 8888 2>&1 | tee /tmp/xrce_agent.log", std::string nodeName="/px4_micro_xrce_dds")
std::atomic< bool > shutdownRequested_
rclcpp::Logger getLogger() const
bool waitForGroupExit(pid_t group, bool &leaderReaped, std::chrono::milliseconds limit)