Gazebo Transport

API Reference

11.4.3
gz/transport/Discovery.hh
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2014 Open Source Robotics Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16 */
17 
18 #ifndef GZ_TRANSPORT_DISCOVERY_HH_
19 #define GZ_TRANSPORT_DISCOVERY_HH_
20 #include <errno.h>
21 #include <string.h>
22 
23 #ifdef _WIN32
24  // For socket(), connect(), send(), and recv().
25  #include <Winsock2.h>
26  #include <Ws2def.h>
27  #include <Ws2ipdef.h>
28  #include <Ws2tcpip.h>
29  // Type used for raw data on this platform.
30  using raw_type = char;
31 #else
32  // For data types
33  #include <sys/types.h>
34  // For socket(), connect(), send(), and recv()
35  #include <sys/socket.h>
36  // For gethostbyname()
37  #include <netdb.h>
38  // For inet_addr()
39  #include <arpa/inet.h>
40  // For close()
41  #include <unistd.h>
42  // For sockaddr_in
43  #include <netinet/in.h>
44  // Type used for raw data on this platform
45  using raw_type = void;
46 #endif
47 
48 #ifdef _WIN32
49  #pragma warning(push, 0)
50 #endif
51 #ifdef _WIN32
52  #pragma warning(pop)
53  // Suppress "decorated name length exceed" warning in STL.
54  #pragma warning(disable: 4503)
55  // Suppress "depreted API warnings" in WINSOCK.
56  #pragma warning(disable: 4996)
57 #endif
58 
59 #include <gz/msgs/discovery.pb.h>
60 
61 #include <algorithm>
62 #include <condition_variable>
63 #include <limits>
64 #include <map>
65 #include <memory>
66 #include <mutex>
67 #include <string>
68 #include <thread>
69 #include <vector>
70 
71 #include <gz/msgs/Utility.hh>
72 
73 #include "gz/transport/config.hh"
74 #include "gz/transport/Export.hh"
75 #include "gz/transport/Helpers.hh"
76 #include "gz/transport/NetUtils.hh"
80 
81 namespace ignition
82 {
83  namespace transport
84  {
85  // Inline bracket to help doxygen filtering.
86  inline namespace IGNITION_TRANSPORT_VERSION_NAMESPACE {
88  enum class DestinationType
89  {
91  UNICAST,
93  MULTICAST,
95  ALL
96  };
97 
98  //
104  bool IGNITION_TRANSPORT_VISIBLE pollSockets(
105  const std::vector<int> &_sockets,
106  const int _timeout);
107 
116  template<typename Pub>
117  class Discovery
118  {
125  public: Discovery(const std::string &_pUuid,
126  const std::string &_ip,
127  const int _port,
128  const bool _verbose = false)
129  : multicastGroup(_ip),
130  port(_port),
131  hostAddr(determineHost()),
132  pUuid(_pUuid),
133  silenceInterval(kDefSilenceInterval),
134  activityInterval(kDefActivityInterval),
135  heartbeatInterval(kDefHeartbeatInterval),
136  connectionCb(nullptr),
137  disconnectionCb(nullptr),
138  verbose(_verbose),
139  initialized(false),
140  numHeartbeatsUninitialized(0),
141  exit(false),
142  enabled(false)
143  {
144  std::string ignIp;
145  if (env("IGN_IP", ignIp) && !ignIp.empty())
146  this->hostInterfaces = {ignIp};
147  else
148  {
149  // Get the list of network interfaces in this host.
150  this->hostInterfaces = determineInterfaces();
151  }
152 
153 #ifdef _WIN32
154  WORD wVersionRequested;
155  WSADATA wsaData;
156 
157  // Request WinSock v2.2.
158  wVersionRequested = MAKEWORD(2, 2);
159  // Load WinSock DLL.
160  if (WSAStartup(wVersionRequested, &wsaData) != 0)
161  {
162  std::cerr << "Unable to load WinSock DLL" << std::endl;
163  return;
164  }
165 #endif
166  for (const auto &netIface : this->hostInterfaces)
167  {
168  auto succeed = this->RegisterNetIface(netIface);
169 
170  // If the IP address that we're selecting as the main IP address of
171  // the host is invalid, we change it to 127.0.0.1 .
172  // This is probably because IGN_IP is set to a wrong value.
173  if (netIface == this->hostAddr && !succeed)
174  {
175  this->RegisterNetIface("127.0.0.1");
176  std::cerr << "Did you set the environment variable IGN_IP with a "
177  << "correct IP address? " << std::endl
178  << " [" << netIface << "] seems an invalid local IP "
179  << "address." << std::endl
180  << " Using 127.0.0.1 as hostname." << std::endl;
181  this->hostAddr = "127.0.0.1";
182  }
183  }
184 
185  // Socket option: SO_REUSEADDR. This options is used only for receiving
186  // data. We can reuse the same socket for receiving multicast data from
187  // multiple interfaces. We will use the socket at position 0 for
188  // receiving data.
189  int reuseAddr = 1;
190  if (setsockopt(this->sockets.at(0), SOL_SOCKET, SO_REUSEADDR,
191  reinterpret_cast<const char *>(&reuseAddr), sizeof(reuseAddr)) != 0)
192  {
193  std::cerr << "Error setting socket option (SO_REUSEADDR)."
194  << std::endl;
195  return;
196  }
197 
198 #ifdef SO_REUSEPORT
199  // Socket option: SO_REUSEPORT. This options is used only for receiving
200  // data. We can reuse the same socket for receiving multicast data from
201  // multiple interfaces. We will use the socket at position 0 for
202  // receiving data.
203  int reusePort = 1;
204  // cppcheck-suppress ConfigurationNotChecked
205  if (setsockopt(this->sockets.at(0), SOL_SOCKET, SO_REUSEPORT,
206  reinterpret_cast<const char *>(&reusePort), sizeof(reusePort)) != 0)
207  {
208  std::cerr << "Error setting socket option (SO_REUSEPORT)."
209  << std::endl;
210  return;
211  }
212 #endif
213  // Bind the first socket to the discovery port.
214  sockaddr_in localAddr;
215  memset(&localAddr, 0, sizeof(localAddr));
216  localAddr.sin_family = AF_INET;
217  localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
218  localAddr.sin_port = htons(static_cast<u_short>(this->port));
219 
220  if (bind(this->sockets.at(0),
221  reinterpret_cast<sockaddr *>(&localAddr), sizeof(sockaddr_in)) < 0)
222  {
223  std::cerr << "Binding to a local port failed." << std::endl;
224  return;
225  }
226 
227  // Set 'mcastAddr' to the multicast discovery group.
228  memset(&this->mcastAddr, 0, sizeof(this->mcastAddr));
229  this->mcastAddr.sin_family = AF_INET;
230  this->mcastAddr.sin_addr.s_addr =
231  inet_addr(this->multicastGroup.c_str());
232  this->mcastAddr.sin_port = htons(static_cast<u_short>(this->port));
233 
235  std::string ignRelay = "";
236  if (env("IGN_RELAY", ignRelay) && !ignRelay.empty())
237  {
238  relays = transport::split(ignRelay, ':');
239  }
240 
241  // Register all unicast relays.
242  for (auto const &relayAddr : relays)
243  this->AddRelayAddress(relayAddr);
244 
245  if (this->verbose)
246  this->PrintCurrentState();
247  }
248 
250  public: virtual ~Discovery()
251  {
252  // Tell the service thread to terminate.
253  this->exitMutex.lock();
254  this->exit = true;
255  this->exitMutex.unlock();
256 
257  // Wait for the service threads to finish before exit.
258  if (this->threadReception.joinable())
259  this->threadReception.join();
260 
261  // Broadcast a BYE message to trigger the remote cancellation of
262  // all our advertised topics.
263  this->SendMsg(DestinationType::ALL, msgs::Discovery::BYE,
264  Publisher("", "", this->pUuid, "", AdvertiseOptions()));
265 
266  // Close sockets.
267  for (const auto &sock : this->sockets)
268  {
269 #ifdef _WIN32
270  closesocket(sock);
271  WSACleanup();
272 #else
273  close(sock);
274 #endif
275  }
276  }
277 
281  public: void Start()
282  {
283  {
284  std::lock_guard<std::mutex> lock(this->mutex);
285 
286  // The service is already running.
287  if (this->enabled)
288  return;
289 
290  this->enabled = true;
291  }
292 
293  auto now = std::chrono::steady_clock::now();
294  this->timeNextHeartbeat = now;
295  this->timeNextActivity = now;
296 
297  // Start the thread that receives discovery information.
298  this->threadReception = std::thread(&Discovery::RecvMessages, this);
299  }
300 
305  public: bool Advertise(const Pub &_publisher)
306  {
307  {
308  std::lock_guard<std::mutex> lock(this->mutex);
309 
310  if (!this->enabled)
311  return false;
312 
313  // Add the addressing information (local publisher).
314  if (!this->info.AddPublisher(_publisher))
315  return false;
316  }
317 
318  // Only advertise a message outside this process if the scope
319  // is not 'Process'
320  if (_publisher.Options().Scope() != Scope_t::PROCESS)
321  this->SendMsg(DestinationType::ALL, msgs::Discovery::ADVERTISE,
322  _publisher);
323 
324  return true;
325  }
326 
337  public: bool Discover(const std::string &_topic) const
338  {
340  bool found;
341  Addresses_M<Pub> addresses;
342 
343  {
344  std::lock_guard<std::mutex> lock(this->mutex);
345 
346  if (!this->enabled)
347  return false;
348 
349  cb = this->connectionCb;
350  }
351 
352  Pub pub;
353  pub.SetTopic(_topic);
354  pub.SetPUuid(this->pUuid);
355 
356  // Send a discovery request.
357  this->SendMsg(DestinationType::ALL, msgs::Discovery::SUBSCRIBE, pub);
358 
359  {
360  std::lock_guard<std::mutex> lock(this->mutex);
361  found = this->info.Publishers(_topic, addresses);
362  }
363 
364  if (found)
365  {
366  // I already have information about this topic.
367  for (const auto &proc : addresses)
368  {
369  for (const auto &node : proc.second)
370  {
371  if (cb)
372  {
373  // Execute the user's callback for a service request. Notice
374  // that we only execute one callback for preventing receive
375  // multiple service responses for a single request.
376  cb(node);
377  }
378  }
379  }
380  }
381 
382  return true;
383  }
384 
387  public: void Register(const MessagePublisher &_pub) const
388  {
389  this->SendMsg(
390  DestinationType::ALL, msgs::Discovery::NEW_CONNECTION, _pub);
391  }
392 
395  public: void Unregister(const MessagePublisher &_pub) const
396  {
397  this->SendMsg(
398  DestinationType::ALL, msgs::Discovery::END_CONNECTION, _pub);
399  }
400 
403  public: const TopicStorage<Pub> &Info() const
404  {
405  std::lock_guard<std::mutex> lock(this->mutex);
406  return this->info;
407  }
408 
413  public: bool Publishers(const std::string &_topic,
414  Addresses_M<Pub> &_publishers) const
415  {
416  std::lock_guard<std::mutex> lock(this->mutex);
417  return this->info.Publishers(_topic, _publishers);
418  }
419 
427  public: bool Unadvertise(const std::string &_topic,
428  const std::string &_nUuid)
429  {
430  Pub inf;
431  {
432  std::lock_guard<std::mutex> lock(this->mutex);
433 
434  if (!this->enabled)
435  return false;
436 
437  // Don't do anything if the topic is not advertised by any of my nodes
438  if (!this->info.Publisher(_topic, this->pUuid, _nUuid, inf))
439  return true;
440 
441  // Remove the topic information.
442  this->info.DelPublisherByNode(_topic, this->pUuid, _nUuid);
443  }
444 
445  // Only unadvertise a message outside this process if the scope
446  // is not 'Process'.
447  if (inf.Options().Scope() != Scope_t::PROCESS)
448  {
449  this->SendMsg(DestinationType::ALL,
450  msgs::Discovery::UNADVERTISE, inf);
451  }
452 
453  return true;
454  }
455 
458  public: std::string HostAddr() const
459  {
460  std::lock_guard<std::mutex> lock(this->mutex);
461  return this->hostAddr;
462  }
463 
468  public: unsigned int ActivityInterval() const
469  {
470  std::lock_guard<std::mutex> lock(this->mutex);
471  return this->activityInterval;
472  }
473 
479  public: unsigned int HeartbeatInterval() const
480  {
481  std::lock_guard<std::mutex> lock(this->mutex);
482  return this->heartbeatInterval;
483  }
484 
489  public: unsigned int SilenceInterval() const
490  {
491  std::lock_guard<std::mutex> lock(this->mutex);
492  return this->silenceInterval;
493  }
494 
498  public: void SetActivityInterval(const unsigned int _ms)
499  {
500  std::lock_guard<std::mutex> lock(this->mutex);
501  this->activityInterval = _ms;
502  }
503 
507  public: void SetHeartbeatInterval(const unsigned int _ms)
508  {
509  std::lock_guard<std::mutex> lock(this->mutex);
510  this->heartbeatInterval = _ms;
511  }
512 
516  public: void SetSilenceInterval(const unsigned int _ms)
517  {
518  std::lock_guard<std::mutex> lock(this->mutex);
519  this->silenceInterval = _ms;
520  }
521 
526  public: void ConnectionsCb(const DiscoveryCallback<Pub> &_cb)
527  {
528  std::lock_guard<std::mutex> lock(this->mutex);
529  this->connectionCb = _cb;
530  }
531 
536  public: void DisconnectionsCb(const DiscoveryCallback<Pub> &_cb)
537  {
538  std::lock_guard<std::mutex> lock(this->mutex);
539  this->disconnectionCb = _cb;
540  }
541 
545  public: void RegistrationsCb(const DiscoveryCallback<Pub> &_cb)
546  {
547  std::lock_guard<std::mutex> lock(this->mutex);
548  this->registrationCb = _cb;
549  }
550 
554  public: void UnregistrationsCb(const DiscoveryCallback<Pub> &_cb)
555  {
556  std::lock_guard<std::mutex> lock(this->mutex);
557  this->unregistrationCb = _cb;
558  }
559 
561  public: void PrintCurrentState() const
562  {
563  std::lock_guard<std::mutex> lock(this->mutex);
564 
565  std::cout << "---------------" << std::endl;
566  std::cout << std::boolalpha << "Enabled: "
567  << this->enabled << std::endl;
568  std::cout << "Discovery state" << std::endl;
569  std::cout << "\tUUID: " << this->pUuid << std::endl;
570  std::cout << "Settings" << std::endl;
571  std::cout << "\tActivity: " << this->activityInterval
572  << " ms." << std::endl;
573  std::cout << "\tHeartbeat: " << this->heartbeatInterval
574  << "ms." << std::endl;
575  std::cout << "\tSilence: " << this->silenceInterval
576  << " ms." << std::endl;
577  std::cout << "Known information:" << std::endl;
578  this->info.Print();
579 
580  // Used to calculate the elapsed time.
582 
583  std::cout << "Activity" << std::endl;
584  if (this->activity.empty())
585  std::cout << "\t<empty>" << std::endl;
586  else
587  {
588  for (auto &proc : this->activity)
589  {
590  // Elapsed time since the last update from this publisher.
591  std::chrono::duration<double> elapsed = now - proc.second;
592 
593  std::cout << "\t" << proc.first << std::endl;
594  std::cout << "\t\t" << "Since: " << std::chrono::duration_cast<
595  std::chrono::milliseconds>(elapsed).count() << " ms. ago. "
596  << std::endl;
597  }
598  }
599  std::cout << "---------------" << std::endl;
600  }
601 
604  public: void TopicList(std::vector<std::string> &_topics) const
605  {
606  this->WaitForInit();
607  std::lock_guard<std::mutex> lock(this->mutex);
608  this->info.TopicList(_topics);
609  }
610 
613  public: void WaitForInit() const
614  {
615  std::unique_lock<std::mutex> lk(this->mutex);
616 
617  if (!this->initialized)
618  {
619  this->initializedCv.wait(lk, [this]{return this->initialized;});
620  }
621  }
622 
626  private: void UpdateActivity()
627  {
628  // The UUIDs of the processes that have expired.
630 
631  // A copy of the disconnection callback.
632  DiscoveryCallback<Pub> disconnectCb;
633 
635 
636  {
637  std::lock_guard<std::mutex> lock(this->mutex);
638 
639  if (now < this->timeNextActivity)
640  return;
641 
642  disconnectCb = this->disconnectionCb;
643 
644  for (auto it = this->activity.cbegin(); it != this->activity.cend();)
645  {
646  // Elapsed time since the last update from this publisher.
647  auto elapsed = now - it->second;
648 
649  // This publisher has expired.
650  if (std::chrono::duration_cast<std::chrono::milliseconds>
651  (elapsed).count() > this->silenceInterval)
652  {
653  // Remove all the info entries for this process UUID.
654  this->info.DelPublishersByProc(it->first);
655 
656  uuids.push_back(it->first);
657 
658  // Remove the activity entry.
659  this->activity.erase(it++);
660  }
661  else
662  ++it;
663  }
664 
665  this->timeNextActivity = std::chrono::steady_clock::now() +
666  std::chrono::milliseconds(this->activityInterval);
667  }
668 
669  if (!disconnectCb)
670  return;
671 
672  // Notify without topic information. This is useful to inform the
673  // client that a remote node is gone, even if we were not
674  // interested in its topics.
675  for (auto const &uuid : uuids)
676  {
677  Pub publisher;
678  publisher.SetPUuid(uuid);
679  disconnectCb(publisher);
680  }
681  }
682 
684  private: void UpdateHeartbeat()
685  {
687 
688  {
689  std::lock_guard<std::mutex> lock(this->mutex);
690 
691  if (now < this->timeNextHeartbeat)
692  return;
693  }
694 
695  Publisher pub("", "", this->pUuid, "", AdvertiseOptions());
696  this->SendMsg(DestinationType::ALL, msgs::Discovery::HEARTBEAT, pub);
697 
699  {
700  std::lock_guard<std::mutex> lock(this->mutex);
701 
702  // Re-advertise topics that are advertised inside this process.
703  this->info.PublishersByProc(this->pUuid, nodes);
704  }
705 
706  for (const auto &topic : nodes)
707  {
708  for (const auto &node : topic.second)
709  {
710  this->SendMsg(DestinationType::ALL,
711  msgs::Discovery::ADVERTISE, node);
712  }
713  }
714 
715  {
716  std::lock_guard<std::mutex> lock(this->mutex);
717  if (!this->initialized)
718  {
719  if (this->numHeartbeatsUninitialized == 2u)
720  {
721  // We consider discovery initialized after two heartbeat cycles.
722  this->initialized = true;
723 
724  // Notify anyone waiting for the initialization phase to finish.
725  this->initializedCv.notify_all();
726  }
727  ++this->numHeartbeatsUninitialized;
728  }
729 
730  this->timeNextHeartbeat = std::chrono::steady_clock::now() +
731  std::chrono::milliseconds(this->heartbeatInterval);
732  }
733  }
734 
744  private: int NextTimeout() const
745  {
746  auto now = std::chrono::steady_clock::now();
747  auto timeUntilNextHeartbeat = this->timeNextHeartbeat - now;
748  auto timeUntilNextActivity = this->timeNextActivity - now;
749 
750  int t = static_cast<int>(
751  std::chrono::duration_cast<std::chrono::milliseconds>
752  (std::min(timeUntilNextHeartbeat, timeUntilNextActivity)).count());
753  int t2 = std::min(t, this->kTimeout);
754  return std::max(t2, 0);
755  }
756 
758  private: void RecvMessages()
759  {
760  bool timeToExit = false;
761  bool recvFailing = false;
762  while (!timeToExit)
763  {
764  // Calculate the timeout.
765  int timeout = this->NextTimeout();
766 
767  if (pollSockets(this->sockets, timeout))
768  {
769  // A failed socket stays readable (e.g. one that macOS has
770  // defunct), so wait before polling it again.
771  if (!this->RecvDiscoveryUpdate(recvFailing))
772  {
774  std::chrono::milliseconds(this->kTimeout));
775  }
776 
777  if (this->verbose)
778  this->PrintCurrentState();
779  }
780 
781  this->UpdateHeartbeat();
782  this->UpdateActivity();
783 
784  // Is it time to exit?
785  {
786  std::lock_guard<std::mutex> lock(this->exitMutex);
787  if (this->exit)
788  timeToExit = true;
789  }
790  }
791  }
792 
797  private: bool RecvDiscoveryUpdate(bool &_failing)
798  {
799  char rcvStr[Discovery::kMaxRcvStr];
800  sockaddr_in clntAddr;
801  socklen_t addrLen = sizeof(clntAddr);
802 
803  int64_t received = recvfrom(this->sockets.at(0),
804  reinterpret_cast<raw_type *>(rcvStr),
805  this->kMaxRcvStr, 0,
806  reinterpret_cast<sockaddr *>(&clntAddr),
807  reinterpret_cast<socklen_t *>(&addrLen));
808  if (received > 0)
809  {
810  uint16_t len = 0;
811  memcpy(&len, &rcvStr[0], sizeof(len));
812 
813  // Ignition Transport delimits each discovery message with a
814  // frame_delimiter that contains byte size information.
815  // A discovery message has the form:
816  //
817  // <frame_delimiter><frame_body>
818  //
819  // Ignition Transport version < 8 sends a frame delimiter that
820  // contains the value of sizeof(frame_delimiter)
821  // + sizeof(frame_body). In other words, the frame_delimiter
822  // contains a value that represents the total size of the
823  // frame_body and frame_delimiter in bytes.
824  //
825  // Ignition Transport version >= 8 sends a frame_delimiter
826  // that contains the value of sizeof(frame_body). In other
827  // words, the frame_delimiter contains a value that represents
828  // the total size of only the frame_body.
829  //
830  // It is possible that two incompatible versions of Ignition
831  // Transport exist on the same network. If we receive an
832  // unexpected size, then we ignore the message.
833 
834  // If-condition for version 8+
835  if (len + sizeof(len) == static_cast<uint16_t>(received))
836  {
837  std::string srcAddr = inet_ntoa(clntAddr.sin_addr);
838  uint16_t srcPort = ntohs(clntAddr.sin_port);
839 
840  if (this->verbose)
841  {
842  std::cout << "\nReceived discovery update from "
843  << srcAddr << ": " << srcPort << std::endl;
844  }
845 
846  this->DispatchDiscoveryMsg(srcAddr, rcvStr + sizeof(len), len);
847  }
848  }
849  else
850  {
851  // An empty read carries no discovery frame. A socket that the OS
852  // has shut down keeps returning errors or empty reads.
853  if (!_failing)
854  {
855  std::cerr << "Discovery::RecvDiscoveryUpdate() failed ("
856  << (received < 0 ? strerror(errno) : "empty read")
857  << "). If the OS shut down this process's sockets "
858  << "(macOS does this under network memory pressure), "
859  << "discovery won't recover until the process restarts."
860  << std::endl;
861  }
862  _failing = true;
863  return false;
864  }
865  _failing = false;
866  return true;
867  }
868 
873  private: void DispatchDiscoveryMsg(const std::string &_fromIp,
874  char *_msg, uint16_t _len)
875  {
876  gz::msgs::Discovery msg;
877 
878  // Parse the message, and return if parsing failed. Parsing could
879  // fail when another discovery node is publishing messages using an
880  // older (or newer) format.
881  if (!msg.ParseFromArray(_msg, _len))
882  return;
883 
884  // Discard the message if the wire protocol is different than mine.
885  if (this->Version() != msg.version())
886  return;
887 
888  std::string recvPUuid = msg.process_uuid();
889 
890  // Discard our own discovery messages.
891  if (recvPUuid == this->pUuid)
892  return;
893 
894  // Forwarding summary:
895  // - From a unicast peer -> to multicast group (with NO_RELAY flag).
896  // - From multicast group -> to unicast peers (with RELAY flag).
897 
898  // If the RELAY flag is set, this discovery message is coming via a
899  // unicast transmission. In this case, we don't process it, we just
900  // forward it to the multicast group, and it will be dispatched once
901  // received there. Note that we also unset the RELAY flag and set the
902  // NO_RELAY flag, to avoid forwarding the message anymore.
903  if (msg.has_flags() && msg.flags().relay())
904  {
905  // Unset the RELAY flag in the header and set the NO_RELAY.
906  msg.mutable_flags()->set_relay(false);
907  msg.mutable_flags()->set_no_relay(true);
908  this->SendMulticast(msg);
909 
910  // A unicast peer contacted me. I need to save its address for
911  // sending future messages in the future.
912  this->AddRelayAddress(_fromIp);
913  return;
914  }
915  // If we are receiving this discovery message via the multicast channel
916  // and the NO_RELAY flag is not set, we forward this message via unicast
917  // to all our relays. Note that this is the most common case, where we
918  // receive a regular multicast message and we forward it to any remote
919  // relays.
920  else if (!msg.has_flags() || !msg.flags().no_relay())
921  {
922  msg.mutable_flags()->set_relay(true);
923  this->SendUnicast(msg);
924  }
925 
926  bool isSenderLocal = (std::find(this->hostInterfaces.begin(),
927  this->hostInterfaces.end(), _fromIp) != this->hostInterfaces.end()) ||
928  (_fromIp.find("127.") == 0);
929 
930  // Update timestamp and cache the callbacks.
931  DiscoveryCallback<Pub> connectCb;
932  DiscoveryCallback<Pub> disconnectCb;
933  DiscoveryCallback<Pub> registerCb;
934  DiscoveryCallback<Pub> unregisterCb;
935  {
936  std::lock_guard<std::mutex> lock(this->mutex);
937  this->activity[recvPUuid] = std::chrono::steady_clock::now();
938  connectCb = this->connectionCb;
939  disconnectCb = this->disconnectionCb;
940  registerCb = this->registrationCb;
941  unregisterCb = this->unregistrationCb;
942  }
943 
944  switch (msg.type())
945  {
946  case msgs::Discovery::ADVERTISE:
947  {
948  // Read the rest of the fields.
949  Pub publisher;
950  publisher.SetFromDiscovery(msg);
951 
952  // Check scope of the topic.
953  if ((publisher.Options().Scope() == Scope_t::PROCESS) ||
954  (publisher.Options().Scope() == Scope_t::HOST &&
955  !isSenderLocal))
956  {
957  return;
958  }
959 
960  // Register an advertised address for the topic.
961  bool added;
962  {
963  std::lock_guard<std::mutex> lock(this->mutex);
964  added = this->info.AddPublisher(publisher);
965  }
966 
967  if (added && connectCb)
968  {
969  // Execute the client's callback.
970  connectCb(publisher);
971  }
972 
973  break;
974  }
975  case msgs::Discovery::SUBSCRIBE:
976  {
977  std::string recvTopic;
978  // Read the topic information.
979  if (msg.has_sub())
980  {
981  recvTopic = msg.sub().topic();
982  }
983  else
984  {
985  std::cerr << "Subscription discovery message is missing "
986  << "Subscriber information.\n";
987  break;
988  }
989 
990  // Check if at least one of my nodes advertises the topic requested.
991  Addresses_M<Pub> addresses;
992  {
993  std::lock_guard<std::mutex> lock(this->mutex);
994  if (!this->info.HasAnyPublishers(recvTopic, this->pUuid))
995  {
996  break;
997  }
998 
999  if (!this->info.Publishers(recvTopic, addresses))
1000  break;
1001  }
1002 
1003  for (const auto &nodeInfo : addresses[this->pUuid])
1004  {
1005  // Check scope of the topic.
1006  if ((nodeInfo.Options().Scope() == Scope_t::PROCESS) ||
1007  (nodeInfo.Options().Scope() == Scope_t::HOST &&
1008  !isSenderLocal))
1009  {
1010  continue;
1011  }
1012 
1013  // Answer an ADVERTISE message.
1014  this->SendMsg(DestinationType::ALL,
1015  msgs::Discovery::ADVERTISE, nodeInfo);
1016  }
1017 
1018  break;
1019  }
1020  case msgs::Discovery::NEW_CONNECTION:
1021  {
1022  // Read the rest of the fields.
1023  Pub publisher;
1024  publisher.SetFromDiscovery(msg);
1025 
1026  if (registerCb)
1027  registerCb(publisher);
1028 
1029  break;
1030  }
1031  case msgs::Discovery::END_CONNECTION:
1032  {
1033  // Read the rest of the fields.
1034  Pub publisher;
1035  publisher.SetFromDiscovery(msg);
1036 
1037  if (unregisterCb)
1038  unregisterCb(publisher);
1039 
1040  break;
1041  }
1042  case msgs::Discovery::HEARTBEAT:
1043  {
1044  // The timestamp has already been updated.
1045  break;
1046  }
1047  case msgs::Discovery::BYE:
1048  {
1049  // Remove the activity entry for this publisher.
1050  {
1051  std::lock_guard<std::mutex> lock(this->mutex);
1052  this->activity.erase(recvPUuid);
1053  }
1054 
1055  if (disconnectCb)
1056  {
1057  Pub pub;
1058  pub.SetPUuid(recvPUuid);
1059  // Notify the new disconnection.
1060  disconnectCb(pub);
1061  }
1062 
1063  // Remove the address entry for this topic.
1064  {
1065  std::lock_guard<std::mutex> lock(this->mutex);
1066  this->info.DelPublishersByProc(recvPUuid);
1067  }
1068 
1069  break;
1070  }
1071  case msgs::Discovery::UNADVERTISE:
1072  {
1073  // Read the address.
1074  Pub publisher;
1075  publisher.SetFromDiscovery(msg);
1076 
1077  // Check scope of the topic.
1078  if ((publisher.Options().Scope() == Scope_t::PROCESS) ||
1079  (publisher.Options().Scope() == Scope_t::HOST &&
1080  !isSenderLocal))
1081  {
1082  return;
1083  }
1084 
1085  if (disconnectCb)
1086  {
1087  // Notify the new disconnection.
1088  disconnectCb(publisher);
1089  }
1090 
1091  // Remove the address entry for this topic.
1092  {
1093  std::lock_guard<std::mutex> lock(this->mutex);
1094  this->info.DelPublisherByNode(publisher.Topic(),
1095  publisher.PUuid(), publisher.NUuid());
1096  }
1097 
1098  break;
1099  }
1100  default:
1101  {
1102  std::cerr << "Unknown message type [" << msg.type() << "].\n";
1103  break;
1104  }
1105  }
1106  }
1107 
1114  private: template<typename T>
1115  void SendMsg(const DestinationType &_destType,
1116  const msgs::Discovery::Type _type,
1117  const T &_pub) const
1118  {
1119  gz::msgs::Discovery discoveryMsg;
1120  discoveryMsg.set_version(this->Version());
1121  discoveryMsg.set_type(_type);
1122  discoveryMsg.set_process_uuid(this->pUuid);
1123 
1124  switch (_type)
1125  {
1126  case msgs::Discovery::ADVERTISE:
1127  case msgs::Discovery::UNADVERTISE:
1128  case msgs::Discovery::NEW_CONNECTION:
1129  case msgs::Discovery::END_CONNECTION:
1130  {
1131  _pub.FillDiscovery(discoveryMsg);
1132  break;
1133  }
1134  case msgs::Discovery::SUBSCRIBE:
1135  {
1136  discoveryMsg.mutable_sub()->set_topic(_pub.Topic());
1137  break;
1138  }
1139  case msgs::Discovery::HEARTBEAT:
1140  case msgs::Discovery::BYE:
1141  break;
1142  default:
1143  std::cerr << "Discovery::SendMsg() error: Unrecognized message"
1144  << " type [" << _type << "]" << std::endl;
1145  return;
1146  }
1147 
1148  if (_destType == DestinationType::MULTICAST ||
1149  _destType == DestinationType::ALL)
1150  {
1151  this->SendMulticast(discoveryMsg);
1152  }
1153 
1154  // Send the discovery message to the unicast relays.
1155  if (_destType == DestinationType::UNICAST ||
1156  _destType == DestinationType::ALL)
1157  {
1158  // Set the RELAY flag in the header.
1159  discoveryMsg.mutable_flags()->set_relay(true);
1160  this->SendUnicast(discoveryMsg);
1161  }
1162 
1163  if (this->verbose)
1164  {
1165  std::cout << "\t* Sending " << msgs::ToString(_type)
1166  << " msg [" << _pub.Topic() << "]" << std::endl;
1167  }
1168  }
1169 
1172  private: void SendUnicast(const msgs::Discovery &_msg) const
1173  {
1174  uint16_t msgSize;
1175 
1176 #if GOOGLE_PROTOBUF_VERSION >= 3004000
1177  size_t msgSizeFull = _msg.ByteSizeLong();
1178 #else
1179  int msgSizeFull = _msg.ByteSize();
1180 #endif
1181  if (msgSizeFull + sizeof(msgSize) > this->kMaxRcvStr)
1182  {
1183  std::cerr << "Discovery message too large to send. Discovery won't "
1184  << "work. This shouldn't happen.\n";
1185  return;
1186  }
1187  msgSize = msgSizeFull;
1188 
1189  uint16_t totalSize = sizeof(msgSize) + msgSize;
1190  char *buffer = static_cast<char *>(new char[totalSize]);
1191  memcpy(&buffer[0], &msgSize, sizeof(msgSize));
1192 
1193  if (_msg.SerializeToArray(buffer + sizeof(msgSize), msgSize))
1194  {
1195  // Send the discovery message to the unicast relays.
1196  for (const auto &sockAddr : this->relayAddrs)
1197  {
1198  errno = 0;
1199  auto sent = sendto(this->sockets.at(0),
1200  reinterpret_cast<const raw_type *>(
1201  reinterpret_cast<const unsigned char*>(buffer)),
1202  totalSize, 0,
1203  reinterpret_cast<const sockaddr *>(&sockAddr),
1204  sizeof(sockAddr));
1205 
1206  if (sent != totalSize)
1207  {
1208  std::cerr << "Exception sending a unicast message:" << std::endl;
1209  std::cerr << " Return value: " << sent << std::endl;
1210  std::cerr << " Error code: " << strerror(errno) << std::endl;
1211  break;
1212  }
1213  }
1214  }
1215  else
1216  {
1217  std::cerr << "Discovery::SendUnicast: Error serializing data."
1218  << std::endl;
1219  }
1220 
1221  delete [] buffer;
1222  }
1223 
1226  private: void SendMulticast(const msgs::Discovery &_msg) const
1227  {
1228  uint16_t msgSize;
1229 
1230 #if GOOGLE_PROTOBUF_VERSION >= 3004000
1231  size_t msgSizeFull = _msg.ByteSizeLong();
1232 #else
1233  int msgSizeFull = _msg.ByteSize();
1234 #endif
1235  if (msgSizeFull + sizeof(msgSize) > this->kMaxRcvStr)
1236  {
1237  std::cerr << "Discovery message too large to send. Discovery won't "
1238  << "work. This shouldn't happen.\n";
1239  return;
1240  }
1241 
1242  msgSize = msgSizeFull;
1243  uint16_t totalSize = sizeof(msgSize) + msgSize;
1244  char *buffer = static_cast<char *>(new char[totalSize]);
1245  memcpy(&buffer[0], &msgSize, sizeof(msgSize));
1246 
1247  if (_msg.SerializeToArray(buffer + sizeof(msgSize), msgSize))
1248  {
1249  // Send the discovery message to the multicast group through all the
1250  // sockets.
1251  for (const auto &sock : this->Sockets())
1252  {
1253  errno = 0;
1254  if (sendto(sock, reinterpret_cast<const raw_type *>(
1255  reinterpret_cast<const unsigned char*>(buffer)),
1256  totalSize, 0,
1257  reinterpret_cast<const sockaddr *>(this->MulticastAddr()),
1258  sizeof(*(this->MulticastAddr()))) != totalSize)
1259  {
1260  // Ignore EPERM and ENOBUFS errors.
1261  //
1262  // See issue #106
1263  //
1264  // Rationale drawn from:
1265  //
1266  // * https://groups.google.com/forum/#!topic/comp.protocols.tcp-ip/Qou9Sfgr77E
1267  // * https://stackoverflow.com/questions/16555101/sendto-dgrams-do-not-block-for-enobufs-on-osx
1268  if (errno != EPERM && errno != ENOBUFS)
1269  {
1270  std::cerr << "Exception sending a multicast message:"
1271  << strerror(errno) << std::endl;
1272  }
1273  break;
1274  }
1275  }
1276  }
1277  else
1278  {
1279  std::cerr << "Discovery::SendMulticast: Error serializing data."
1280  << std::endl;
1281  }
1282 
1283  delete [] buffer;
1284  }
1285 
1288  private: const std::vector<int> &Sockets() const
1289  {
1290  return this->sockets;
1291  }
1292 
1295  private: const sockaddr_in *MulticastAddr() const
1296  {
1297  return &this->mcastAddr;
1298  }
1299 
1302  private: uint8_t Version() const
1303  {
1304  static std::string ignStats;
1305  static int topicStats =
1306  (env("IGN_TRANSPORT_TOPIC_STATISTICS", ignStats) && ignStats == "1");
1307  return this->kWireVersion + (topicStats * 100);
1308  }
1309 
1314  private: bool RegisterNetIface(const std::string &_ip)
1315  {
1316  // Make a new socket for sending discovery information.
1317  int sock = static_cast<int>(socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP));
1318  if (sock < 0)
1319  {
1320  std::cerr << "Socket creation failed." << std::endl;
1321  return false;
1322  }
1323 
1324 #ifdef SO_NOSIGPIPE
1325  // Fail sends with EPIPE instead of raising SIGPIPE when the OS shuts
1326  // this socket down, as macOS does when it runs out of network buffers.
1327  int noSigPipe = 1;
1328  if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe,
1329  sizeof(noSigPipe)) != 0)
1330  {
1331  std::cerr << "Error setting socket option (SO_NOSIGPIPE)."
1332  << std::endl;
1333  }
1334 #endif
1335 
1336  // Socket option: IP_MULTICAST_IF.
1337  // This socket option needs to be applied to each socket used to send
1338  // data. This option selects the source interface for outgoing messages.
1339  struct in_addr ifAddr;
1340  ifAddr.s_addr = inet_addr(_ip.c_str());
1341  if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF,
1342  reinterpret_cast<const char*>(&ifAddr), sizeof(ifAddr)) != 0)
1343  {
1344  std::cerr << "Error setting socket option (IP_MULTICAST_IF)."
1345  << std::endl;
1346  return false;
1347  }
1348 
1349  this->sockets.push_back(sock);
1350 
1351  // Join the multicast group. We have to do it for each network interface
1352  // but we can do it on the same socket. We will use the socket at
1353  // position 0 for receiving multicast information.
1354  struct ip_mreq group;
1355  group.imr_multiaddr.s_addr =
1356  inet_addr(this->multicastGroup.c_str());
1357  group.imr_interface.s_addr = inet_addr(_ip.c_str());
1358  if (setsockopt(this->sockets.at(0), IPPROTO_IP, IP_ADD_MEMBERSHIP,
1359  reinterpret_cast<const char*>(&group), sizeof(group)) != 0)
1360  {
1361  std::cerr << "Error setting socket option (IP_ADD_MEMBERSHIP)."
1362  << std::endl;
1363  return false;
1364  }
1365 
1366  return true;
1367  }
1368 
1371  private: void AddRelayAddress(const std::string &_ip)
1372  {
1373  // Sanity check: Make sure that this IP address is not already saved.
1374  for (auto const &addr : this->relayAddrs)
1375  {
1376  if (addr.sin_addr.s_addr == inet_addr(_ip.c_str()))
1377  return;
1378  }
1379 
1380  sockaddr_in addr;
1381  memset(&addr, 0, sizeof(addr));
1382  addr.sin_family = AF_INET;
1383  addr.sin_addr.s_addr = inet_addr(_ip.c_str());
1384  addr.sin_port = htons(static_cast<u_short>(this->port));
1385 
1386  this->relayAddrs.push_back(addr);
1387  }
1388 
1392  private: static const unsigned int kDefActivityInterval = 100;
1393 
1397  private: static const unsigned int kDefHeartbeatInterval = 1000;
1398 
1402  private: static const unsigned int kDefSilenceInterval = 3000;
1403 
1405  private: std::string multicastGroup;
1406 
1408  private: const int kTimeout = 250;
1409 
1411  private: static const uint16_t kMaxRcvStr =
1413 
1416  private: static const uint8_t kWireVersion = 10;
1417 
1419  private: int port;
1420 
1422  private: std::string hostAddr;
1423 
1425  private: std::vector<std::string> hostInterfaces;
1426 
1428  private: std::string pUuid;
1429 
1433  private: unsigned int silenceInterval;
1434 
1438  private: unsigned int activityInterval;
1439 
1443  private: unsigned int heartbeatInterval;
1444 
1446  private: DiscoveryCallback<Pub> connectionCb;
1447 
1449  private: DiscoveryCallback<Pub> disconnectionCb;
1450 
1452  private: DiscoveryCallback<Pub> registrationCb;
1453 
1455  private: DiscoveryCallback<Pub> unregistrationCb;
1456 
1458  private: TopicStorage<Pub> info;
1459 
1465 
1467  private: bool verbose;
1468 
1470  private: std::vector<int> sockets;
1471 
1473  private: sockaddr_in mcastAddr;
1474 
1476  private: std::vector<sockaddr_in> relayAddrs;
1477 
1479  private: mutable std::mutex mutex;
1480 
1482  private: std::thread threadReception;
1483 
1485  private: Timestamp timeNextHeartbeat;
1486 
1488  private: Timestamp timeNextActivity;
1489 
1491  private: std::mutex exitMutex;
1492 
1497  private: bool initialized;
1498 
1500  private: unsigned int numHeartbeatsUninitialized;
1501 
1503  private: mutable std::condition_variable initializedCv;
1504 
1506  private: bool exit;
1507 
1509  private: bool enabled;
1510  };
1511 
1515 
1519  }
1520  }
1521 }
1522 
1523 #endif
T boolalpha(T... args)
T c_str(T... args)
A class for customizing the publication options for a topic or service advertised....
Definition: gz/transport/AdvertiseOptions.hh:58
A discovery class that implements a distributed topic discovery protocol. It uses UDP multicast for s...
Definition: gz/transport/Discovery.hh:118
void WaitForInit() const
Check if ready/initialized. If not, then wait on the initializedCv condition variable.
Definition: gz/transport/Discovery.hh:613
void Start()
Start the discovery service. You probably want to register the callbacks for receiving discovery noti...
Definition: gz/transport/Discovery.hh:281
bool Advertise(const Pub &_publisher)
Advertise a new message.
Definition: gz/transport/Discovery.hh:305
unsigned int ActivityInterval() const
The discovery checks the validity of the topic information every 'activity interval' milliseconds.
Definition: gz/transport/Discovery.hh:468
unsigned int HeartbeatInterval() const
Each node broadcasts periodic heartbeats to keep its topic information alive in other nodes....
Definition: gz/transport/Discovery.hh:479
const TopicStorage< Pub > & Info() const
Get the discovery information.
Definition: gz/transport/Discovery.hh:403
std::string HostAddr() const
Get the IP address of this host.
Definition: gz/transport/Discovery.hh:458
void Unregister(const MessagePublisher &_pub) const
Unregister a node from this process as a remote subscriber.
Definition: gz/transport/Discovery.hh:395
std::map< std::string, Timestamp > activity
Activity information. Every time there is a message from a remote node, its activity information is u...
Definition: gz/transport/Discovery.hh:1464
void Register(const MessagePublisher &_pub) const
Register a node from this process as a remote subscriber.
Definition: gz/transport/Discovery.hh:387
bool Unadvertise(const std::string &_topic, const std::string &_nUuid)
Unadvertise a new message. Broadcast a discovery message that will cancel all the discovery informati...
Definition: gz/transport/Discovery.hh:427
void SetHeartbeatInterval(const unsigned int _ms)
Set the heartbeat interval.
Definition: gz/transport/Discovery.hh:507
unsigned int SilenceInterval() const
Get the maximum time allowed without receiving any discovery information from a node before canceling...
Definition: gz/transport/Discovery.hh:489
void PrintCurrentState() const
Print the current discovery state.
Definition: gz/transport/Discovery.hh:561
void SetSilenceInterval(const unsigned int _ms)
Set the maximum silence interval.
Definition: gz/transport/Discovery.hh:516
bool Publishers(const std::string &_topic, Addresses_M< Pub > &_publishers) const
Get all the publishers' information known for a given topic.
Definition: gz/transport/Discovery.hh:413
Discovery(const std::string &_pUuid, const std::string &_ip, const int _port, const bool _verbose=false)
Constructor.
Definition: gz/transport/Discovery.hh:125
void RegistrationsCb(const DiscoveryCallback< Pub > &_cb)
Register a callback to receive an event when a new remote node subscribes to a topic within this proc...
Definition: gz/transport/Discovery.hh:545
void ConnectionsCb(const DiscoveryCallback< Pub > &_cb)
Register a callback to receive discovery connection events. Each time a new topic is connected,...
Definition: gz/transport/Discovery.hh:526
bool Discover(const std::string &_topic) const
Request discovery information about a topic. When using this method, the user might want to use SetCo...
Definition: gz/transport/Discovery.hh:337
void SetActivityInterval(const unsigned int _ms)
Set the activity interval.
Definition: gz/transport/Discovery.hh:498
void DisconnectionsCb(const DiscoveryCallback< Pub > &_cb)
Register a callback to receive discovery disconnection events. Each time a topic is no longer active,...
Definition: gz/transport/Discovery.hh:536
void UnregistrationsCb(const DiscoveryCallback< Pub > &_cb)
Register a callback to receive an event when a remote node unsubscribes to a topic within this proces...
Definition: gz/transport/Discovery.hh:554
virtual ~Discovery()
Destructor.
Definition: gz/transport/Discovery.hh:250
void TopicList(std::vector< std::string > &_topics) const
Get the list of topics currently advertised in the network.
Definition: gz/transport/Discovery.hh:604
This class stores all the information about a message publisher.
Definition: gz/transport/Publisher.hh:177
This class stores all the information about a publisher. It stores the topic name that publishes,...
Definition: gz/transport/Publisher.hh:40
T duration_cast(T... args)
T empty(T... args)
T endl(T... args)
T erase(T... args)
T find(T... args)
void raw_type
Definition: gz/transport/Discovery.hh:45
T lock(T... args)
T max(T... args)
T memcpy(T... args)
T memset(T... args)
T min(T... args)
std::chrono::steady_clock::time_point Timestamp
Definition: gz/transport/TransportTypes.hh:153
std::vector< std::string > split(const std::string &_orig, char _delim)
split at a one character delimiter to get a vector of something
bool env(const std::string &_name, std::string &_value)
Find the environment variable '_name' and return its value.
@ ALL
Topic/service available to any subscriber (default scope).
@ HOST
Topic/service only available to subscribers in the same machine as the publisher.
@ PROCESS
Topic/service only available to subscribers in the same process as the publisher.
std::vector< std::string > determineInterfaces()
Determine the list of network interfaces for this machine. Reference: https://github....
DestinationType
Options for sending discovery messages.
Definition: gz/transport/Discovery.hh:89
@ UNICAST
Send data via unicast only.
@ ALL
Send data via unicast and multicast.
@ MULTICAST
Send data via multicast only.
bool pollSockets(const std::vector< int > &_sockets, const int _timeout)
std::string determineHost()
Determine IP or hostname. Reference: https://github.com/ros/ros_comm/blob/hydro-devel/clients/ roscpp...
Definition: gz/transport/AdvertiseOptions.hh:29
STL namespace.
T push_back(T... args)
T sleep_for(T... args)
T strerror(T... args)