Gazebo Transport

API Reference

13.7.0
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 <type_traits>
70 #include <utility>
71 #include <vector>
72 
73 #include <gz/msgs/Utility.hh>
74 
75 #include "gz/transport/config.hh"
76 #include "gz/transport/Export.hh"
77 #include "gz/transport/Helpers.hh"
78 #include "gz/transport/NetUtils.hh"
82 
83 namespace gz
84 {
85  namespace transport
86  {
87  // Inline bracket to help doxygen filtering.
88  inline namespace GZ_TRANSPORT_VERSION_NAMESPACE {
90  enum class DestinationType
91  {
93  UNICAST,
95  MULTICAST,
97  ALL
98  };
99 
100  //
106  bool GZ_TRANSPORT_VISIBLE pollSockets(
107  const std::vector<int> &_sockets,
108  const int _timeout);
109 
118  template<typename Pub>
119  class Discovery
120  {
127  public: Discovery(const std::string &_pUuid,
128  const std::string &_ip,
129  const int _port,
130  const bool _verbose = false)
131  : multicastGroup(_ip),
132  port(_port),
133  hostAddr(determineHost()),
134  pUuid(_pUuid),
135  silenceInterval(kDefSilenceInterval),
136  activityInterval(kDefActivityInterval),
137  heartbeatInterval(kDefHeartbeatInterval),
138  connectionCb(nullptr),
139  disconnectionCb(nullptr),
140  verbose(_verbose),
141  initialized(false),
142  numHeartbeatsUninitialized(0),
143  exit(false),
144  enabled(false)
145  {
146  std::string gzIp;
147  if (env("GZ_IP", gzIp) && !gzIp.empty())
148  {
149  this->hostInterfaces = {gzIp};
150  }
151  else
152  {
153  // Get the list of network interfaces in this host.
154  this->hostInterfaces = determineInterfaces();
155  }
156 
157 #ifdef _WIN32
158  WORD wVersionRequested;
159  WSADATA wsaData;
160 
161  // Request WinSock v2.2.
162  wVersionRequested = MAKEWORD(2, 2);
163  // Load WinSock DLL.
164  if (WSAStartup(wVersionRequested, &wsaData) != 0)
165  {
166  std::cerr << "Unable to load WinSock DLL" << std::endl;
167  return;
168  }
169 #endif
170  for (const auto &netIface : this->hostInterfaces)
171  {
172  auto succeed = this->RegisterNetIface(netIface);
173 
174  // If the IP address that we're selecting as the main IP address of
175  // the host is invalid, we change it to 127.0.0.1 .
176  // This is probably because GZ_IP is set to a wrong value.
177  if (netIface == this->hostAddr && !succeed)
178  {
179  this->RegisterNetIface("127.0.0.1");
180  std::cerr << "Did you set the environment variable GZ_IP with a "
181  << "correct IP address? " << std::endl
182  << " [" << netIface << "] seems an invalid local IP "
183  << "address." << std::endl
184  << " Using 127.0.0.1 as hostname." << std::endl;
185  this->hostAddr = "127.0.0.1";
186  }
187  }
188 
189  // Socket option: SO_REUSEADDR. This options is used only for receiving
190  // data. We can reuse the same socket for receiving multicast data from
191  // multiple interfaces. We will use the socket at position 0 for
192  // receiving data.
193  int reuseAddr = 1;
194  if (setsockopt(this->sockets.at(0), SOL_SOCKET, SO_REUSEADDR,
195  reinterpret_cast<const char *>(&reuseAddr), sizeof(reuseAddr)) != 0)
196  {
197  std::cerr << "Error setting socket option (SO_REUSEADDR)."
198  << std::endl;
199  return;
200  }
201 
202 #ifdef SO_REUSEPORT
203  // Socket option: SO_REUSEPORT. This options is used only for receiving
204  // data. We can reuse the same socket for receiving multicast data from
205  // multiple interfaces. We will use the socket at position 0 for
206  // receiving data.
207  int reusePort = 1;
208  // cppcheck-suppress ConfigurationNotChecked
209  if (setsockopt(this->sockets.at(0), SOL_SOCKET, SO_REUSEPORT,
210  reinterpret_cast<const char *>(&reusePort), sizeof(reusePort)) != 0)
211  {
212  std::cerr << "Error setting socket option (SO_REUSEPORT)."
213  << std::endl;
214  return;
215  }
216 #endif
217  // Bind the first socket to the discovery port.
218  sockaddr_in localAddr;
219  memset(&localAddr, 0, sizeof(localAddr));
220  localAddr.sin_family = AF_INET;
221  localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
222  localAddr.sin_port = htons(static_cast<u_short>(this->port));
223 
224  if (bind(this->sockets.at(0),
225  reinterpret_cast<sockaddr *>(&localAddr), sizeof(sockaddr_in)) < 0)
226  {
227  std::cerr << "Binding to a local port failed." << std::endl;
228  return;
229  }
230 
231  // Set 'mcastAddr' to the multicast discovery group.
232  memset(&this->mcastAddr, 0, sizeof(this->mcastAddr));
233  this->mcastAddr.sin_family = AF_INET;
234  this->mcastAddr.sin_addr.s_addr =
235  inet_addr(this->multicastGroup.c_str());
236  this->mcastAddr.sin_port = htons(static_cast<u_short>(this->port));
237 
239  std::string gzRelay;
240  if (env("GZ_RELAY", gzRelay) && !gzRelay.empty())
241  {
242  relays = transport::split(gzRelay, ':');
243  }
244 
245  // Register all unicast relays.
246  for (auto const &relayAddr : relays)
247  this->AddRelayAddress(relayAddr);
248 
249  if (this->verbose)
250  this->PrintCurrentState();
251  }
252 
254  public: virtual ~Discovery()
255  {
256  // Tell the service thread to terminate.
257  this->exitMutex.lock();
258  this->exit = true;
259  this->exitMutex.unlock();
260 
261  // Wait for the service threads to finish before exit.
262  if (this->threadReception.joinable())
263  this->threadReception.join();
264 
265  // Broadcast a BYE message to trigger the remote cancellation of
266  // all our advertised topics.
267  this->SendMsg(DestinationType::ALL, msgs::Discovery::BYE,
268  Publisher("", "", this->pUuid, "", AdvertiseOptions()));
269 
270  // Close sockets.
271  for (const auto &sock : this->sockets)
272  {
273 #ifdef _WIN32
274  closesocket(sock);
275  WSACleanup();
276 #else
277  close(sock);
278 #endif
279  }
280  }
281 
285  public: void Start()
286  {
287  {
288  std::lock_guard<std::mutex> lock(this->mutex);
289 
290  // The service is already running.
291  if (this->enabled)
292  return;
293 
294  this->enabled = true;
295  }
296 
297  auto now = std::chrono::steady_clock::now();
298  this->timeNextHeartbeat = now;
299  this->timeNextActivity = now;
300 
301  // Start the thread that receives discovery information.
302  this->threadReception = std::thread(&Discovery::RecvMessages, this);
303  }
304 
309  public: bool Advertise(const Pub &_publisher)
310  {
312 
313  {
314  std::lock_guard<std::mutex> lock(this->mutex);
315 
316  if (!this->enabled)
317  return false;
318 
319  // Add the addressing information (local publisher).
320  if (!this->info.AddPublisher(_publisher))
321  return false;
322 
323  cb = this->connectionCb;
324  }
325 
326  if (cb)
327  cb(_publisher);
328 
329  // Only advertise a message outside this process if the scope
330  // is not 'Process'
331  if (_publisher.Options().Scope() != Scope_t::PROCESS)
332  this->SendMsg(DestinationType::ALL, msgs::Discovery::ADVERTISE,
333  _publisher);
334 
335  return true;
336  }
337 
348  public: bool Discover(const std::string &_topic) const
349  {
351  bool found;
352  Addresses_M<Pub> addresses;
353 
354  {
355  std::lock_guard<std::mutex> lock(this->mutex);
356 
357  if (!this->enabled)
358  return false;
359 
360  cb = this->connectionCb;
361  }
362 
363  Pub pub;
364  pub.SetTopic(_topic);
365  pub.SetPUuid(this->pUuid);
366 
367  // Send a discovery request.
368  this->SendMsg(DestinationType::ALL, msgs::Discovery::SUBSCRIBE, pub);
369 
370  {
371  std::lock_guard<std::mutex> lock(this->mutex);
372  found = this->info.Publishers(_topic, addresses);
373  }
374 
375  if (found)
376  {
377  // I already have information about this topic.
378  for (const auto &proc : addresses)
379  {
380  for (const auto &node : proc.second)
381  {
382  if (cb)
383  {
384  // Execute the user's callback for a service request. Notice
385  // that we only execute one callback for preventing receive
386  // multiple service responses for a single request.
387  cb(node);
388  }
389  }
390  }
391  }
392 
393  return true;
394  }
395 
398  public: void SendSubscribersRep(const MessagePublisher &_pub) const
399  {
400  this->SendMsg(
401  DestinationType::ALL, msgs::Discovery::SUBSCRIBERS_REP, _pub);
402  }
403 
406  public: void Register(const MessagePublisher &_pub) const
407  {
408  this->SendMsg(
409  DestinationType::ALL, msgs::Discovery::NEW_CONNECTION, _pub);
410  }
411 
414  public: void Unregister(const MessagePublisher &_pub) const
415  {
416  this->SendMsg(
417  DestinationType::ALL, msgs::Discovery::END_CONNECTION, _pub);
418  }
419 
422  public: const TopicStorage<Pub> &Info() const
423  {
424  std::lock_guard<std::mutex> lock(this->mutex);
425  return this->info;
426  }
427 
432  public: bool Publishers(const std::string &_topic,
433  Addresses_M<Pub> &_publishers) const
434  {
435  std::lock_guard<std::mutex> lock(this->mutex);
436  return this->info.Publishers(_topic, _publishers);
437  }
438 
443  public: bool RemoteSubscribers(const std::string &_topic,
444  Addresses_M<Pub> &_subscribers) const
445  {
446  std::lock_guard<std::mutex> lock(this->mutex);
447  return this->remoteSubscribers.Publishers(_topic, _subscribers);
448  }
449 
457  public: bool Unadvertise(const std::string &_topic,
458  const std::string &_nUuid)
459  {
460  Pub inf;
461  {
462  std::lock_guard<std::mutex> lock(this->mutex);
463 
464  if (!this->enabled)
465  return false;
466 
467  // Don't do anything if the topic is not advertised by any of my nodes
468  if (!this->info.Publisher(_topic, this->pUuid, _nUuid, inf))
469  return true;
470 
471  // Remove the topic information.
472  this->info.DelPublisherByNode(_topic, this->pUuid, _nUuid);
473  }
474 
475  // Only unadvertise a message outside this process if the scope
476  // is not 'Process'.
477  if (inf.Options().Scope() != Scope_t::PROCESS)
478  {
479  this->SendMsg(DestinationType::ALL,
480  msgs::Discovery::UNADVERTISE, inf);
481  }
482 
483  return true;
484  }
485 
488  public: std::string HostAddr() const
489  {
490  std::lock_guard<std::mutex> lock(this->mutex);
491  return this->hostAddr;
492  }
493 
498  public: unsigned int ActivityInterval() const
499  {
500  std::lock_guard<std::mutex> lock(this->mutex);
501  return this->activityInterval;
502  }
503 
509  public: unsigned int HeartbeatInterval() const
510  {
511  std::lock_guard<std::mutex> lock(this->mutex);
512  return this->heartbeatInterval;
513  }
514 
519  public: unsigned int SilenceInterval() const
520  {
521  std::lock_guard<std::mutex> lock(this->mutex);
522  return this->silenceInterval;
523  }
524 
528  public: void SetActivityInterval(const unsigned int _ms)
529  {
530  std::lock_guard<std::mutex> lock(this->mutex);
531  this->activityInterval = _ms;
532  }
533 
537  public: void SetHeartbeatInterval(const unsigned int _ms)
538  {
539  std::lock_guard<std::mutex> lock(this->mutex);
540  this->heartbeatInterval = _ms;
541  }
542 
546  public: void SetSilenceInterval(const unsigned int _ms)
547  {
548  std::lock_guard<std::mutex> lock(this->mutex);
549  this->silenceInterval = _ms;
550  }
551 
556  public: void ConnectionsCb(const DiscoveryCallback<Pub> &_cb)
557  {
558  std::lock_guard<std::mutex> lock(this->mutex);
559  this->connectionCb = _cb;
560  }
561 
566  public: void DisconnectionsCb(const DiscoveryCallback<Pub> &_cb)
567  {
568  std::lock_guard<std::mutex> lock(this->mutex);
569  this->disconnectionCb = _cb;
570  }
571 
575  public: void RegistrationsCb(const DiscoveryCallback<Pub> &_cb)
576  {
577  std::lock_guard<std::mutex> lock(this->mutex);
578  this->registrationCb = _cb;
579  }
580 
584  public: void UnregistrationsCb(const DiscoveryCallback<Pub> &_cb)
585  {
586  std::lock_guard<std::mutex> lock(this->mutex);
587  this->unregistrationCb = _cb;
588  }
589 
593  public: void SubscribersCb(const std::function<void()> &_cb)
594  {
595  std::lock_guard<std::mutex> lock(this->mutex);
596  this->subscribersCb = _cb;
597  }
598 
600  public: void PrintCurrentState() const
601  {
602  std::lock_guard<std::mutex> lock(this->mutex);
603 
604  std::cout << "---------------" << std::endl;
605  std::cout << std::boolalpha << "Enabled: "
606  << this->enabled << std::endl;
607  std::cout << "Discovery state" << std::endl;
608  std::cout << "\tUUID: " << this->pUuid << std::endl;
609  std::cout << "Settings" << std::endl;
610  std::cout << "\tActivity: " << this->activityInterval
611  << " ms." << std::endl;
612  std::cout << "\tHeartbeat: " << this->heartbeatInterval
613  << "ms." << std::endl;
614  std::cout << "\tSilence: " << this->silenceInterval
615  << " ms." << std::endl;
616  std::cout << "Known information:" << std::endl;
617  this->info.Print();
618 
619  // Used to calculate the elapsed time.
621 
622  std::cout << "Activity" << std::endl;
623  if (this->activity.empty())
624  std::cout << "\t<empty>" << std::endl;
625  else
626  {
627  for (auto &proc : this->activity)
628  {
629  // Elapsed time since the last update from this publisher.
630  std::chrono::duration<double> elapsed = now - proc.second;
631 
632  std::cout << "\t" << proc.first << std::endl;
633  std::cout << "\t\t" << "Since: " << std::chrono::duration_cast<
634  std::chrono::milliseconds>(elapsed).count() << " ms. ago. "
635  << std::endl;
636  }
637  }
638  std::cout << "---------------" << std::endl;
639  }
640 
644  public: void TopicList(std::vector<std::string> &_topics)
645  {
646  // Request the list of subscribers. This request is only meaningful
647  // for message discovery: nothing answers it on the service
648  // discovery channel.
649  if constexpr (std::is_same_v<Pub, MessagePublisher>)
650  {
651  Publisher pub("", "", this->pUuid, "", AdvertiseOptions());
652  this->SendMsg(
653  DestinationType::ALL, msgs::Discovery::SUBSCRIBERS_REQ, pub);
654  }
655 
656  this->WaitForInit();
657  std::lock_guard<std::mutex> lock(this->mutex);
658  this->info.TopicList(_topics);
659 
660  std::vector<std::string> remoteSubs;
661  this->remoteSubscribers.TopicList(remoteSubs);
662 
663  // Add the remote subscribers
664  for (auto const &t : remoteSubs)
665  {
666  if (std::find(_topics.begin(), _topics.end(), t) == _topics.end())
667  {
668  _topics.push_back(t);
669  }
670  }
671  }
672 
675  public: void WaitForInit() const
676  {
677  std::unique_lock<std::mutex> lk(this->mutex);
678 
679  if (!this->initialized)
680  {
681  this->initializedCv.wait(lk, [this]{return this->initialized;});
682  }
683  }
684 
688  private: void UpdateActivity()
689  {
690  // The UUIDs of the processes that have expired.
692 
693  // A copy of the disconnection callback.
694  DiscoveryCallback<Pub> disconnectCb;
695 
697 
698  {
699  std::lock_guard<std::mutex> lock(this->mutex);
700 
701  if (now < this->timeNextActivity)
702  return;
703 
704  disconnectCb = this->disconnectionCb;
705 
706  for (auto it = this->activity.cbegin(); it != this->activity.cend();)
707  {
708  // Elapsed time since the last update from this publisher.
709  auto elapsed = now - it->second;
710 
711  // This publisher has expired.
712  if (std::chrono::duration_cast<std::chrono::milliseconds>
713  (elapsed).count() > this->silenceInterval)
714  {
715  // Remove all the info entries for this process UUID.
716  this->info.DelPublishersByProc(it->first);
717  this->remoteSubscribers.DelPublishersByProc(it->first);
718 
719  uuids.push_back(it->first);
720 
721  // Remove the activity entry.
722  this->activity.erase(it++);
723  }
724  else
725  ++it;
726  }
727 
728  this->timeNextActivity = std::chrono::steady_clock::now() +
729  std::chrono::milliseconds(this->activityInterval);
730  }
731 
732  if (!disconnectCb)
733  return;
734 
735  // Notify without topic information. This is useful to inform the
736  // client that a remote node is gone, even if we were not
737  // interested in its topics.
738  for (auto const &uuid : uuids)
739  {
740  Pub publisher;
741  publisher.SetPUuid(uuid);
742  disconnectCb(publisher);
743  }
744  }
745 
748  public: void AddRelayAddress(const std::string &_ip)
749  {
750  std::lock_guard<std::mutex> lock(this->mutex);
751  // Sanity check: Make sure that this IP address is not already saved.
752  for (auto const &addr : this->relayAddrs)
753  {
754  if (addr.sin_addr.s_addr == inet_addr(_ip.c_str()))
755  return;
756  }
757 
758  sockaddr_in addr;
759  memset(&addr, 0, sizeof(addr));
760  addr.sin_family = AF_INET;
761  addr.sin_addr.s_addr = inet_addr(_ip.c_str());
762  addr.sin_port = htons(static_cast<u_short>(this->port));
763 
764  this->relayAddrs.push_back(addr);
765  }
766 
767  // \brief Gets this instance's relay addresses.
768  // \return The list of relay addresses.
770  {
772 
773  std::lock_guard<std::mutex> lock(this->mutex);
774 
775  for (auto const &addr : this->relayAddrs) {
776  result.push_back(inet_ntoa(addr.sin_addr));
777  }
778 
779  return result;
780  }
781 
783  private: void UpdateHeartbeat()
784  {
786 
787  {
788  std::lock_guard<std::mutex> lock(this->mutex);
789 
790  if (now < this->timeNextHeartbeat)
791  return;
792  }
793 
794  Publisher pub("", "", this->pUuid, "", AdvertiseOptions());
795  this->SendMsg(DestinationType::ALL, msgs::Discovery::HEARTBEAT, pub);
796 
798  {
799  std::lock_guard<std::mutex> lock(this->mutex);
800 
801  // Re-advertise topics that are advertised inside this process.
802  this->info.PublishersByProc(this->pUuid, nodes);
803  }
804 
805  for (const auto &topic : nodes)
806  {
807  for (const auto &node : topic.second)
808  {
809  this->SendMsg(DestinationType::ALL,
810  msgs::Discovery::ADVERTISE, node);
811  }
812  }
813 
814  {
815  std::lock_guard<std::mutex> lock(this->mutex);
816  if (!this->initialized)
817  {
818  if (this->numHeartbeatsUninitialized == 2u)
819  {
820  // We consider discovery initialized after two heartbeat cycles.
821  this->initialized = true;
822 
823  // Notify anyone waiting for the initialization phase to finish.
824  this->initializedCv.notify_all();
825  }
826  ++this->numHeartbeatsUninitialized;
827  }
828 
829  this->timeNextHeartbeat = std::chrono::steady_clock::now() +
830  std::chrono::milliseconds(this->heartbeatInterval);
831  }
832  }
833 
843  private: int NextTimeout() const
844  {
845  auto now = std::chrono::steady_clock::now();
846  auto timeUntilNextHeartbeat = this->timeNextHeartbeat - now;
847  auto timeUntilNextActivity = this->timeNextActivity - now;
848 
849  int t = static_cast<int>(
850  std::chrono::duration_cast<std::chrono::milliseconds>
851  (std::min(timeUntilNextHeartbeat, timeUntilNextActivity)).count());
852  int t2 = std::min(t, this->kTimeout);
853  return std::max(t2, 0);
854  }
855 
857  private: void RecvMessages()
858  {
859  bool timeToExit = false;
860  bool recvFailing = false;
861  while (!timeToExit)
862  {
863  // Calculate the timeout.
864  int timeout = this->NextTimeout();
865 
866  if (pollSockets(this->sockets, timeout))
867  {
868  // A failed socket stays readable (e.g. one that macOS has
869  // defunct), so wait before polling it again.
870  if (!this->RecvDiscoveryUpdate(recvFailing))
871  {
873  std::chrono::milliseconds(this->kTimeout));
874  }
875 
876  if (this->verbose)
877  this->PrintCurrentState();
878  }
879 
880  this->UpdateHeartbeat();
881  this->UpdateActivity();
882 
883  // Is it time to exit?
884  {
885  std::lock_guard<std::mutex> lock(this->exitMutex);
886  if (this->exit)
887  timeToExit = true;
888  }
889  }
890  }
891 
896  private: bool RecvDiscoveryUpdate(bool &_failing)
897  {
898  char rcvStr[Discovery::kMaxRcvStr];
899  sockaddr_in clntAddr;
900  socklen_t addrLen = sizeof(clntAddr);
901 
902  int64_t received = recvfrom(this->sockets.at(0),
903  reinterpret_cast<raw_type *>(rcvStr),
904  this->kMaxRcvStr, 0,
905  reinterpret_cast<sockaddr *>(&clntAddr),
906  reinterpret_cast<socklen_t *>(&addrLen));
907  if (received > 0)
908  {
909  uint16_t len = 0;
910  memcpy(&len, &rcvStr[0], sizeof(len));
911 
912  // Gazebo Transport delimits each discovery message with a
913  // frame_delimiter that contains byte size information.
914  // A discovery message has the form:
915  //
916  // <frame_delimiter><frame_body>
917  //
918  // Gazebo Transport version < 8 sends a frame delimiter that
919  // contains the value of sizeof(frame_delimiter)
920  // + sizeof(frame_body). In other words, the frame_delimiter
921  // contains a value that represents the total size of the
922  // frame_body and frame_delimiter in bytes.
923  //
924  // Gazebo Transport version >= 8 sends a frame_delimiter
925  // that contains the value of sizeof(frame_body). In other
926  // words, the frame_delimiter contains a value that represents
927  // the total size of only the frame_body.
928  //
929  // It is possible that two incompatible versions of Gazebo
930  // Transport exist on the same network. If we receive an
931  // unexpected size, then we ignore the message.
932 
933  // If-condition for version 8+
934  if (len + sizeof(len) == static_cast<uint16_t>(received))
935  {
936  std::string srcAddr = inet_ntoa(clntAddr.sin_addr);
937  uint16_t srcPort = ntohs(clntAddr.sin_port);
938 
939  if (this->verbose)
940  {
941  std::cout << "\nReceived discovery update from "
942  << srcAddr << ": " << srcPort << std::endl;
943  }
944 
945  this->DispatchDiscoveryMsg(srcAddr, rcvStr + sizeof(len), len);
946  }
947  }
948  else
949  {
950  // An empty read carries no discovery frame. A socket that the OS
951  // has shut down keeps returning errors or empty reads.
952  if (!_failing)
953  {
954  std::cerr << "Discovery::RecvDiscoveryUpdate() failed ("
955  << (received < 0 ? strerror(errno) : "empty read")
956  << "). If the OS shut down this process's sockets "
957  << "(macOS does this under network memory pressure), "
958  << "discovery won't recover until the process restarts."
959  << std::endl;
960  }
961  _failing = true;
962  return false;
963  }
964  _failing = false;
965  return true;
966  }
967 
972  private: void DispatchDiscoveryMsg(const std::string &_fromIp,
973  char *_msg, uint16_t _len)
974  {
975  gz::msgs::Discovery msg;
976 
977  // Parse the message, and return if parsing failed. Parsing could
978  // fail when another discovery node is publishing messages using an
979  // older (or newer) format.
980  if (!msg.ParseFromArray(_msg, _len))
981  return;
982 
983  // Discard the message if the wire protocol is different than mine.
984  if (this->Version() != msg.version())
985  return;
986 
987  std::string recvPUuid = msg.process_uuid();
988 
989  // Discard our own discovery messages.
990  if (recvPUuid == this->pUuid)
991  return;
992 
993  // Forwarding summary:
994  // - From a unicast peer -> to multicast group (with NO_RELAY flag).
995  // - From multicast group -> to unicast peers (with RELAY flag).
996 
997  // If the RELAY flag is set, this discovery message is coming via a
998  // unicast transmission. In this case, we don't process it, we just
999  // forward it to the multicast group, and it will be dispatched once
1000  // received there. Note that we also unset the RELAY flag and set the
1001  // NO_RELAY flag, to avoid forwarding the message anymore.
1002  if (msg.has_flags() && msg.flags().relay())
1003  {
1004  // Unset the RELAY flag in the header and set the NO_RELAY.
1005  msg.mutable_flags()->set_relay(false);
1006  msg.mutable_flags()->set_no_relay(true);
1007  this->SendMulticast(msg);
1008 
1009  // A unicast peer contacted me. I need to save its address for
1010  // sending future messages in the future.
1011  this->AddRelayAddress(_fromIp);
1012  return;
1013  }
1014  // If we are receiving this discovery message via the multicast channel
1015  // and the NO_RELAY flag is not set, we forward this message via unicast
1016  // to all our relays. Note that this is the most common case, where we
1017  // receive a regular multicast message and we forward it to any remote
1018  // relays.
1019  else if (!msg.has_flags() || !msg.flags().no_relay())
1020  {
1021  msg.mutable_flags()->set_relay(true);
1022  this->SendUnicast(msg);
1023  }
1024 
1025  bool isSenderLocal = (std::find(this->hostInterfaces.begin(),
1026  this->hostInterfaces.end(), _fromIp) != this->hostInterfaces.end()) ||
1027  (_fromIp.find("127.") == 0);
1028 
1029  // Update timestamp and cache the callbacks.
1030  DiscoveryCallback<Pub> connectCb;
1031  DiscoveryCallback<Pub> disconnectCb;
1032  DiscoveryCallback<Pub> registerCb;
1033  DiscoveryCallback<Pub> unregisterCb;
1034  std::function<void()> subscribersReqCb;
1035  {
1036  std::lock_guard<std::mutex> lock(this->mutex);
1037  this->activity[recvPUuid] = std::chrono::steady_clock::now();
1038  connectCb = this->connectionCb;
1039  disconnectCb = this->disconnectionCb;
1040  registerCb = this->registrationCb;
1041  unregisterCb = this->unregistrationCb;
1042  subscribersReqCb = this->subscribersCb;
1043  }
1044 
1045  switch (msg.type())
1046  {
1047  case msgs::Discovery::ADVERTISE:
1048  {
1049  // Read the rest of the fields.
1050  Pub publisher;
1051  publisher.SetFromDiscovery(msg);
1052 
1053  // Check scope of the topic.
1054  if ((publisher.Options().Scope() == Scope_t::PROCESS) ||
1055  (publisher.Options().Scope() == Scope_t::HOST &&
1056  !isSenderLocal))
1057  {
1058  return;
1059  }
1060 
1061  // Register an advertised address for the topic.
1062  bool added;
1063  {
1064  std::lock_guard<std::mutex> lock(this->mutex);
1065  added = this->info.AddPublisher(publisher);
1066  }
1067 
1068  if (added && connectCb)
1069  {
1070  // Execute the client's callback.
1071  connectCb(publisher);
1072  }
1073 
1074  break;
1075  }
1076  case msgs::Discovery::SUBSCRIBE:
1077  {
1078  std::string recvTopic;
1079  // Read the topic information.
1080  if (msg.has_sub())
1081  {
1082  recvTopic = msg.sub().topic();
1083  }
1084  else
1085  {
1086  std::cerr << "Subscription discovery message is missing "
1087  << "Subscriber information.\n";
1088  break;
1089  }
1090 
1091  // Check if at least one of my nodes advertises the topic requested.
1092  Addresses_M<Pub> addresses;
1093  {
1094  std::lock_guard<std::mutex> lock(this->mutex);
1095  if (!this->info.HasAnyPublishers(recvTopic, this->pUuid))
1096  {
1097  break;
1098  }
1099 
1100  if (!this->info.Publishers(recvTopic, addresses))
1101  break;
1102  }
1103 
1104  for (const auto &nodeInfo : addresses[this->pUuid])
1105  {
1106  // Check scope of the topic.
1107  if ((nodeInfo.Options().Scope() == Scope_t::PROCESS) ||
1108  (nodeInfo.Options().Scope() == Scope_t::HOST &&
1109  !isSenderLocal))
1110  {
1111  continue;
1112  }
1113 
1114  // Answer an ADVERTISE message.
1115  this->SendMsg(DestinationType::ALL,
1116  msgs::Discovery::ADVERTISE, nodeInfo);
1117  }
1118 
1119  break;
1120  }
1121  case msgs::Discovery::SUBSCRIBERS_REQ:
1122  {
1123  if (subscribersReqCb)
1124  subscribersReqCb();
1125 
1126  break;
1127  }
1128  case msgs::Discovery::SUBSCRIBERS_REP:
1129  {
1130  // Save the remote subscriber.
1131  Pub publisher;
1132  publisher.SetFromDiscovery(msg);
1133 
1134  {
1135  std::lock_guard<std::mutex> lock(this->mutex);
1136  this->remoteSubscribers.AddPublisher(publisher);
1137  }
1138  break;
1139  }
1140  case msgs::Discovery::NEW_CONNECTION:
1141  {
1142  // Read the rest of the fields.
1143  Pub publisher;
1144  publisher.SetFromDiscovery(msg);
1145 
1146  if (registerCb)
1147  registerCb(publisher);
1148 
1149  break;
1150  }
1151  case msgs::Discovery::END_CONNECTION:
1152  {
1153  // Read the rest of the fields.
1154  Pub publisher;
1155  publisher.SetFromDiscovery(msg);
1156 
1157  {
1158  std::lock_guard<std::mutex> lock(this->mutex);
1159  this->remoteSubscribers.DelPublisherByNode(
1160  publisher.Topic(), publisher.PUuid(), publisher.NUuid());
1161  }
1162 
1163  if (unregisterCb)
1164  unregisterCb(publisher);
1165 
1166  break;
1167  }
1168  case msgs::Discovery::HEARTBEAT:
1169  {
1170  // The timestamp has already been updated.
1171  break;
1172  }
1173  case msgs::Discovery::BYE:
1174  {
1175  // Remove the activity entry for this publisher.
1176  {
1177  std::lock_guard<std::mutex> lock(this->mutex);
1178  this->activity.erase(recvPUuid);
1179  }
1180 
1181  if (disconnectCb)
1182  {
1183  Pub pub;
1184  pub.SetPUuid(recvPUuid);
1185  // Notify the new disconnection.
1186  disconnectCb(pub);
1187  }
1188 
1189  // Remove the address entry for this topic.
1190  {
1191  std::lock_guard<std::mutex> lock(this->mutex);
1192  this->info.DelPublishersByProc(recvPUuid);
1193  this->remoteSubscribers.DelPublishersByProc(recvPUuid);
1194  }
1195 
1196  break;
1197  }
1198  case msgs::Discovery::UNADVERTISE:
1199  {
1200  // Read the address.
1201  Pub publisher;
1202  publisher.SetFromDiscovery(msg);
1203 
1204  // Check scope of the topic.
1205  if ((publisher.Options().Scope() == Scope_t::PROCESS) ||
1206  (publisher.Options().Scope() == Scope_t::HOST &&
1207  !isSenderLocal))
1208  {
1209  return;
1210  }
1211 
1212  if (disconnectCb)
1213  {
1214  // Notify the new disconnection.
1215  disconnectCb(publisher);
1216  }
1217 
1218  // Remove the address entry for this topic.
1219  {
1220  std::lock_guard<std::mutex> lock(this->mutex);
1221  this->info.DelPublisherByNode(publisher.Topic(),
1222  publisher.PUuid(), publisher.NUuid());
1223  }
1224 
1225  break;
1226  }
1227  default:
1228  {
1229  std::cerr << "Unknown message type [" << msg.type() << "].\n";
1230  break;
1231  }
1232  }
1233  }
1234 
1241  private: template<typename T>
1242  void SendMsg(const DestinationType &_destType,
1243  const msgs::Discovery::Type _type,
1244  const T &_pub) const
1245  {
1246  gz::msgs::Discovery discoveryMsg;
1247  discoveryMsg.set_version(this->Version());
1248  discoveryMsg.set_type(_type);
1249  discoveryMsg.set_process_uuid(this->pUuid);
1250  _pub.FillDiscovery(discoveryMsg);
1251 
1252  switch (_type)
1253  {
1254  case msgs::Discovery::ADVERTISE:
1255  case msgs::Discovery::UNADVERTISE:
1256  case msgs::Discovery::NEW_CONNECTION:
1257  case msgs::Discovery::END_CONNECTION:
1258  {
1259  _pub.FillDiscovery(discoveryMsg);
1260  break;
1261  }
1262  case msgs::Discovery::SUBSCRIBE:
1263  {
1264  discoveryMsg.mutable_sub()->set_topic(_pub.Topic());
1265  break;
1266  }
1267  case msgs::Discovery::HEARTBEAT:
1268  case msgs::Discovery::BYE:
1269  case msgs::Discovery::SUBSCRIBERS_REQ:
1270  case msgs::Discovery::SUBSCRIBERS_REP:
1271  break;
1272  default:
1273  std::cerr << "Discovery::SendMsg() error: Unrecognized message"
1274  << " type [" << _type << "]" << std::endl;
1275  return;
1276  }
1277 
1278  if (_destType == DestinationType::MULTICAST ||
1279  _destType == DestinationType::ALL)
1280  {
1281  this->SendMulticast(discoveryMsg);
1282  }
1283 
1284  // Send the discovery message to the unicast relays.
1285  if (_destType == DestinationType::UNICAST ||
1286  _destType == DestinationType::ALL)
1287  {
1288  // Set the RELAY flag in the header.
1289  discoveryMsg.mutable_flags()->set_relay(true);
1290  this->SendUnicast(discoveryMsg);
1291  }
1292 
1293  if (this->verbose)
1294  {
1295  std::cout << "\t* Sending " << msgs::ToString(_type)
1296  << " msg [" << _pub.Topic() << "]" << std::endl;
1297  }
1298  }
1299 
1302  private: void SendUnicast(const msgs::Discovery &_msg) const
1303  {
1304  uint16_t msgSize;
1305 
1306 #if GOOGLE_PROTOBUF_VERSION >= 3004000
1307  size_t msgSizeFull = _msg.ByteSizeLong();
1308 #else
1309  int msgSizeFull = _msg.ByteSize();
1310 #endif
1311  if (msgSizeFull + sizeof(msgSize) > this->kMaxRcvStr)
1312  {
1313  std::cerr << "Discovery message too large to send. Discovery won't "
1314  << "work. This shouldn't happen.\n";
1315  return;
1316  }
1317  msgSize = msgSizeFull;
1318 
1319  uint16_t totalSize = sizeof(msgSize) + msgSize;
1320  char *buffer = static_cast<char *>(new char[totalSize]);
1321  memcpy(&buffer[0], &msgSize, sizeof(msgSize));
1322 
1323  if (_msg.SerializeToArray(buffer + sizeof(msgSize), msgSize))
1324  {
1325  // Send the discovery message to the unicast relays.
1326  std::lock_guard<std::mutex> lock(this->mutex);
1327 
1328  for (const auto &sockAddr : this->relayAddrs)
1329  {
1330  errno = 0;
1331  auto sent = sendto(this->sockets.at(0),
1332  reinterpret_cast<const raw_type *>(
1333  reinterpret_cast<const unsigned char*>(buffer)),
1334  totalSize, 0,
1335  reinterpret_cast<const sockaddr *>(&sockAddr),
1336  sizeof(sockAddr));
1337 
1338  if (sent != totalSize)
1339  {
1340  std::cerr << "Exception sending a unicast message:" << std::endl;
1341  std::cerr << " Return value: " << sent << std::endl;
1342  std::cerr << " Error code: " << strerror(errno) << std::endl;
1343  break;
1344  }
1345  }
1346  }
1347  else
1348  {
1349  std::cerr << "Discovery::SendUnicast: Error serializing data."
1350  << std::endl;
1351  }
1352 
1353  delete [] buffer;
1354  }
1355 
1358  private: void SendMulticast(const msgs::Discovery &_msg) const
1359  {
1360  uint16_t msgSize;
1361 
1362 #if GOOGLE_PROTOBUF_VERSION >= 3004000
1363  size_t msgSizeFull = _msg.ByteSizeLong();
1364 #else
1365  int msgSizeFull = _msg.ByteSize();
1366 #endif
1367  if (msgSizeFull + sizeof(msgSize) > this->kMaxRcvStr)
1368  {
1369  std::cerr << "Discovery message too large to send. Discovery won't "
1370  << "work. This shouldn't happen.\n";
1371  return;
1372  }
1373 
1374  msgSize = msgSizeFull;
1375  uint16_t totalSize = sizeof(msgSize) + msgSize;
1376  char *buffer = static_cast<char *>(new char[totalSize]);
1377  memcpy(&buffer[0], &msgSize, sizeof(msgSize));
1378 
1379  if (_msg.SerializeToArray(buffer + sizeof(msgSize), msgSize))
1380  {
1381  // Send the discovery message to the multicast group through all the
1382  // sockets.
1383  for (const auto &sock : this->Sockets())
1384  {
1385  errno = 0;
1386  if (sendto(sock, reinterpret_cast<const raw_type *>(
1387  reinterpret_cast<const unsigned char*>(buffer)),
1388  totalSize, 0,
1389  reinterpret_cast<const sockaddr *>(this->MulticastAddr()),
1390  sizeof(*(this->MulticastAddr()))) != totalSize)
1391  {
1392  // Ignore EPERM and ENOBUFS errors.
1393  //
1394  // See issue #106
1395  //
1396  // Rationale drawn from:
1397  //
1398  // * https://groups.google.com/forum/#!topic/comp.protocols.tcp-ip/Qou9Sfgr77E
1399  // * https://stackoverflow.com/questions/16555101/sendto-dgrams-do-not-block-for-enobufs-on-osx
1400  if (errno != EPERM && errno != ENOBUFS)
1401  {
1402  std::cerr << "Exception sending a multicast message:"
1403  << strerror(errno) << std::endl;
1404  }
1405  break;
1406  }
1407  }
1408  }
1409  else
1410  {
1411  std::cerr << "Discovery::SendMulticast: Error serializing data."
1412  << std::endl;
1413  }
1414 
1415  delete [] buffer;
1416  }
1417 
1420  private: const std::vector<int> &Sockets() const
1421  {
1422  return this->sockets;
1423  }
1424 
1427  private: const sockaddr_in *MulticastAddr() const
1428  {
1429  return &this->mcastAddr;
1430  }
1431 
1434  private: uint8_t Version() const
1435  {
1436  static std::string gzStats;
1437  static int topicStats;
1438 
1439  if (env("GZ_TRANSPORT_TOPIC_STATISTICS", gzStats) && !gzStats.empty())
1440  {
1441  topicStats = (gzStats == "1");
1442  }
1443 
1444  return this->kWireVersion + (topicStats * 100);
1445  }
1446 
1451  private: bool RegisterNetIface(const std::string &_ip)
1452  {
1453  // Make a new socket for sending discovery information.
1454  int sock = static_cast<int>(socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP));
1455  if (sock < 0)
1456  {
1457  std::cerr << "Socket creation failed." << std::endl;
1458  return false;
1459  }
1460 
1461 #ifdef SO_NOSIGPIPE
1462  // Fail sends with EPIPE instead of raising SIGPIPE when the OS shuts
1463  // this socket down, as macOS does when it runs out of network buffers.
1464  int noSigPipe = 1;
1465  if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe,
1466  sizeof(noSigPipe)) != 0)
1467  {
1468  std::cerr << "Error setting socket option (SO_NOSIGPIPE)."
1469  << std::endl;
1470  }
1471 #endif
1472 
1473  // Socket option: IP_MULTICAST_IF.
1474  // This socket option needs to be applied to each socket used to send
1475  // data. This option selects the source interface for outgoing messages.
1476  struct in_addr ifAddr;
1477  ifAddr.s_addr = inet_addr(_ip.c_str());
1478  if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF,
1479  reinterpret_cast<const char*>(&ifAddr), sizeof(ifAddr)) != 0)
1480  {
1481  std::cerr << "Error setting socket option (IP_MULTICAST_IF)."
1482  << std::endl;
1483  return false;
1484  }
1485 
1486  this->sockets.push_back(sock);
1487 
1488  // Join the multicast group. We have to do it for each network interface
1489  // but we can do it on the same socket. We will use the socket at
1490  // position 0 for receiving multicast information.
1491  struct ip_mreq group;
1492  group.imr_multiaddr.s_addr =
1493  inet_addr(this->multicastGroup.c_str());
1494  group.imr_interface.s_addr = inet_addr(_ip.c_str());
1495  if (setsockopt(this->sockets.at(0), IPPROTO_IP, IP_ADD_MEMBERSHIP,
1496  reinterpret_cast<const char*>(&group), sizeof(group)) != 0)
1497  {
1498  std::cerr << "Error setting socket option (IP_ADD_MEMBERSHIP)."
1499  << std::endl;
1500  return false;
1501  }
1502 
1503  return true;
1504  }
1505 
1509  private: static const unsigned int kDefActivityInterval = 100;
1510 
1514  private: static const unsigned int kDefHeartbeatInterval = 1000;
1515 
1519  private: static const unsigned int kDefSilenceInterval = 3000;
1520 
1522  private: std::string multicastGroup;
1523 
1525  private: const int kTimeout = 250;
1526 
1528  private: static const uint16_t kMaxRcvStr =
1530 
1533  private: static const uint8_t kWireVersion = 10;
1534 
1536  private: int port;
1537 
1539  private: std::string hostAddr;
1540 
1542  private: std::vector<std::string> hostInterfaces;
1543 
1545  private: std::string pUuid;
1546 
1550  private: unsigned int silenceInterval;
1551 
1555  private: unsigned int activityInterval;
1556 
1560  private: unsigned int heartbeatInterval;
1561 
1563  private: DiscoveryCallback<Pub> connectionCb;
1564 
1566  private: DiscoveryCallback<Pub> disconnectionCb;
1567 
1569  private: DiscoveryCallback<Pub> registrationCb;
1570 
1572  private: DiscoveryCallback<Pub> unregistrationCb;
1573 
1575  private: std::function<void()> subscribersCb;
1576 
1578  private: TopicStorage<Pub> info;
1579 
1581  private: TopicStorage<Pub> remoteSubscribers;
1582 
1588 
1590  private: bool verbose;
1591 
1593  private: std::vector<int> sockets;
1594 
1596  private: sockaddr_in mcastAddr;
1597 
1599  private: std::vector<sockaddr_in> relayAddrs;
1600 
1602  private: mutable std::mutex mutex;
1603 
1605  private: std::thread threadReception;
1606 
1608  private: Timestamp timeNextHeartbeat;
1609 
1611  private: Timestamp timeNextActivity;
1612 
1614  private: std::mutex exitMutex;
1615 
1620  private: bool initialized;
1621 
1623  private: unsigned int numHeartbeatsUninitialized;
1624 
1626  private: mutable std::condition_variable initializedCv;
1627 
1629  private: bool exit;
1630 
1632  private: bool enabled;
1633  };
1634 
1638 
1642  }
1643  }
1644 }
1645 
1646 #endif