ROS 2 rclcpp + rcl - humble  humble
ROS 2 C++ Client Library with ROS Client Library
context.cpp
1 // Copyright 2015-2020 Open Source Robotics Foundation, 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 #include "rclcpp/context.hpp"
16 
17 #include <memory>
18 #include <mutex>
19 #include <sstream>
20 #include <string>
21 #include <vector>
22 #include <unordered_set>
23 #include <utility>
24 
25 #include "rcl/init.h"
26 #include "rcl/logging.h"
27 
28 #include "rclcpp/detail/utilities.hpp"
29 #include "rclcpp/exceptions.hpp"
30 #include "rclcpp/logging.hpp"
31 #include "rclcpp/graph_listener.hpp"
32 #include "rcpputils/scope_exit.hpp"
33 #include "rcutils/error_handling.h"
34 #include "rcutils/macros.h"
35 
36 #include "./logging_mutex.hpp"
37 
38 using rclcpp::Context;
39 
40 namespace rclcpp
41 {
44 {
45 public:
46  RCLCPP_SMART_PTR_DEFINITIONS(WeakContextsWrapper)
47 
48  void
49  add_context(const Context::SharedPtr & context)
50  {
51  std::lock_guard<std::mutex> guard(mutex_);
52  weak_contexts_.push_back(context);
53  }
54 
55  void
56  remove_context(const Context * context)
57  {
58  std::lock_guard<std::mutex> guard(mutex_);
59  weak_contexts_.erase(
60  std::remove_if(
61  weak_contexts_.begin(),
62  weak_contexts_.end(),
63  [context](const Context::WeakPtr weak_context) {
64  auto locked_context = weak_context.lock();
65  if (!locked_context) {
66  // take advantage and removed expired contexts
67  return true;
68  }
69  return locked_context.get() == context;
70  }
71  ),
72  weak_contexts_.end());
73  }
74 
75  std::vector<Context::SharedPtr>
76  get_contexts()
77  {
78  std::lock_guard<std::mutex> lock(mutex_);
79  std::vector<Context::SharedPtr> shared_contexts;
80  for (auto it = weak_contexts_.begin(); it != weak_contexts_.end(); /* noop */) {
81  auto context_ptr = it->lock();
82  if (!context_ptr) {
83  // remove invalid weak context pointers
84  it = weak_contexts_.erase(it);
85  } else {
86  ++it;
87  shared_contexts.push_back(context_ptr);
88  }
89  }
90  return shared_contexts;
91  }
92 
93 private:
94  std::vector<std::weak_ptr<rclcpp::Context>> weak_contexts_;
95  std::mutex mutex_;
96 };
97 } // namespace rclcpp
98 
100 
102 static
103 WeakContextsWrapper::SharedPtr
104 get_weak_contexts()
105 {
106  static WeakContextsWrapper::SharedPtr weak_contexts = WeakContextsWrapper::make_shared();
107  if (!weak_contexts) {
108  throw std::runtime_error("weak contexts vector is not valid");
109  }
110  return weak_contexts;
111 }
112 
114 static
115 size_t &
116 get_logging_reference_count()
117 {
118  static size_t ref_count = 0;
119  return ref_count;
120 }
121 
122 extern "C"
123 {
124 static
125 void
126 rclcpp_logging_output_handler(
127  const rcutils_log_location_t * location,
128  int severity, const char * name, rcutils_time_point_value_t timestamp,
129  const char * format, va_list * args)
130 {
131  try {
132  std::shared_ptr<std::recursive_mutex> logging_mutex;
133  logging_mutex = get_global_logging_mutex();
134  std::lock_guard<std::recursive_mutex> guard(*logging_mutex);
136  location, severity, name, timestamp, format, args);
137  } catch (std::exception & ex) {
138  RCUTILS_SAFE_FWRITE_TO_STDERR(ex.what());
139  RCUTILS_SAFE_FWRITE_TO_STDERR("\n");
140  } catch (...) {
141  RCUTILS_SAFE_FWRITE_TO_STDERR("failed to take global rclcpp logging mutex\n");
142  }
143 }
144 } // extern "C"
145 
146 Context::Context()
147 : rcl_context_(nullptr),
148  shutdown_reason_(""),
149  logging_mutex_(nullptr)
150 {}
151 
152 Context::~Context()
153 {
154  // acquire the init lock to prevent race conditions with init and shutdown
155  // this will not prevent errors, but will maybe make them easier to reproduce
156  std::lock_guard<std::recursive_mutex> lock(init_mutex_);
157  try {
158  this->shutdown("context destructor was called while still not shutdown");
159  // at this point it is shutdown and cannot reinit
160  // clean_up will finalize the rcl context
161  this->clean_up();
162  } catch (const std::exception & exc) {
163  RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "unhandled exception in ~Context(): %s", exc.what());
164  } catch (...) {
165  RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "unhandled exception in ~Context()");
166  }
167 }
168 
169 RCLCPP_LOCAL
170 void
171 __delete_context(rcl_context_t * context)
172 {
173  if (context) {
174  if (rcl_context_is_valid(context)) {
175  RCLCPP_ERROR(
176  rclcpp::get_logger("rclcpp"), "rcl context unexpectedly not shutdown during cleanup");
177  } else {
178  // if context pointer is not null and is shutdown, then it's ready for fini
179  rcl_ret_t ret = rcl_context_fini(context);
180  if (RCL_RET_OK != ret) {
181  RCLCPP_ERROR(
182  rclcpp::get_logger("rclcpp"),
183  "failed to finalize context: %s", rcl_get_error_string().str);
184  rcl_reset_error();
185  }
186  }
187  delete context;
188  }
189 }
190 
191 void
193  int argc,
194  char const * const * argv,
195  const rclcpp::InitOptions & init_options)
196 {
197  std::lock_guard<std::recursive_mutex> init_lock(init_mutex_);
198  if (this->is_valid()) {
200  }
201  this->clean_up();
202  rcl_context_t * context = new rcl_context_t;
203  if (!context) {
204  throw std::runtime_error("failed to allocate memory for rcl context");
205  }
207  rcl_ret_t ret = rcl_init(argc, argv, init_options.get_rcl_init_options(), context);
208  if (RCL_RET_OK != ret) {
209  delete context;
210  rclcpp::exceptions::throw_from_rcl_error(ret, "failed to initialize rcl");
211  }
212  rcl_context_.reset(context, __delete_context);
213 
214  if (init_options.auto_initialize_logging()) {
215  logging_mutex_ = get_global_logging_mutex();
216  std::lock_guard<std::recursive_mutex> guard(*logging_mutex_);
217  size_t & count = get_logging_reference_count();
218  if (0u == count) {
220  &rcl_context_->global_arguments,
222  rclcpp_logging_output_handler);
223  if (RCL_RET_OK != ret) {
224  rcl_context_.reset();
225  rclcpp::exceptions::throw_from_rcl_error(ret, "failed to configure logging");
226  }
227  } else {
228  RCLCPP_WARN(
229  rclcpp::get_logger("rclcpp"),
230  "logging was initialized more than once");
231  }
232  ++count;
233  }
234 
235  try {
236  std::vector<std::string> unparsed_ros_arguments = detail::get_unparsed_ros_arguments(
237  argc, argv, &(rcl_context_->global_arguments), rcl_get_default_allocator());
238  if (!unparsed_ros_arguments.empty()) {
239  throw exceptions::UnknownROSArgsError(std::move(unparsed_ros_arguments));
240  }
241 
242  init_options_ = init_options;
243 
244  weak_contexts_ = get_weak_contexts();
245  weak_contexts_->add_context(this->shared_from_this());
246  } catch (const std::exception & e) {
247  ret = rcl_shutdown(rcl_context_.get());
248  rcl_context_.reset();
249  if (RCL_RET_OK != ret) {
250  std::ostringstream oss;
251  oss << "While handling: " << e.what() << std::endl <<
252  " another exception was thrown";
253  rclcpp::exceptions::throw_from_rcl_error(ret, oss.str());
254  }
255  throw;
256  }
257 }
258 
259 bool
261 {
262  // Take a local copy of the shared pointer to avoid it getting nulled under our feet.
263  auto local_rcl_context = rcl_context_;
264  if (!local_rcl_context) {
265  return false;
266  }
267  return rcl_context_is_valid(local_rcl_context.get());
268 }
269 
270 const rclcpp::InitOptions &
272 {
273  return init_options_;
274 }
275 
278 {
279  return init_options_;
280 }
281 
282 size_t
284 {
285  size_t domain_id;
286  rcl_ret_t ret = rcl_context_get_domain_id(rcl_context_.get(), &domain_id);
287  if (RCL_RET_OK != ret) {
288  rclcpp::exceptions::throw_from_rcl_error(ret, "failed to get domain id from context");
289  }
290  return domain_id;
291 }
292 
293 std::string
295 {
296  std::lock_guard<std::recursive_mutex> lock(init_mutex_);
297  return shutdown_reason_;
298 }
299 
301 
315 static thread_local std::unordered_set<const Context *> g_contexts_in_shutdown;
316 
317 bool
318 Context::shutdown(const std::string & reason)
319 {
320  // prevent races
321  std::lock_guard<std::recursive_mutex> init_lock(init_mutex_);
322  // ensure validity
323  if (!this->is_valid()) {
324  // if it is not valid, then it cannot be shutdown
325  return false;
326  }
327  // prevent reentrant calls, e.g. from a pre_shutdown callback
328  if (!g_contexts_in_shutdown.insert(this).second) {
329  // shutdown of this context is already in progress on this thread
330  return false;
331  }
332  RCPPUTILS_SCOPE_EXIT(g_contexts_in_shutdown.erase(this); );
333 
334  // call each pre-shutdown callback
335  {
336  std::lock_guard<std::mutex> lock{pre_shutdown_callbacks_mutex_};
337  for (const auto & callback : pre_shutdown_callbacks_) {
338  (*callback)();
339  }
340  }
341 
342  // rcl shutdown
343  rcl_ret_t ret = rcl_shutdown(rcl_context_.get());
344  if (RCL_RET_OK != ret) {
345  rclcpp::exceptions::throw_from_rcl_error(ret);
346  }
347  // set shutdown reason
348  shutdown_reason_ = reason;
349  // call each shutdown callback
350  {
351  std::lock_guard<std::mutex> lock(on_shutdown_callbacks_mutex_);
352  for (const auto & callback : on_shutdown_callbacks_) {
353  (*callback)();
354  }
355  }
356 
357  // interrupt all blocking sleep_for() and all blocking executors or wait sets
358  this->interrupt_all_sleep_for();
359  // remove self from the global contexts
360  weak_contexts_->remove_context(this);
361  // shutdown logger
362  if (logging_mutex_) {
363  // logging was initialized by this context
364  std::lock_guard<std::recursive_mutex> guard(*logging_mutex_);
365  size_t & count = get_logging_reference_count();
366  if (0u == --count) {
367  rcl_ret_t rcl_ret = rcl_logging_fini();
368  if (RCL_RET_OK != rcl_ret) {
369  RCUTILS_SAFE_FWRITE_TO_STDERR(
370  RCUTILS_STRINGIFY(__file__) ":"
371  RCUTILS_STRINGIFY(__LINE__)
372  " failed to fini logging");
373  rcl_reset_error();
374  }
375  }
376  }
377  return true;
378 }
379 
380 rclcpp::Context::OnShutdownCallback
381 Context::on_shutdown(OnShutdownCallback callback)
382 {
383  add_on_shutdown_callback(callback);
384  return callback;
385 }
386 
388 Context::add_on_shutdown_callback(OnShutdownCallback callback)
389 {
390  return add_shutdown_callback(ShutdownType::on_shutdown, callback);
391 }
392 
393 bool
395 {
396  return remove_shutdown_callback(ShutdownType::on_shutdown, callback_handle);
397 }
398 
400 Context::add_pre_shutdown_callback(PreShutdownCallback callback)
401 {
402  return add_shutdown_callback(ShutdownType::pre_shutdown, callback);
403 }
404 
405 bool
407  const PreShutdownCallbackHandle & callback_handle)
408 {
409  return remove_shutdown_callback(ShutdownType::pre_shutdown, callback_handle);
410 }
411 
413 Context::add_shutdown_callback(
414  ShutdownType shutdown_type,
415  ShutdownCallback callback)
416 {
417  auto callback_shared_ptr =
418  std::make_shared<ShutdownCallbackHandle::ShutdownCallbackType>(callback);
419 
420  switch (shutdown_type) {
421  case ShutdownType::pre_shutdown:
422  {
423  std::lock_guard<std::mutex> lock(pre_shutdown_callbacks_mutex_);
424  pre_shutdown_callbacks_.emplace(callback_shared_ptr);
425  }
426  break;
427  case ShutdownType::on_shutdown:
428  {
429  std::lock_guard<std::mutex> lock(on_shutdown_callbacks_mutex_);
430  on_shutdown_callbacks_.emplace(callback_shared_ptr);
431  }
432  break;
433  }
434 
435  ShutdownCallbackHandle callback_handle;
436  callback_handle.callback = callback_shared_ptr;
437  return callback_handle;
438 }
439 
440 bool
441 Context::remove_shutdown_callback(
442  ShutdownType shutdown_type,
443  const ShutdownCallbackHandle & callback_handle)
444 {
445  std::mutex * mutex_ptr = nullptr;
446  std::unordered_set<
447  std::shared_ptr<ShutdownCallbackHandle::ShutdownCallbackType>> * callback_list_ptr;
448 
449  switch (shutdown_type) {
450  case ShutdownType::pre_shutdown:
451  mutex_ptr = &pre_shutdown_callbacks_mutex_;
452  callback_list_ptr = &pre_shutdown_callbacks_;
453  break;
454  case ShutdownType::on_shutdown:
455  mutex_ptr = &on_shutdown_callbacks_mutex_;
456  callback_list_ptr = &on_shutdown_callbacks_;
457  break;
458  }
459 
460  std::lock_guard<std::mutex> lock(*mutex_ptr);
461  auto callback_shared_ptr = callback_handle.callback.lock();
462  if (callback_shared_ptr == nullptr) {
463  return false;
464  }
465  return callback_list_ptr->erase(callback_shared_ptr) == 1;
466 }
467 
468 std::vector<rclcpp::Context::OnShutdownCallback>
470 {
471  return get_shutdown_callback(ShutdownType::on_shutdown);
472 }
473 
474 std::vector<rclcpp::Context::PreShutdownCallback>
476 {
477  return get_shutdown_callback(ShutdownType::pre_shutdown);
478 }
479 
480 std::vector<rclcpp::Context::ShutdownCallback>
481 Context::get_shutdown_callback(ShutdownType shutdown_type) const
482 {
483  std::mutex * mutex_ptr = nullptr;
484  const std::unordered_set<
485  std::shared_ptr<ShutdownCallbackHandle::ShutdownCallbackType>> * callback_list_ptr;
486 
487  switch (shutdown_type) {
488  case ShutdownType::pre_shutdown:
489  mutex_ptr = &pre_shutdown_callbacks_mutex_;
490  callback_list_ptr = &pre_shutdown_callbacks_;
491  break;
492  case ShutdownType::on_shutdown:
493  mutex_ptr = &on_shutdown_callbacks_mutex_;
494  callback_list_ptr = &on_shutdown_callbacks_;
495  break;
496  }
497 
498  std::vector<rclcpp::Context::ShutdownCallback> callbacks;
499  {
500  std::lock_guard<std::mutex> lock(*mutex_ptr);
501  for (auto & iter : *callback_list_ptr) {
502  callbacks.emplace_back(*iter);
503  }
504  }
505 
506  return callbacks;
507 }
508 
509 std::shared_ptr<rcl_context_t>
511 {
512  return rcl_context_;
513 }
514 
515 bool
516 Context::sleep_for(const std::chrono::nanoseconds & nanoseconds)
517 {
518  std::chrono::nanoseconds time_left = nanoseconds;
519  do {
520  {
521  std::unique_lock<std::mutex> lock(interrupt_mutex_);
522  auto start = std::chrono::steady_clock::now();
523  // this will release the lock while waiting
524  interrupt_condition_variable_.wait_for(lock, time_left);
525  time_left -= std::chrono::steady_clock::now() - start;
526  }
527  } while (time_left > std::chrono::nanoseconds::zero() && this->is_valid());
528  // Return true if the timeout elapsed successfully, otherwise false.
529  return this->is_valid();
530 }
531 
532 void
534 {
535  interrupt_condition_variable_.notify_all();
536 }
537 
538 void
539 Context::clean_up()
540 {
541  shutdown_reason_ = "";
542  rcl_context_.reset();
543  sub_contexts_.clear();
544 }
545 
546 std::vector<Context::SharedPtr>
548 {
549  WeakContextsWrapper::SharedPtr weak_contexts = get_weak_contexts();
550  return weak_contexts->get_contexts();
551 }
#define rcl_get_default_allocator
Return a properly initialized rcl_allocator_t with default values.
Definition: allocator.h:37
Thrown when init is called on an already initialized context.
Definition: context.hpp:43
Context which encapsulates shared state between nodes and other similar entities.
Definition: context.hpp:73
virtual RCLCPP_PUBLIC void init(int argc, char const *const *argv, const rclcpp::InitOptions &init_options=rclcpp::InitOptions())
Initialize the context, and the underlying elements like the rcl context.
Definition: context.cpp:192
RCLCPP_PUBLIC std::vector< OnShutdownCallback > get_on_shutdown_callbacks() const
Return the shutdown callbacks.
Definition: context.cpp:469
RCLCPP_PUBLIC std::vector< PreShutdownCallback > get_pre_shutdown_callbacks() const
Return the pre-shutdown callbacks.
Definition: context.cpp:475
RCLCPP_PUBLIC size_t get_domain_id() const
Return actual domain id.
Definition: context.cpp:283
RCLCPP_PUBLIC std::string shutdown_reason() const
Return the shutdown reason, or empty string if not shutdown.
Definition: context.cpp:294
RCLCPP_PUBLIC const rclcpp::InitOptions & get_init_options() const
Return the init options used during init.
Definition: context.cpp:271
RCLCPP_PUBLIC bool sleep_for(const std::chrono::nanoseconds &nanoseconds)
Sleep for a given period of time or until shutdown() is called.
Definition: context.cpp:516
virtual RCLCPP_PUBLIC void interrupt_all_sleep_for()
Interrupt any blocking sleep_for calls, causing them to return immediately and return true.
Definition: context.cpp:533
virtual RCLCPP_PUBLIC OnShutdownCallback on_shutdown(OnShutdownCallback callback)
Add a on_shutdown callback to be called when shutdown is called for this context.
Definition: context.cpp:381
virtual RCLCPP_PUBLIC OnShutdownCallbackHandle add_on_shutdown_callback(OnShutdownCallback callback)
Add a on_shutdown callback to be called when shutdown is called for this context.
Definition: context.cpp:388
virtual RCLCPP_PUBLIC bool remove_pre_shutdown_callback(const PreShutdownCallbackHandle &callback_handle)
Remove an registered pre_shutdown callback.
Definition: context.cpp:406
RCLCPP_PUBLIC bool is_valid() const
Return true if the context is valid, otherwise false.
Definition: context.cpp:260
virtual RCLCPP_PUBLIC PreShutdownCallbackHandle add_pre_shutdown_callback(PreShutdownCallback callback)
Add a pre_shutdown callback to be called before shutdown is called for this context.
Definition: context.cpp:400
virtual RCLCPP_PUBLIC bool remove_on_shutdown_callback(const OnShutdownCallbackHandle &callback_handle)
Remove an registered on_shutdown callbacks.
Definition: context.cpp:394
virtual RCLCPP_PUBLIC bool shutdown(const std::string &reason)
Shutdown the context, making it uninitialized and therefore invalid for derived entities.
Definition: context.cpp:318
RCLCPP_PUBLIC std::shared_ptr< rcl_context_t > get_rcl_context()
Return the internal rcl context.
Definition: context.cpp:510
Encapsulation of options for initializing rclcpp.
RCLCPP_PUBLIC const rcl_init_options_t * get_rcl_init_options() const
Return the rcl init options.
RCLCPP_PUBLIC bool auto_initialize_logging() const
Return true if logging should be initialized when rclcpp::Context::init is called.
Class to manage vector of weak pointers to all created contexts.
Definition: context.cpp:44
Thrown when unparsed ROS specific arguments are found.
Definition: exceptions.hpp:197
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_context_fini(rcl_context_t *context)
Finalize a context.
Definition: context.c:49
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_context_get_domain_id(rcl_context_t *context, size_t *domain_id)
Returns the context domain id.
Definition: context.c:83
struct rcl_context_s rcl_context_t
Encapsulates the non-global state of an init/shutdown cycle.
RCL_PUBLIC RCL_WARN_UNUSED bool rcl_context_is_valid(const rcl_context_t *context)
Return true if the given context is currently valid, otherwise false.
Definition: context.c:94
RCL_PUBLIC RCL_WARN_UNUSED rcl_context_t rcl_get_zero_initialized_context(void)
Return a zero initialization context object.
Definition: context.c:29
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_shutdown(rcl_context_t *context)
Shutdown a given rcl context.
Definition: init.c:232
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_init(int argc, char const *const *argv, const rcl_init_options_t *options, rcl_context_t *context)
Initialization of rcl.
Definition: init.c:46
RCL_PUBLIC RCL_WARN_UNUSED const rcl_allocator_t * rcl_init_options_get_allocator(const rcl_init_options_t *init_options)
Return the allocator stored in the init_options.
Definition: init_options.c:169
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_logging_fini(void)
Definition: logging.c:125
RCL_PUBLIC void rcl_logging_multiple_output_handler(const rcutils_log_location_t *location, int severity, const char *name, rcutils_time_point_value_t timestamp, const char *format, va_list *args)
Default output handler used by rcl.
Definition: logging.c:152
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_logging_configure_with_output_handler(const rcl_arguments_t *global_args, const rcl_allocator_t *allocator, rcl_logging_output_handler_t output_handler)
Configure the logging system with the provided output handler.
Definition: logging.c:57
Versions of rosidl_typesupport_cpp::get_message_type_support_handle that handle adapted types.
RCLCPP_PUBLIC std::vector< Context::SharedPtr > get_contexts()
Return a copy of the list of context shared pointers.
Definition: context.cpp:547
RCLCPP_PUBLIC Logger get_logger(const std::string &name)
Return a named logger.
Definition: logger.cpp:27
Encapsulates the non-global state of an init/shutdown cycle.
Definition: context.h:114
#define RCL_RET_OK
Success return code.
Definition: types.h:26
rmw_ret_t rcl_ret_t
The type that holds an rcl return code.
Definition: types.h:23