Goby3 3.7.0
2026.11.12
Loading...
Searching...
No Matches
interprocess.h
Go to the documentation of this file.
1// Copyright 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_UDPM_TRANSPORT_INTERPROCESS_H
25#define GOBY_UDPM_TRANSPORT_INTERPROCESS_H
26
27#include <arpa/inet.h>
28#include <array>
29#include <boost/asio/buffer.hpp>
30#include <boost/asio/executor_work_guard.hpp>
31#include <boost/asio/ip/multicast.hpp>
32#include <boost/asio/ip/udp.hpp>
33#include <boost/asio/post.hpp>
34#include <boost/asio/socket_base.hpp>
35#include <boost/asio/steady_timer.hpp>
36#include <boost/circular_buffer.hpp>
37#include <chrono>
38#include <cstring>
39#include <deque>
40#include <memory>
41#include <mutex>
42#include <set>
43#include <thread>
44#include <unordered_map>
45
52
55
56namespace goby
57{
58namespace middleware
59{
60template <typename Data> class Publisher;
61} // namespace middleware
62
63namespace udpm
64{
65
66// Packet status codes
67enum class UDPMPacketStatus : uint8_t
68{
69 NORMAL = 0,
70};
71
72// Packet header (9 bytes, after the null-terminated identifier):
73// message_index : uint32 (network byte order)
74// num_packets : uint16 (network byte order)
75// packet_count : uint16 (network byte order)
76// status : uint8
77static constexpr std::size_t UDPM_PACKET_HEADER_SIZE =
78 sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint8_t);
79
87
88inline void encode_header(char* buf, const UDPMPacketHeader& h)
89{
90 uint32_t mi = htonl(h.message_index);
91 uint16_t np = htons(h.num_packets);
92 uint16_t pc = htons(h.packet_count);
93 std::memcpy(buf, &mi, 4);
94 std::memcpy(buf + 4, &np, 2);
95 std::memcpy(buf + 6, &pc, 2);
96 buf[8] = static_cast<uint8_t>(h.status);
97}
98
99inline UDPMPacketHeader decode_header(const char* buf)
100{
102 uint32_t mi;
103 uint16_t np, pc;
104 std::memcpy(&mi, buf, 4);
105 std::memcpy(&np, buf + 4, 2);
106 std::memcpy(&pc, buf + 6, 2);
107 h.message_index = ntohl(mi);
108 h.num_packets = ntohs(np);
109 h.packet_count = ntohs(pc);
110 h.status = static_cast<UDPMPacketStatus>(static_cast<uint8_t>(buf[8]));
111 return h;
112}
113
114template <typename InnerTransporter,
115 template <typename Derived, typename InnerTransporterType,
116 typename ImplementationTag_> class PortalBase,
117 typename ImplementationTag>
119 : public PortalBase<InterProcessPortalImplementation<InnerTransporter, PortalBase,
120 ImplementationTag>,
121 InnerTransporter, ImplementationTag>
122{
123 public:
125 ImplementationTag>,
126 InnerTransporter, ImplementationTag>;
127
129
131 {
132 _init();
133 }
134
135 InterProcessPortalImplementation(InnerTransporter& inner,
137 : Base(inner), cfg_(cfg)
138 {
139 _init();
140 }
141
143 {
144 // Close socket first to cancel any pending async operations,
145 // then release the work guard so io_.ctx.run() can return, then join.
146 io_.socket.close();
147 io_.work.reset();
148 if (io_thread_.joinable())
149 io_thread_.join();
150 }
151
152 // no-op - no hold implemented in UDPM
153 void ready() {}
154 bool hold_state() { return false; }
155
156 friend Base;
157 friend typename Base::Base;
158 friend typename Base::Common;
159
160 private:
161 // -----------------------------------------------------------------------
162 // Called from main thread before io_thread_ starts; sets up socket and
163 // launches io_thread_.
164 // -----------------------------------------------------------------------
165 void _init()
166 {
168
169 boost::asio::ip::address listen_address =
170 boost::asio::ip::make_address(cfg_.listen_address());
171 boost::asio::ip::address multicast_address =
172 boost::asio::ip::make_address(cfg_.multicast_address());
173 short multicast_port = static_cast<short>(cfg_.multicast_port());
174
175 boost::asio::ip::udp::endpoint listen_endpoint(listen_address, multicast_port);
176 io_.transmit_endpoint = boost::asio::ip::udp::endpoint(multicast_address, multicast_port);
177
178 io_.socket.open(listen_endpoint.protocol());
179 io_.socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
180 io_.socket.bind(listen_endpoint);
181 io_.socket.set_option(boost::asio::ip::multicast::join_group(multicast_address));
182
183 // Arm the first async receive before starting io_thread_ so the
184 // operation is already queued when io_.ctx.run() is called.
185 _start_async_receive();
186 io_thread_ = std::thread([this]() { io_.ctx.run(); });
187 }
188
189 // -----------------------------------------------------------------------
190 // Runs on io_thread_: arms (or re-arms) a single async datagram receive.
191 // Called once from _init() (main thread, before io_thread_ starts) and
192 // then re-posted from within the completion handler on io_thread_.
193 // -----------------------------------------------------------------------
194 void _start_async_receive()
195 {
196 io_.socket.async_receive_from(
197 boost::asio::buffer(io_.rx_buffer), io_.sender_endpoint,
198 [this](boost::system::error_code ec, std::size_t length)
199 {
200 if (!ec)
201 {
202 {
203 std::lock_guard<std::mutex> l(rx_mutex_);
204 rx_.push_back(std::string(io_.rx_buffer.begin(),
205 io_.rx_buffer.begin() + length));
206 }
207 middleware::detail::notify_poller(*this->poll_mutex(), *this->cv());
208 _start_async_receive();
209 }
210 });
211 }
212
213 // -----------------------------------------------------------------------
214 // Main thread helpers
215 // -----------------------------------------------------------------------
216
217 std::shared_ptr<std::vector<char>> _build_packet(const std::string& identifier,
218 const UDPMPacketHeader& hdr,
219 const char* data_begin, std::size_t data_len)
220 {
221 auto pkt = std::make_shared<std::vector<char>>();
222 pkt->reserve(identifier.size() + UDPM_PACKET_HEADER_SIZE + data_len);
223 pkt->insert(pkt->end(), identifier.begin(), identifier.end());
224 char hdr_buf[UDPM_PACKET_HEADER_SIZE];
225 encode_header(hdr_buf, hdr);
226 pkt->insert(pkt->end(), hdr_buf, hdr_buf + UDPM_PACKET_HEADER_SIZE);
227 if (data_len > 0)
228 pkt->insert(pkt->end(), data_begin, data_begin + data_len);
229 return pkt;
230 }
231
232 void _async_send(std::shared_ptr<std::vector<char>> pkt)
233 {
234 if (cfg_.max_send_rate_bytes_per_second() > 0)
235 {
236 auto now = std::chrono::steady_clock::now();
237
238 std::this_thread::sleep_until(next_send_time_);
239
240 double delay_sec = static_cast<double>(pkt->size()) /
241 static_cast<double>(cfg_.max_send_rate_bytes_per_second());
242
243 if (static_cast<long>(delay_sec * 1.0e9) < std::numeric_limits<long>::max())
244 next_send_time_ =
245 now + std::chrono::nanoseconds(static_cast<long>(1e9 * delay_sec));
246 else if (static_cast<long>(delay_sec * 1.0e6) < std::numeric_limits<long>::max())
247
248 next_send_time_ =
249 now + std::chrono::microseconds(static_cast<long>(1e6 * delay_sec));
250 else
251 next_send_time_ =
252 now + std::chrono::milliseconds(static_cast<long>(1e3 * delay_sec));
253 }
254
255 _do_socket_send(std::move(pkt));
256 }
257
258 void _do_socket_send(std::shared_ptr<std::vector<char>> pkt)
259 {
260 // Post the actual socket write to io_thread_ so that the socket is
261 // only ever touched from io_thread_.
262 boost::asio::post(io_.ctx,
263 [this, pkt = std::move(pkt)]()
264 {
265 io_.socket.async_send_to(
266 boost::asio::buffer(*pkt), io_.transmit_endpoint,
267 [pkt](boost::system::error_code ec, std::size_t length)
268 {
269 if (!ec)
270 goby::glog.is_debug3() &&
271 goby::glog << "UDPM: Sent " << length << "B"
272 << std::endl;
273 else
274 goby::glog.is_warn() &&
275 goby::glog << "UDPM: Send error: " << ec.message()
276 << std::endl;
277 });
278 });
279 }
280
281 void _do_publish(const std::string& identifier, const std::vector<char>& bytes)
282 {
284 goby::glog << "UDPM: Publishing for: "
285 << std::string(identifier.begin(),
286 std::find(identifier.begin(), identifier.end(), '\0'))
287 << ", " << bytes.size() << "B" << std::endl;
288
289 const std::size_t header_overhead = identifier.size() + UDPM_PACKET_HEADER_SIZE;
290 const std::size_t payload_bytes = cfg_.udp_payload_bytes();
291
292 std::string id_key(identifier.begin(),
293 std::find(identifier.begin(), identifier.end(), '\0'));
294
295 uint32_t msg_idx = tx_message_index_[id_key]++;
296
297 // single packet for message
298 if (header_overhead + bytes.size() <= payload_bytes)
299 {
300 goby::glog.is_debug3() && goby::glog << "UDPM: Sent in a single packet" << std::endl;
301
302 UDPMPacketHeader hdr;
303 hdr.message_index = msg_idx;
304 hdr.num_packets = 1;
305 hdr.packet_count = 0;
306 hdr.status = UDPMPacketStatus::NORMAL;
307
308 auto pkt = _build_packet(identifier, hdr, bytes.data(), bytes.size());
309
310 TxMessageEntry entry;
311 entry.message_index = msg_idx;
312 entry.packets.push_back(pkt);
313
314 _async_send(pkt);
315 return;
316 }
317
318 const std::size_t max_data_per_packet = payload_bytes - header_overhead;
319 const std::size_t num_packets_needed =
320 (bytes.size() + max_data_per_packet - 1) / max_data_per_packet;
321
322 if (num_packets_needed > std::numeric_limits<uint16_t>::max())
323 {
325 goby::glog << "UDPM: Message too large to packetize: " << bytes.size() << " bytes, "
326 << num_packets_needed << " packets needed" << std::endl;
327 }
328
329 const uint16_t num_pkts = static_cast<uint16_t>(std::min(
330 num_packets_needed, static_cast<std::size_t>(std::numeric_limits<uint16_t>::max())));
331
332 TxMessageEntry entry;
333 entry.message_index = msg_idx;
334 entry.packets.reserve(num_pkts);
335
336 goby::glog.is_debug3() && goby::glog << "UDPM: Sending in " << num_pkts << " packets"
337 << std::endl;
338 for (uint16_t i = 0; i < num_pkts; ++i)
339 {
340 std::size_t offset = static_cast<std::size_t>(i) * max_data_per_packet;
341 std::size_t chunk = std::min(max_data_per_packet, bytes.size() - offset);
342
343 UDPMPacketHeader hdr;
344 hdr.message_index = msg_idx;
345 hdr.num_packets = num_pkts;
346 hdr.packet_count = i;
347 hdr.status = UDPMPacketStatus::NORMAL;
348
349 auto pkt = _build_packet(identifier, hdr, bytes.data() + offset, chunk);
350 entry.packets.push_back(pkt);
351 _async_send(pkt);
352 }
353 }
354
355 void _do_portal_subscribe(const std::string& identifier)
356 {
357 goby::glog.is_debug3() && goby::glog << "UDPM: Subscribe for: " << identifier << " (no-op)"
358 << std::endl;
359 }
360 void _do_portal_unsubscribe(const std::string& identifier)
361 {
362 goby::glog.is_debug3() && goby::glog << "UDPM: Unsubscribe for: " << identifier
363 << " (no-op)" << std::endl;
364 }
365 void _do_portal_wildcard_subscribe()
366 {
367 goby::glog.is_debug3() && goby::glog << "UDPM: Wildcard subscribe (no-op)" << std::endl;
368 }
369 void _do_portal_wildcard_unsubscribe()
370 {
371 goby::glog.is_debug3() && goby::glog << "UDPM: Wildcard unsubscribe (no-op)" << std::endl;
372 }
373
374 void _process_received_packet(std::unique_ptr<std::unique_lock<std::mutex>>& lock,
375 const std::string& raw)
376 {
377 auto null_it = std::find(raw.begin(), raw.end(),
379 if (null_it == raw.end())
380 {
382 << "UDPM: Received packet with no null terminator, dropping"
383 << std::endl;
384 return;
385 }
386
387 std::string id_key(raw.begin(), null_it);
388
389 auto header_start = null_it + 1;
390 if (raw.end() - header_start < static_cast<std::ptrdiff_t>(UDPM_PACKET_HEADER_SIZE))
391 {
393 goby::glog << "UDPM: Received packet too short for header, dropping" << std::endl;
394 return;
395 }
396
397 UDPMPacketHeader hdr = decode_header(&*header_start);
398 auto data_begin = header_start + UDPM_PACKET_HEADER_SIZE;
399
401 goby::glog << "UDPM: Received packet for " << id_key << " msg_idx=" << hdr.message_index
402 << " num_pkts=" << hdr.num_packets << " pkt_cnt=" << hdr.packet_count
403 << " status=" << static_cast<int>(hdr.status)
404 << " data=" << (raw.end() - data_begin) << "B" << std::endl;
405
406 if (hdr.num_packets == 1)
407 {
408 std::string full_data(raw.begin(), null_it + 1);
409 full_data.append(data_begin, raw.end());
410 this->_handle_received_data(lock, full_data);
411 return;
412 }
413
414 auto& partial = rx_partial_[id_key];
415 if (partial.message_index != hdr.message_index)
416 {
417 goby::glog.is_warn() && goby::glog << "UDPM: Dropping partial packet for " << id_key
418 << " msg_idx=" << hdr.message_index << std::endl;
419 partial = RxPartialMessage();
420 }
421
422 if (partial.num_packets == 0)
423 partial.num_packets = hdr.num_packets;
424
425 partial.received_packets[hdr.packet_count] = std::vector<char>(data_begin, raw.end());
426
427 if (partial.received_packets.size() == hdr.num_packets)
428 {
429 std::string reassembled(raw.begin(), null_it + 1);
430 for (uint16_t i = 0; i < hdr.num_packets; ++i)
431 {
432 auto& pkt = partial.received_packets[i];
433 reassembled.append(pkt.begin(), pkt.end());
434 }
435 partial = RxPartialMessage();
436 this->_handle_received_data(lock, reassembled);
437 }
438 }
439
440 int _poll(std::unique_ptr<std::unique_lock<std::mutex>>& lock)
441 {
442 int items = 0;
443
444 std::deque<std::string> local_rx;
445 {
446 std::lock_guard<std::mutex> l(rx_mutex_);
447 local_rx.swap(rx_);
448 }
449
450 while (!local_rx.empty())
451 {
452 ++items;
453 _process_received_packet(lock, local_rx.front());
454 local_rx.pop_front();
455 }
456
457 return items;
458 }
459
460 private:
461 struct RxPartialMessage
462 {
463 uint32_t message_index{0};
464 uint16_t num_packets{0};
465 std::unordered_map<uint16_t, std::vector<char>> received_packets;
466 };
467
468 struct TxMessageEntry
469 {
470 uint32_t message_index{0};
471 std::vector<std::shared_ptr<std::vector<char>>> packets;
472 };
473
474 // -----------------------------------------------------------------------
475 // Read-only configuration: written once in constructor, then safe to read
476 // from any thread without synchronization.
477 // -----------------------------------------------------------------------
478 const protobuf::InterProcessPortalConfig cfg_;
479
480 // -----------------------------------------------------------------------
481 // io_thread_ exclusive state
482 //
483 // All members of IOState are accessed ONLY from io_thread_, or from
484 // _init() before io_thread_ is started. Do NOT access these directly
485 // from the main thread once io_thread_ is running.
486 //
487 // Methods that run on io_thread_:
488 // _start_async_receive() -- arms / re-arms async receives
489 // async_receive_from completion handler -- pushes to rx_ then notifies
490 // async_send_to operation -- posted by _do_socket_send() via boost::asio::post
491 // -----------------------------------------------------------------------
492 struct IOState
493 {
495 boost::asio::ip::udp::socket socket{ctx};
496 boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work{
497 ctx.get_executor()};
498 boost::asio::ip::udp::endpoint sender_endpoint; // updated by async_receive_from
499 boost::asio::ip::udp::endpoint transmit_endpoint; // set once in _init, then read-only
500
501 static constexpr int max_udp_size{65507};
502 std::array<char, max_udp_size> rx_buffer{}; // staging buffer for incoming datagrams
503 } io_;
504
505 // -----------------------------------------------------------------------
506 // Shared state: written by io_thread_, read (swapped) by main thread.
507 //
508 // rx_ : io_thread_ pushes completed datagrams; main thread swaps it out
509 // in _poll(). All accesses must hold rx_mutex_.
510 // -----------------------------------------------------------------------
511 std::mutex rx_mutex_;
512 std::deque<std::string> rx_;
513
514 // -----------------------------------------------------------------------
515 // Main thread exclusive state
516 //
517 // These members are accessed ONLY from the main thread.
518 //
519 // Methods that run on the main thread:
520 // _init() -- setup; starts io_thread_
521 // _build_packet() -- serializes outgoing datagrams
522 // _async_send() -- rate-limiter; calls _do_socket_send()
523 // _do_socket_send() -- posts async_send_to to io_thread_
524 // _do_publish() -- fragments and enqueues outgoing messages
525 // _do_portal_subscribe/unsubscribe/wildcard_* -- subscription bookkeeping
526 // _process_received_packet() -- reassembles and dispatches incoming data
527 // _poll() -- drains rx_ and calls _process_received_packet
528 // -----------------------------------------------------------------------
529 std::unordered_map<std::string, uint32_t> tx_message_index_;
530 std::unordered_map<std::string, RxPartialMessage> rx_partial_;
531 std::chrono::steady_clock::time_point next_send_time_{std::chrono::steady_clock::now()};
532
533 // -----------------------------------------------------------------------
534 // Thread management
535 // -----------------------------------------------------------------------
536 std::thread io_thread_; // runs io_.ctx.run()
537};
538
539template <typename InnerTransporter = middleware::NullTransporter>
543
544template <typename InnerTransporter = middleware::NullTransporter>
547
548} // namespace udpm
549} // namespace goby
550
551namespace goby
552{
553namespace middleware
554{
555namespace detail
556{
558{
559 template <typename InnerTransporter>
562 static constexpr const char* name = "udpm";
563};
564} // namespace detail
565} // namespace middleware
566} // namespace goby
567
568#endif
Implements the forwarder concept for the interprocess layer.
InterProcessPortalImplementation(InnerTransporter &inner, const protobuf::InterProcessPortalConfig &cfg)
InterProcessPortalImplementation(const protobuf::InterProcessPortalConfig &cfg)
void set_lock_action(logger_lock::LockAction lock_action)
detail namespace with internal helper functions
Definition json.hpp:263
UDPMPacketHeader decode_header(const char *buf)
static constexpr std::size_t UDPM_PACKET_HEADER_SIZE
void encode_header(char *buf, const UDPMPacketHeader &h)
The global namespace for the Goby project.
util::FlexOstream glog
Access the Goby logger through this object.
Maps an ImplementationTag to the portal that implements it, so that generic code can be written again...
ImplementationTag for udpm interprocess transporters.
Definition tags.h:36