130 const bool _verbose =
false)
131 : multicastGroup(_ip),
135 silenceInterval(kDefSilenceInterval),
136 activityInterval(kDefActivityInterval),
137 heartbeatInterval(kDefHeartbeatInterval),
138 connectionCb(nullptr),
139 disconnectionCb(nullptr),
142 numHeartbeatsUninitialized(0),
147 if (
env(
"GZ_IP", gzIp) && !gzIp.
empty())
149 this->hostInterfaces = {gzIp};
158 WORD wVersionRequested;
162 wVersionRequested = MAKEWORD(2, 2);
164 if (WSAStartup(wVersionRequested, &wsaData) != 0)
170 for (
const auto &netIface : this->hostInterfaces)
172 auto succeed = this->RegisterNetIface(netIface);
177 if (netIface == this->hostAddr && !succeed)
179 this->RegisterNetIface(
"127.0.0.1");
180 std::cerr <<
"Did you set the environment variable GZ_IP with a "
182 <<
" [" << netIface <<
"] seems an invalid local IP "
184 <<
" Using 127.0.0.1 as hostname." <<
std::endl;
185 this->hostAddr =
"127.0.0.1";
194 if (setsockopt(this->sockets.at(0), SOL_SOCKET, SO_REUSEADDR,
195 reinterpret_cast<const char *
>(&reuseAddr),
sizeof(reuseAddr)) != 0)
197 std::cerr <<
"Error setting socket option (SO_REUSEADDR)."
209 if (setsockopt(this->sockets.at(0), SOL_SOCKET, SO_REUSEPORT,
210 reinterpret_cast<const char *
>(&reusePort),
sizeof(reusePort)) != 0)
212 std::cerr <<
"Error setting socket option (SO_REUSEPORT)."
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));
224 if (bind(this->sockets.at(0),
225 reinterpret_cast<sockaddr *
>(&localAddr),
sizeof(sockaddr_in)) < 0)
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));
240 if (
env(
"GZ_RELAY", gzRelay) && !gzRelay.
empty())
242 relays = transport::split(gzRelay,
':');
246 for (
auto const &relayAddr : relays)
247 this->AddRelayAddress(relayAddr);
250 this->PrintCurrentState();
257 this->exitMutex.lock();
259 this->exitMutex.unlock();
262 if (this->threadReception.joinable())
263 this->threadReception.join();
267 this->SendMsg(DestinationType::ALL, msgs::Discovery::BYE,
271 for (
const auto &sock : this->sockets)
294 this->enabled =
true;
298 this->timeNextHeartbeat = now;
299 this->timeNextActivity = now;
302 this->threadReception =
std::thread(&Discovery::RecvMessages,
this);
320 if (!this->info.AddPublisher(_publisher))
323 cb = this->connectionCb;
331 if (_publisher.Options().Scope() != Scope_t::PROCESS)
332 this->SendMsg(DestinationType::ALL, msgs::Discovery::ADVERTISE,
360 cb = this->connectionCb;
364 pub.SetTopic(_topic);
365 pub.SetPUuid(this->pUuid);
368 this->SendMsg(DestinationType::ALL, msgs::Discovery::SUBSCRIBE, pub);
372 found = this->info.Publishers(_topic, addresses);
378 for (
const auto &proc : addresses)
380 for (
const auto &node : proc.second)
401 DestinationType::ALL, msgs::Discovery::SUBSCRIBERS_REP, _pub);
409 DestinationType::ALL, msgs::Discovery::NEW_CONNECTION, _pub);
417 DestinationType::ALL, msgs::Discovery::END_CONNECTION, _pub);
436 return this->info.Publishers(_topic, _publishers);
447 return this->remoteSubscribers.Publishers(_topic, _subscribers);
468 if (!this->info.Publisher(_topic, this->pUuid, _nUuid, inf))
472 this->info.DelPublisherByNode(_topic, this->pUuid, _nUuid);
477 if (inf.Options().Scope() != Scope_t::PROCESS)
479 this->SendMsg(DestinationType::ALL,
480 msgs::Discovery::UNADVERTISE, inf);
491 return this->hostAddr;
501 return this->activityInterval;
512 return this->heartbeatInterval;
522 return this->silenceInterval;
531 this->activityInterval = _ms;
540 this->heartbeatInterval = _ms;
549 this->silenceInterval = _ms;
559 this->connectionCb = _cb;
569 this->disconnectionCb = _cb;
578 this->registrationCb = _cb;
587 this->unregistrationCb = _cb;
596 this->subscribersCb = _cb;
610 std::cout <<
"\tActivity: " << this->activityInterval
612 std::cout <<
"\tHeartbeat: " << this->heartbeatInterval
614 std::cout <<
"\tSilence: " << this->silenceInterval
623 if (this->activity.empty())
627 for (
auto &proc : this->activity)
649 if constexpr (std::is_same_v<Pub, MessagePublisher>)
653 DestinationType::ALL, msgs::Discovery::SUBSCRIBERS_REQ, pub);
658 this->info.TopicList(_topics);
661 this->remoteSubscribers.TopicList(remoteSubs);
664 for (
auto const &t : remoteSubs)
679 if (!this->initialized)
681 this->initializedCv.wait(lk, [
this]{
return this->initialized;});
688 private:
void UpdateActivity()
701 if (now < this->timeNextActivity)
704 disconnectCb = this->disconnectionCb;
706 for (
auto it = this->activity.cbegin(); it != this->activity.cend();)
709 auto elapsed = now - it->second;
712 if (std::chrono::duration_cast<std::chrono::milliseconds>
713 (elapsed).count() > this->silenceInterval)
716 this->info.DelPublishersByProc(it->first);
717 this->remoteSubscribers.DelPublishersByProc(it->first);
722 this->activity.erase(it++);
738 for (
auto const &uuid : uuids)
741 publisher.SetPUuid(uuid);
742 disconnectCb(publisher);
752 for (
auto const &addr : this->relayAddrs)
754 if (addr.sin_addr.s_addr == inet_addr(_ip.
c_str()))
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));
764 this->relayAddrs.push_back(addr);
775 for (
auto const &addr : this->relayAddrs) {
776 result.
push_back(inet_ntoa(addr.sin_addr));
783 private:
void UpdateHeartbeat()
790 if (now < this->timeNextHeartbeat)
794 Publisher pub(
"",
"", this->pUuid,
"", AdvertiseOptions());
795 this->SendMsg(DestinationType::ALL, msgs::Discovery::HEARTBEAT, pub);
802 this->info.PublishersByProc(this->pUuid, nodes);
805 for (
const auto &topic : nodes)
807 for (
const auto &node : topic.second)
809 this->SendMsg(DestinationType::ALL,
810 msgs::Discovery::ADVERTISE, node);
816 if (!this->initialized)
818 if (this->numHeartbeatsUninitialized == 2u)
821 this->initialized =
true;
824 this->initializedCv.notify_all();
826 ++this->numHeartbeatsUninitialized;
843 private:
int NextTimeout()
const
846 auto timeUntilNextHeartbeat = this->timeNextHeartbeat - now;
847 auto timeUntilNextActivity = this->timeNextActivity - now;
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);
857 private:
void RecvMessages()
859 bool timeToExit =
false;
860 bool recvFailing =
false;
864 int timeout = this->NextTimeout();
870 if (!this->RecvDiscoveryUpdate(recvFailing))
877 this->PrintCurrentState();
880 this->UpdateHeartbeat();
881 this->UpdateActivity();
896 private:
bool RecvDiscoveryUpdate(
bool &_failing)
898 char rcvStr[Discovery::kMaxRcvStr];
899 sockaddr_in clntAddr;
900 socklen_t addrLen =
sizeof(clntAddr);
902 int64_t received = recvfrom(this->sockets.at(0),
903 reinterpret_cast<raw_type *
>(rcvStr),
905 reinterpret_cast<sockaddr *
>(&clntAddr),
906 reinterpret_cast<socklen_t *
>(&addrLen));
910 memcpy(&len, &rcvStr[0],
sizeof(len));
934 if (len +
sizeof(len) ==
static_cast<uint16_t
>(received))
936 std::string srcAddr = inet_ntoa(clntAddr.sin_addr);
937 uint16_t srcPort = ntohs(clntAddr.sin_port);
941 std::cout <<
"\nReceived discovery update from "
942 << srcAddr <<
": " << srcPort <<
std::endl;
945 this->DispatchDiscoveryMsg(srcAddr, rcvStr +
sizeof(len), len);
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."
972 private:
void DispatchDiscoveryMsg(
const std::string &_fromIp,
973 char *_msg, uint16_t _len)
975 gz::msgs::Discovery msg;
980 if (!msg.ParseFromArray(_msg, _len))
984 if (this->Version() != msg.version())
990 if (recvPUuid == this->pUuid)
1002 if (msg.has_flags() && msg.flags().relay())
1005 msg.mutable_flags()->set_relay(
false);
1006 msg.mutable_flags()->set_no_relay(
true);
1007 this->SendMulticast(msg);
1011 this->AddRelayAddress(_fromIp);
1019 else if (!msg.has_flags() || !msg.flags().no_relay())
1021 msg.mutable_flags()->set_relay(
true);
1022 this->SendUnicast(msg);
1025 bool isSenderLocal = (
std::find(this->hostInterfaces.begin(),
1026 this->hostInterfaces.end(), _fromIp) != this->hostInterfaces.end()) ||
1027 (_fromIp.
find(
"127.") == 0);
1030 DiscoveryCallback<Pub> connectCb;
1031 DiscoveryCallback<Pub> disconnectCb;
1032 DiscoveryCallback<Pub> registerCb;
1033 DiscoveryCallback<Pub> unregisterCb;
1038 connectCb = this->connectionCb;
1039 disconnectCb = this->disconnectionCb;
1040 registerCb = this->registrationCb;
1041 unregisterCb = this->unregistrationCb;
1042 subscribersReqCb = this->subscribersCb;
1047 case msgs::Discovery::ADVERTISE:
1051 publisher.SetFromDiscovery(msg);
1054 if ((publisher.Options().Scope() == Scope_t::PROCESS) ||
1055 (publisher.Options().Scope() == Scope_t::HOST &&
1065 added = this->info.AddPublisher(publisher);
1068 if (added && connectCb)
1071 connectCb(publisher);
1076 case msgs::Discovery::SUBSCRIBE:
1082 recvTopic = msg.sub().topic();
1086 std::cerr <<
"Subscription discovery message is missing "
1087 <<
"Subscriber information.\n";
1092 Addresses_M<Pub> addresses;
1095 if (!this->info.HasAnyPublishers(recvTopic, this->pUuid))
1100 if (!this->info.Publishers(recvTopic, addresses))
1104 for (
const auto &nodeInfo : addresses[this->pUuid])
1107 if ((nodeInfo.Options().Scope() == Scope_t::PROCESS) ||
1108 (nodeInfo.Options().Scope() == Scope_t::HOST &&
1115 this->SendMsg(DestinationType::ALL,
1116 msgs::Discovery::ADVERTISE, nodeInfo);
1121 case msgs::Discovery::SUBSCRIBERS_REQ:
1123 if (subscribersReqCb)
1128 case msgs::Discovery::SUBSCRIBERS_REP:
1132 publisher.SetFromDiscovery(msg);
1136 this->remoteSubscribers.AddPublisher(publisher);
1140 case msgs::Discovery::NEW_CONNECTION:
1144 publisher.SetFromDiscovery(msg);
1147 registerCb(publisher);
1151 case msgs::Discovery::END_CONNECTION:
1155 publisher.SetFromDiscovery(msg);
1159 this->remoteSubscribers.DelPublisherByNode(
1160 publisher.Topic(), publisher.PUuid(), publisher.NUuid());
1164 unregisterCb(publisher);
1168 case msgs::Discovery::HEARTBEAT:
1173 case msgs::Discovery::BYE:
1178 this->activity.erase(recvPUuid);
1184 pub.SetPUuid(recvPUuid);
1192 this->info.DelPublishersByProc(recvPUuid);
1193 this->remoteSubscribers.DelPublishersByProc(recvPUuid);
1198 case msgs::Discovery::UNADVERTISE:
1202 publisher.SetFromDiscovery(msg);
1205 if ((publisher.Options().Scope() == Scope_t::PROCESS) ||
1206 (publisher.Options().Scope() == Scope_t::HOST &&
1215 disconnectCb(publisher);
1221 this->info.DelPublisherByNode(publisher.Topic(),
1222 publisher.PUuid(), publisher.NUuid());
1229 std::cerr <<
"Unknown message type [" << msg.type() <<
"].\n";
1241 private:
template<
typename T>
1242 void SendMsg(
const DestinationType &_destType,
1243 const msgs::Discovery::Type _type,
1244 const T &_pub)
const
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);
1254 case msgs::Discovery::ADVERTISE:
1255 case msgs::Discovery::UNADVERTISE:
1256 case msgs::Discovery::NEW_CONNECTION:
1257 case msgs::Discovery::END_CONNECTION:
1259 _pub.FillDiscovery(discoveryMsg);
1262 case msgs::Discovery::SUBSCRIBE:
1264 discoveryMsg.mutable_sub()->set_topic(_pub.Topic());
1267 case msgs::Discovery::HEARTBEAT:
1268 case msgs::Discovery::BYE:
1269 case msgs::Discovery::SUBSCRIBERS_REQ:
1270 case msgs::Discovery::SUBSCRIBERS_REP:
1273 std::cerr <<
"Discovery::SendMsg() error: Unrecognized message"
1274 <<
" type [" << _type <<
"]" <<
std::endl;
1278 if (_destType == DestinationType::MULTICAST ||
1279 _destType == DestinationType::ALL)
1281 this->SendMulticast(discoveryMsg);
1285 if (_destType == DestinationType::UNICAST ||
1286 _destType == DestinationType::ALL)
1289 discoveryMsg.mutable_flags()->set_relay(
true);
1290 this->SendUnicast(discoveryMsg);
1295 std::cout <<
"\t* Sending " << msgs::ToString(_type)
1296 <<
" msg [" << _pub.Topic() <<
"]" <<
std::endl;
1302 private:
void SendUnicast(
const msgs::Discovery &_msg)
const
1306#if GOOGLE_PROTOBUF_VERSION >= 3004000
1307 size_t msgSizeFull = _msg.ByteSizeLong();
1309 int msgSizeFull = _msg.ByteSize();
1311 if (msgSizeFull +
sizeof(msgSize) > this->kMaxRcvStr)
1313 std::cerr <<
"Discovery message too large to send. Discovery won't "
1314 <<
"work. This shouldn't happen.\n";
1317 msgSize = msgSizeFull;
1319 uint16_t totalSize =
sizeof(msgSize) + msgSize;
1320 char *buffer =
static_cast<char *
>(
new char[totalSize]);
1321 memcpy(&buffer[0], &msgSize,
sizeof(msgSize));
1323 if (_msg.SerializeToArray(buffer +
sizeof(msgSize), msgSize))
1328 for (
const auto &sockAddr : this->relayAddrs)
1331 auto sent = sendto(this->sockets.at(0),
1332 reinterpret_cast<const raw_type *
>(
1333 reinterpret_cast<const unsigned char*
>(buffer)),
1335 reinterpret_cast<const sockaddr *
>(&sockAddr),
1338 if (sent != totalSize)
1349 std::cerr <<
"Discovery::SendUnicast: Error serializing data."
1358 private:
void SendMulticast(
const msgs::Discovery &_msg)
const
1362#if GOOGLE_PROTOBUF_VERSION >= 3004000
1363 size_t msgSizeFull = _msg.ByteSizeLong();
1365 int msgSizeFull = _msg.ByteSize();
1367 if (msgSizeFull +
sizeof(msgSize) > this->kMaxRcvStr)
1369 std::cerr <<
"Discovery message too large to send. Discovery won't "
1370 <<
"work. This shouldn't happen.\n";
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));
1379 if (_msg.SerializeToArray(buffer +
sizeof(msgSize), msgSize))
1383 for (
const auto &sock : this->Sockets())
1386 if (sendto(sock,
reinterpret_cast<const raw_type *
>(
1387 reinterpret_cast<const unsigned char*
>(buffer)),
1389 reinterpret_cast<const sockaddr *
>(this->MulticastAddr()),
1390 sizeof(*(this->MulticastAddr()))) != totalSize)
1400 if (errno != EPERM && errno != ENOBUFS)
1402 std::cerr <<
"Exception sending a multicast message:"
1411 std::cerr <<
"Discovery::SendMulticast: Error serializing data."
1422 return this->sockets;
1427 private:
const sockaddr_in *MulticastAddr()
const
1429 return &this->mcastAddr;
1434 private: uint8_t Version()
const
1437 static int topicStats;
1439 if (
env(
"GZ_TRANSPORT_TOPIC_STATISTICS", gzStats) && !gzStats.
empty())
1441 topicStats = (gzStats ==
"1");
1444 return this->kWireVersion + (topicStats * 100);
1451 private:
bool RegisterNetIface(
const std::string &_ip)
1454 int sock =
static_cast<int>(socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP));
1465 if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe,
1466 sizeof(noSigPipe)) != 0)
1468 std::cerr <<
"Error setting socket option (SO_NOSIGPIPE)."
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)
1481 std::cerr <<
"Error setting socket option (IP_MULTICAST_IF)."
1486 this->sockets.push_back(sock);
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)
1498 std::cerr <<
"Error setting socket option (IP_ADD_MEMBERSHIP)."
1509 private:
static const unsigned int kDefActivityInterval = 100;
1514 private:
static const unsigned int kDefHeartbeatInterval = 1000;
1519 private:
static const unsigned int kDefSilenceInterval = 3000;
1525 private:
const int kTimeout = 250;
1528 private:
static const uint16_t kMaxRcvStr =
1533 private:
static const uint8_t kWireVersion = 10;
1550 private:
unsigned int silenceInterval;
1555 private:
unsigned int activityInterval;
1560 private:
unsigned int heartbeatInterval;
1563 private: DiscoveryCallback<Pub> connectionCb;
1566 private: DiscoveryCallback<Pub> disconnectionCb;
1569 private: DiscoveryCallback<Pub> registrationCb;
1572 private: DiscoveryCallback<Pub> unregistrationCb;
1578 private: TopicStorage<Pub> info;
1581 private: TopicStorage<Pub> remoteSubscribers;
1590 private:
bool verbose;
1596 private: sockaddr_in mcastAddr;
1620 private:
bool initialized;
1623 private:
unsigned int numHeartbeatsUninitialized;
1632 private:
bool enabled;