Goby3 3.7.0
2026.11.12
Loading...
Searching...
No Matches
interprocess.h
Go to the documentation of this file.
1// Copyright 2016-2026:
2// GobySoft, LLC (2013-)
3// Community contributors (see AUTHORS file)
4// File authors:
5// Toby Schneider <toby@gobysoft.org>
6//
7//
8// This file is part of the Goby Underwater Autonomy Project Libraries
9// ("The Goby Libraries").
10//
11// The Goby Libraries are free software: you can redistribute them and/or modify
12// them under the terms of the GNU Lesser General Public License as published by
13// the Free Software Foundation, either version 2.1 of the License, or
14// (at your option) any later version.
15//
16// The Goby Libraries are distributed in the hope that they will be useful,
17// but WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19// GNU Lesser General Public License for more details.
20//
21// You should have received a copy of the GNU Lesser General Public License
22// along with Goby. If not, see <http://www.gnu.org/licenses/>.
23
24#ifndef GOBY_ZEROMQ_TRANSPORT_INTERPROCESS_H
25#define GOBY_ZEROMQ_TRANSPORT_INTERPROCESS_H
26
28
29#include <atomic> // for atomic
30#include <chrono> // for mill...
31#include <condition_variable> // for cond...
32#include <deque> // for deque
33#include <functional> // for func...
34#include <memory> // for shar...
35#include <mutex> // for time...
36#include <set> // for set
37#include <string> // for string
38#include <thread> // for get_id
39#include <unordered_map> // for unor...
40#include <utility> // for make...
41#include <vector> // for vector
42
43#include <zmq.h> // for ZMQ_...
44#include <zmq.hpp> // for sock...
45
46#include "goby/middleware/common.h" // for thre...
47#include "goby/middleware/group.h" // for Group
48#include "goby/middleware/marshalling/interface.h" // for Seri...
53#include "goby/middleware/transport/interface.h" // for Poll...
54#include "goby/middleware/transport/interprocess.h" // for Inte...
55#include "goby/middleware/transport/null.h" // for Null...
57#include "goby/middleware/transport/subscriber.h" // for Subs...
58#include "goby/time/system_clock.h" // for Syst...
59#include "goby/util/debug_logger/flex_ostream.h" // for Flex...
63#include "goby/zeromq/transport/detail/tags.h" // for InterProcessTag
64
65#if ZMQ_VERSION <= ZMQ_MAKE_VERSION(4, 3, 1)
66#define USE_OLD_ZMQ_CPP_API
67#endif
68
69#if CPPZMQ_VERSION < ZMQ_MAKE_VERSION(4, 7, 1)
70#define USE_OLD_CPPZMQ_SETSOCKOPT
71#endif
72
73#if CPPZMQ_VERSION < ZMQ_MAKE_VERSION(4, 8, 0)
74#define USE_OLD_CPPZMQ_POLL
75#endif
76
77namespace goby
78{
79namespace middleware
80{
81template <typename Data> class Publisher;
82} // namespace middleware
83
84namespace zeromq
85{
86namespace groups
87{
88constexpr goby::middleware::Group manager_request{"goby::zeromq::_internal_manager_request"};
89constexpr goby::middleware::Group manager_response{"goby::zeromq::_internal_manager_response"};
90} // namespace groups
91
92constexpr const char* delimiter_str{"/"};
93
94void setup_socket(zmq::socket_t& socket, const protobuf::Socket& cfg);
95
97std::string ready_marker_identifier(const std::string& client_name);
98
99#ifdef USE_OLD_ZMQ_CPP_API
102#else
103using zmq_recv_flags_type = zmq::recv_flags;
104using zmq_send_flags_type = zmq::send_flags;
105#endif
106
107// run in the same thread as InterProcessPortal
109{
110 public:
111 InterProcessPortalMainThread(zmq::context_t& context,
114 {
115#ifdef USE_OLD_CPPZMQ_SETSOCKOPT
116 control_socket_.setsockopt(ZMQ_LINGER, 0);
117 publish_socket_.setsockopt(ZMQ_LINGER, 0);
118#else
119 control_socket_.set(zmq::sockopt::linger, 0);
120 publish_socket_.set(zmq::sockopt::linger, 0);
121#endif
122 }
123
124 bool publish_ready() { return !hold_; }
125 bool subscribe_ready() { return have_pubsub_sockets_; }
126
127 bool recv(protobuf::InprocControl* control_msg,
130
132 void set_hold_state(bool hold, const std::set<std::string>& required_clients);
133 bool hold_state() { return hold_; }
134
137
138 void publish(const std::string& identifier, const char* bytes, int size,
139 bool ignore_buffer = false);
140 void subscribe(const std::string& identifier);
141 void unsubscribe(const std::string& identifier);
143
144 std::deque<protobuf::InprocControl>& control_buffer() { return control_buffer_; }
146
147 private:
148 void release_hold_if_ready();
149
150 private:
152 zmq::socket_t control_socket_;
153 zmq::socket_t publish_socket_;
154 bool hold_{true};
155 bool manager_hold_{true};
156 std::set<std::string> required_clients_;
157 std::chrono::steady_clock::time_point hold_release_deadline_;
158 // every subscription in the system, as forwarded by the Router to this XPUB socket
159 std::set<std::string> subscriptions_;
160 bool have_pubsub_sockets_{false};
161
162 std::deque<std::pair<std::string, std::vector<char>>>
163 publish_queue_; //used before hold == false
164
165 // buffer messages while waiting for (un)subscribe ack
166 std::deque<protobuf::InprocControl> control_buffer_;
167};
168
169// run in a separate thread to allow zmq_.poll() to block without interrupting the main thread
171{
172 public:
174 zmq::context_t& context, std::atomic<bool>& alive,
175 std::shared_ptr<std::mutex> poller_mutex,
176 std::shared_ptr<std::condition_variable> poller_cv);
177 void run();
179 {
180#ifdef USE_OLD_CPPZMQ_SETSOCKOPT
181 control_socket_.setsockopt(ZMQ_LINGER, 0);
182 subscribe_socket_.setsockopt(ZMQ_LINGER, 0);
183 manager_socket_.setsockopt(ZMQ_LINGER, 0);
184#else
185 control_socket_.set(zmq::sockopt::linger, 0);
186 subscribe_socket_.set(zmq::sockopt::linger, 0);
187 manager_socket_.set(zmq::sockopt::linger, 0);
188#endif
189 }
190
191 private:
192 void poll(long timeout_ms = -1);
193 void control_data(const zmq::message_t& zmq_msg);
194 void subscribe_data(const zmq::message_t& zmq_msg);
195 void manager_data(const zmq::message_t& zmq_msg);
196 void send_control_msg(const protobuf::InprocControl& control);
197 void send_manager_request(const protobuf::ManagerRequest& req);
198 void wake_poller();
199
200 private:
202 zmq::socket_t control_socket_;
203 zmq::socket_t subscribe_socket_;
204 zmq::socket_t manager_socket_;
205 std::atomic<bool>& alive_;
206 std::shared_ptr<std::mutex> poller_mutex_;
207 std::shared_ptr<std::condition_variable> poller_cv_;
208 bool poller_wakeup_pending_{false};
209 static constexpr long poller_wakeup_retry_ms_{1};
210 std::vector<zmq::pollitem_t> poll_items_;
211 enum
212 {
213 SOCKET_CONTROL = 0,
214 SOCKET_MANAGER = 1,
215 SOCKET_SUBSCRIBE = 2
216 };
217 enum
218 {
219 NUMBER_SOCKETS = 3
220 };
221 bool have_pubsub_sockets_{false};
222 bool hold_{true};
223 bool manager_waiting_for_reply_{false};
224
225 goby::time::SystemClock::time_point next_hold_state_request_time_{
227 const goby::time::SystemClock::duration hold_state_request_period_{
228 std::chrono::milliseconds(100)};
229};
230
231template <typename InnerTransporter,
232 template <typename Derived, typename InnerTransporterType,
233 typename ImplementationTag_> class PortalBase,
234 typename ImplementationTag>
236 : public PortalBase<InterProcessPortalImplementation<InnerTransporter, PortalBase,
237 ImplementationTag>,
238 InnerTransporter, ImplementationTag>
239{
240 public:
242 ImplementationTag>,
243 InnerTransporter, ImplementationTag>;
245
247 : cfg_(cfg),
248 zmq_context_(cfg.zeromq_number_io_threads()),
249 zmq_main_(zmq_context_, cfg_),
250 zmq_read_thread_(cfg_, zmq_context_, zmq_alive_,
251 middleware::PollerInterface::poll_mutex(),
252 middleware::PollerInterface::cv())
253 {
254 _init();
255 }
256
257 InterProcessPortalImplementation(InnerTransporter& inner,
259 : Base(inner),
260 cfg_(cfg),
261 zmq_context_(cfg.zeromq_number_io_threads()),
262 zmq_main_(zmq_context_, cfg_),
263 zmq_read_thread_(cfg_, zmq_context_, zmq_alive_,
264 middleware::PollerInterface::poll_mutex(),
265 middleware::PollerInterface::cv())
266 {
267 _init();
268 }
269
271 {
272 if (zmq_thread_)
273 {
274 zmq_main_.reader_shutdown();
275 zmq_thread_->join();
276 }
277 }
278
280 void ready() { ready_ = true; }
281
283 bool hold_state() { return zmq_main_.hold_state(); }
284
285 friend Base;
286 friend typename Base::Base;
287 friend typename Base::Common;
288
289 private:
290 void _init()
291 {
293
294 // start zmq read thread
295 zmq_thread_ = std::make_unique<std::thread>([this]() { zmq_read_thread_.run(); });
296
297 while (!zmq_main_.subscribe_ready())
298 {
299 protobuf::InprocControl control_msg;
300 if (zmq_main_.recv(&control_msg))
301 {
302 switch (control_msg.type())
303 {
304 case protobuf::InprocControl::PUB_CONFIGURATION:
305 zmq_main_.set_publish_cfg(control_msg.publish_socket());
306 break;
307 default: break;
308 }
309 }
310 }
311
312 //
313 // Handle hold state request/response using pub sub so that we ensure
314 // publishing and subscribe is completely functional before releasing the hold
315 //
316 this->template _subscribe<protobuf::ManagerResponse,
317 middleware::MarshallingScheme::PROTOBUF>(
318 [this](std::shared_ptr<const protobuf::ManagerResponse> response)
319 {
320 goby::glog.is_debug3() && goby::glog << "Received ManagerResponse: "
321 << response->ShortDebugString() << std::endl;
322 if (response->request() == protobuf::PROVIDE_HOLD_STATE &&
323 response->client_pid() == getpid() &&
324 response->client_name() == cfg_.client_name())
325 {
326 zmq_main_.set_hold_state(
327 response->hold(), std::set<std::string>(response->required_client().begin(),
328 response->required_client().end()));
329 }
330 },
331 groups::manager_response, middleware::Subscriber<protobuf::ManagerResponse>());
332 manager_response_subscribed_ = true;
333 }
334
335 void _do_publish(const std::string& identifier, const std::vector<char>& bytes)
336 {
337 zmq_main_.publish(identifier, bytes.data(), bytes.size(), ignore_buffer_);
338 }
339
340 void _do_portal_subscribe(const std::string& identifier) { zmq_main_.subscribe(identifier); }
341 void _do_portal_unsubscribe(const std::string& identifier)
342 {
343 zmq_main_.unsubscribe(identifier);
344 }
345
346 void _do_portal_wildcard_subscribe() { zmq_main_.subscribe(delimiter_str); }
347 void _do_portal_wildcard_unsubscribe() { zmq_main_.unsubscribe(delimiter_str); }
348
349 int _poll(std::unique_ptr<std::unique_lock<std::mutex>>& lock)
350 {
351 int items = 0;
352 protobuf::InprocControl new_control_msg;
353
354#ifdef USE_OLD_ZMQ_CPP_API
355 int flags = ZMQ_NOBLOCK;
356#else
357 auto flags = zmq::recv_flags::dontwait;
358#endif
359
360 // the inner layers have already been polled, so all subscriptions forwarded so far
361 // precede the marker on the SUB socket
362 if (ready_ && !ready_marker_subscribed_)
363 {
364 zmq_main_.subscribe(ready_marker_identifier(cfg_.client_name()));
365 ready_marker_subscribed_ = true;
366 }
367
368 while (zmq_main_.recv(&new_control_msg, flags))
369 zmq_main_.control_buffer().push_back(new_control_msg);
370
371 while (!zmq_main_.control_buffer().empty())
372 {
373 const auto& control_msg = zmq_main_.control_buffer().front();
374 switch (control_msg.type())
375 {
376 case protobuf::InprocControl::RECEIVE:
377 {
378 ++items;
379 this->_handle_received_data(lock, control_msg.received_data());
380 }
381 break;
382
383 case protobuf::InprocControl::REQUEST_HOLD_STATE:
384 {
385 protobuf::ManagerRequest req;
386
387 req.set_ready(ready_);
388 req.set_request(protobuf::PROVIDE_HOLD_STATE);
389 req.set_client_name(cfg_.client_name());
390 req.set_client_pid(getpid());
391
392 goby::glog.is_debug3() && goby::glog << "Published ManagerRequest: "
393 << req.ShortDebugString() << std::endl;
394
395 ignore_buffer_ = true;
396 this->template publish<groups::manager_request>(req);
397 ignore_buffer_ = false;
398 }
399 break;
400
401 default: break;
402 }
403 zmq_main_.control_buffer().pop_front();
404 }
405
406 zmq_main_.read_subscriptions();
407
408 if (manager_response_subscribed_ && zmq_main_.publish_ready())
409 {
410 this->template _unsubscribe<protobuf::ManagerResponse,
411 middleware::MarshallingScheme::PROTOBUF>(
412 groups::manager_response, middleware::Subscriber<protobuf::ManagerResponse>());
413 manager_response_subscribed_ = false;
414 }
415
416 return items;
417 }
418
419 private:
420 const protobuf::InterProcessPortalConfig cfg_;
421
422 std::unique_ptr<std::thread> zmq_thread_;
423 std::atomic<bool> zmq_alive_{true};
424 zmq::context_t zmq_context_;
425 InterProcessPortalMainThread zmq_main_;
426 InterProcessPortalReadThread zmq_read_thread_;
427
428 bool ready_{false};
429 bool ready_marker_subscribed_{false};
430 bool manager_response_subscribed_{false};
431 bool ignore_buffer_{false};
432};
433
435{
436 public:
437 Router(zmq::context_t& context, const protobuf::InterProcessPortalConfig& cfg)
438 : context_(context), cfg_(cfg)
439 {
440 }
441
442 void run();
443 unsigned last_port(zmq::socket_t& socket);
444
445 Router(Router&) = delete;
447
448 public:
449 std::atomic<unsigned> pub_port{0};
450 std::atomic<unsigned> sub_port{0};
451
452 private:
453 zmq::context_t& context_;
455};
456
458{
459 public:
460 Manager(zmq::context_t& context, const protobuf::InterProcessPortalConfig& cfg,
461 const Router& router);
462
463 Manager(zmq::context_t& context, const protobuf::InterProcessPortalConfig& cfg,
464 const Router& router, const protobuf::InterProcessManagerHold& hold)
465 : Manager(context, cfg, router)
466 {
467 for (const auto& req_c : hold.required_client()) required_clients_.insert(req_c);
468 }
469
470 void run();
471
475
477
478 private:
479 std::set<std::string> reported_clients_;
480 std::set<std::string> required_clients_;
481
482 zmq::context_t& context_;
484 const Router& router_;
485
486 std::vector<zmq::pollitem_t> poll_items_;
487 enum
488 {
489 SOCKET_MANAGER = 0,
490 SOCKET_SUBSCRIBE = 1,
491 };
492 enum
493 {
494 NUMBER_SOCKETS = 2
495 };
496
497 std::unique_ptr<zmq::socket_t> manager_socket_;
498 std::unique_ptr<zmq::socket_t> subscribe_socket_;
499 std::unique_ptr<zmq::socket_t> publish_socket_;
500
503 protobuf::ManagerRequest, middleware::scheme<protobuf::ManagerRequest>()>::type_name(),
504 middleware::scheme<protobuf::ManagerRequest>(), groups::manager_request,
506
507 std::string zmq_filter_rep_{
509 middleware::SerializerParserHelper<
510 protobuf::ManagerResponse,
511 middleware::scheme<protobuf::ManagerResponse>()>::type_name(),
512 middleware::scheme<protobuf::ManagerResponse>(), groups::manager_response,
513 middleware::IdentifierWildcard::NO_WILDCARDS, std::to_string(getpid())) +
515}; // namespace zeromq
516
517template <typename InnerTransporter = middleware::NullTransporter>
521
522template <typename InnerTransporter = middleware::NullTransporter>
525
526} // namespace zeromq
527} // namespace goby
528
529namespace goby
530{
531namespace middleware
532{
533namespace detail
534{
535template <> struct implementation_traits<goby::zeromq::detail::InterProcessTag>
536{
537 template <typename InnerTransporter>
540 static constexpr const char* name = "zeromq";
541};
542} // namespace detail
543} // namespace middleware
544} // namespace goby
545
546#endif
Class for grouping publications in the Goby middleware. Analogous to "topics" in ROS,...
Definition group.h:60
Implements the forwarder concept for the interprocess layer.
static std::string make_identifier(const std::string &type_name, int scheme, const std::string &group, IdentifierWildcard wildcard, const std::string &process, std::unordered_map< int, std::string > *schemes_buffer=nullptr, std::unordered_map< std::thread::id, std::string > *threads_buffer=nullptr)
Class that holds additional metadata and callback functions related to a subscription (and is optiona...
Definition subscriber.h:37
void set_lock_action(logger_lock::LockAction lock_action)
bool hold_state()
When using hold functionality, returns whether the system is holding (true) and thus waiting for all ...
InterProcessPortalImplementation(InnerTransporter &inner, const protobuf::InterProcessPortalConfig &cfg)
InterProcessPortalImplementation(const protobuf::InterProcessPortalConfig &cfg)
void ready()
When using hold functionality, call when the process is ready to receive publications (typically done...
InterProcessPortalMainThread(zmq::context_t &context, const protobuf::InterProcessPortalConfig &cfg)
void set_publish_cfg(const protobuf::Socket &cfg)
void set_hold_state(bool hold, const std::set< std::string > &required_clients)
Hold state as reported by the Manager; the hold is released once the ready marker of every required c...
void unsubscribe(const std::string &identifier)
std::deque< protobuf::InprocControl > & control_buffer()
void subscribe(const std::string &identifier)
void read_subscriptions()
Reads subscriptions arriving at the XPUB socket, releasing the hold if ready.
void publish(const std::string &identifier, const char *bytes, int size, bool ignore_buffer=false)
void send_control_msg(const protobuf::InprocControl &control)
bool recv(protobuf::InprocControl *control_msg, zmq_recv_flags_type flags=zmq_recv_flags_type())
InterProcessPortalReadThread(const protobuf::InterProcessPortalConfig &cfg, zmq::context_t &context, std::atomic< bool > &alive, std::shared_ptr< std::mutex > poller_mutex, std::shared_ptr< std::condition_variable > poller_cv)
Manager(zmq::context_t &context, const protobuf::InterProcessPortalConfig &cfg, const Router &router, const protobuf::InterProcessManagerHold &hold)
protobuf::Socket subscribe_socket_cfg()
Manager(zmq::context_t &context, const protobuf::InterProcessPortalConfig &cfg, const Router &router)
protobuf::Socket publish_socket_cfg()
protobuf::ManagerResponse handle_request(const protobuf::ManagerRequest &pb_request)
Router & operator=(Router &)=delete
Router(Router &)=delete
std::atomic< unsigned > sub_port
unsigned last_port(zmq::socket_t &socket)
Router(zmq::context_t &context, const protobuf::InterProcessPortalConfig &cfg)
std::atomic< unsigned > pub_port
::goby::zeromq::protobuf::InprocControl_InprocControlType type() const
const ::goby::zeromq::protobuf::Socket & publish_socket() const
const std::string & required_client(int index) const
detail namespace with internal helper functions
Definition json.hpp:263
constexpr goby::middleware::Group manager_response
constexpr goby::middleware::Group manager_request
constexpr const char * delimiter_str
std::string ready_marker_identifier(const std::string &client_name)
Subscription a client makes once it is ready(); its arrival at a publisher's socket implies all of th...
int zmq_send_flags_type
int zmq_recv_flags_type
void setup_socket(zmq::socket_t &socket, const protobuf::Socket &cfg)
The global namespace for the Goby project.
util::FlexOstream glog
Access the Goby logger through this object.
Class for parsing and serializing a given marshalling scheme. Must be specialized for a particular sc...
Definition interface.h:98
std::chrono::time_point< SystemClock > time_point
static time_point now() noexcept
Returns the current system time unless SimulatorSettings::using_sim_time is set to true,...
std::chrono::microseconds duration
Duration type.
ImplementationTag for zeromq interprocess transporters.
Definition tags.h:36