SMACC2
Loading...
Searching...
No Matches
smacc_client_async_behavior.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
15/*****************************************************************************************************************
16 *
17 * Authors: Pablo Inigo Blasco, Brett Aldrich
18 *
19 ******************************************************************************************************************/
20
23
24using namespace std::chrono_literals;
25
26namespace smacc2
27{
28namespace
29{
31{
32 std::string state, orthogonal, behavior;
33};
34
35// Emits the start tracepoint when built and the end tracepoint when destroyed, also on an exception.
37{
38 AsyncTraceScope(bool entry, const AsyncTraceNames & names) : entry_(entry), names_(names)
39 {
40 if (entry_)
41 {
42 TRACETOOLS_TRACEPOINT(
44 names_.orthogonal.c_str(), names_.behavior.c_str());
45 }
46 else
47 {
48 TRACETOOLS_TRACEPOINT(
49 smacc2_client_behavior_async_on_exit_start, names_.state.c_str(), names_.orthogonal.c_str(),
50 names_.behavior.c_str());
51 }
52 }
54 {
55 if (entry_)
56 {
57 TRACETOOLS_TRACEPOINT(
58 smacc2_client_behavior_async_on_entry_end, names_.state.c_str(), names_.orthogonal.c_str(),
59 names_.behavior.c_str());
60 }
61 else
62 {
63 TRACETOOLS_TRACEPOINT(
64 smacc2_client_behavior_async_on_exit_end, names_.state.c_str(), names_.orthogonal.c_str(),
65 names_.behavior.c_str());
66 }
67 }
68 bool entry_;
70};
71} // namespace
72
73// A behavior thread that ended by exception: at shutdown the usual cause is the behavior's own rclcpp
74// sleep or graph call on the shut-down context and is expected; while ROS is up it is an error.
76 const rclcpp::Logger & logger, const std::string & name, const char * thread, const char * what)
77{
78 if (rclcpp::ok())
79 {
80 RCLCPP_ERROR_STREAM(
81 logger, "[" << name << "] " << thread << " thread ended by exception: " << what);
82 }
83 else
84 {
85 RCLCPP_INFO_STREAM(
86 logger, "[" << name << "] " << thread << " thread ended by exception at shutdown: " << what);
87 }
88}
89
91{
92 RCLCPP_INFO_STREAM(getLogger(), "[" << getName() << "] asynchronous onEntry thread started");
93 // Copied here, on the state machine thread: the behavior's thread must not ask an exiting state.
94 const AsyncTraceNames names{getTraceStateName(), getTraceOrthogonalName(), getName()};
95 this->onEntryThread_ = std::async(
96 std::launch::async,
97 [this, names]
98 {
99 // An exception is reported when it happens, not when the state exits and joins this thread.
100 try
101 {
102 AsyncTraceScope trace(true, names);
103 this->onEntry();
104 }
105 catch (const std::exception & e)
106 {
107 logThreadException(getLogger(), getName(), "onEntry", e.what());
108 if (rclcpp::ok()) this->postInitializationFailureEvent(e.what());
109 return 0;
110 }
111 catch (...)
112 {
113 logThreadException(getLogger(), getName(), "onEntry", "non-standard exception");
114 if (rclcpp::ok()) this->postInitializationFailureEvent("non-standard exception");
115 return 0;
116 }
117 this->postFinishEventFn_();
118 RCLCPP_INFO_STREAM(getLogger(), "[" << getName() << "] asynchronous onEntry thread finished");
119 return 0;
120 });
121}
122
124 std::optional<std::future<int>> & threadfut, bool requestFinish)
125{
126 if (!threadfut || !threadfut->valid())
127 {
128 RCLCPP_DEBUG_STREAM(
129 getLogger(),
130 "[" << getName() << "] onEntry thread not created or already joined. Skipping wait.");
131 return;
132 }
133
134 try
135 {
136 // Never stops at rclcpp shutdown: the thread must be joined before this object is released.
137 while (true)
138 {
139 // A thread that has already returned needs no finish request (the future stays valid until
140 // consumed here); without this check shutdown logged a FATAL requestForceFinish for it.
141 if (threadfut->wait_for(std::chrono::seconds(0)) == std::future_status::ready)
142 {
143 threadfut->get();
144 break;
145 }
146
147 if (requestFinish && !rclcpp::ok())
148 {
150 }
151
152 auto status = threadfut->wait_for(std::chrono::milliseconds(20));
153 if (status == std::future_status::ready)
154 {
155 threadfut->get();
156 break;
157 }
158
159 RCLCPP_INFO_STREAM(
160 getLogger(),
161 "[" << getName()
162 << "] fut valid but waiting for asynchronous onEntry thread to finish: state: "
163 << (int)status);
164
165 rclcpp::sleep_for(100ms);
166 RCLCPP_WARN_THROTTLE(
167 getLogger(), *(getNode()->get_clock()), 1000,
168 "[%s] waiting for finishing client behavior, before leaving the state. Is the client "
169 "behavior stuck? requesting force finish",
170 this->getName().c_str());
171
172 if (requestFinish) requestForceFinish();
173 }
174 }
175 catch (const std::exception & e)
176 {
177 logThreadException(getLogger(), getName(), "onEntry", e.what());
178 }
179 catch (...)
180 {
181 logThreadException(getLogger(), getName(), "onEntry", "non-standard exception");
182 }
183}
184
186{
187 waitFutureIfNotFinished(this->onEntryThread_, requestFinish);
188}
189
191{
192 RCLCPP_INFO_STREAM(getLogger(), "[" << getName() << "] onExit - join async onEntry thread");
193 this->waitOnEntryThread(true);
194
195 RCLCPP_INFO_STREAM(
196 getLogger(), "[" << getName() << "] onExit - Creating asynchronous onExit thread");
197 const AsyncTraceNames names{getTraceStateName(), getTraceOrthogonalName(), getName()};
198 this->onExitThread_ = std::async(
199 std::launch::async,
200 [this, names]
201 {
202 {
203 AsyncTraceScope trace(false, names);
204 this->onExit();
205 }
206 RCLCPP_INFO_STREAM(getLogger(), "[" << getName() << "] asynchronous onExit done.");
207 return 0;
208 });
209}
210
212{
213 RCLCPP_DEBUG_STREAM(
214 getLogger(), "[" << getName()
215 << "] Destroying client behavior- Waiting finishing of asynchronous onExit "
216 "thread");
217 try
218 {
219 if (this->onExitThread_)
220 {
221 this->onExitThread_->get();
222 }
223 }
224 catch (const std::exception & e)
225 {
226 logThreadException(getLogger(), getName(), "onExit", e.what());
227 }
228 catch (...)
229 {
230 logThreadException(getLogger(), getName(), "onExit", "non-standard exception");
231 }
232
233 // Backstop: no behavior may be released with its onEntry thread live.
234 this->waitOnEntryThread(true);
235
236 RCLCPP_DEBUG_STREAM(
237 getLogger(), "[" << getName()
238 << "] Destroying client behavior- onExit thread finished. Proccedding "
239 "destruction.");
240}
241
243{
244 // Last line of defense: every release path joins the threads first; if one is missed, join here
245 // before the members the thread uses are destroyed, rather than let ~future block after them.
246 if (this->onEntryThread_ && this->onEntryThread_->valid())
247 {
248 RCLCPP_ERROR_STREAM(
249 getLogger(), "[" << getName() << "] destroyed with a live onEntry thread; joining it");
250 this->waitOnEntryThread(true);
251 }
252 if (this->onExitThread_ && this->onExitThread_->valid())
253 {
254 RCLCPP_ERROR_STREAM(
255 getLogger(), "[" << getName() << "] destroyed with a live onExit thread; joining it");
256 try
257 {
258 this->onExitThread_->get();
259 }
260 catch (const std::exception & e)
261 {
262 RCLCPP_ERROR_STREAM(getLogger(), "[" << getName() << "] onExit thread threw: " << e.what());
263 }
264 catch (...)
265 {
266 RCLCPP_ERROR_STREAM(
267 getLogger(), "[" << getName() << "] onExit thread threw a non-standard exception");
268 }
269 }
270}
271
273
275
277{
278 RCLCPP_FATAL_STREAM_THROTTLE(
279 getLogger(), *(getNode()->get_clock()), 1000,
280 "[" << getName() << "] " << static_cast<const void *>(this) << " requestForceFinish");
282}
283
285
286} // namespace smacc2
virtual rclcpp::Logger getLogger() const
void postInitializationFailureEvent(const std::string &what)
virtual rclcpp::Node::SharedPtr getNode() const
bool isShutdownRequested()
onEntry is executed in a new thread. However the current state cannot be left until the onEntry threa...
std::optional< std::future< int > > onExitThread_
std::optional< std::future< int > > onEntryThread_
void waitFutureIfNotFinished(std::optional< std::future< int > > &threadfut, bool requestFinish)
static void logThreadException(const rclcpp::Logger &logger, const std::string &name, const char *thread, const char *what)
smacc2_client_behavior_async_on_entry_start
smacc2_client_behavior_async_on_exit_start
smacc2_client_behavior_async_on_entry_end
smacc2_client_behavior_async_on_exit_end