-
Notifications
You must be signed in to change notification settings - Fork 43
/
Node.cc
980 lines (815 loc) · 28.8 KB
/
Node.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
/*
* Copyright (C) 2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <algorithm>
#include <cassert>
#include <csignal>
#include <condition_variable>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_set>
#include <vector>
#include "ignition/transport/Helpers.hh"
#include "ignition/transport/MessageInfo.hh"
#include "ignition/transport/Node.hh"
#include "ignition/transport/NodeOptions.hh"
#include "ignition/transport/NodeShared.hh"
#include "ignition/transport/TopicUtils.hh"
#include "ignition/transport/TransportTypes.hh"
#include "ignition/transport/Uuid.hh"
#include "NodePrivate.hh"
#include "NodeSharedPrivate.hh"
#ifdef _MSC_VER
#pragma warning(disable: 4503)
#endif
using namespace ignition;
using namespace transport;
namespace ignition
{
namespace transport
{
inline namespace IGNITION_TRANSPORT_VERSION_NAMESPACE
{
/// \brief Flag to detect SIGINT or SIGTERM while the code is executing
/// waitForShutdown().
static bool g_shutdown = false;
/// \brief Mutex to protect the boolean shutdown variable.
static std::mutex g_shutdown_mutex;
/// \brief Condition variable to wakeup waitForShutdown() and exit.
static std::condition_variable g_shutdown_cv;
//////////////////////////////////////////////////
/// \brief Function executed when a SIGINT or SIGTERM signals are captured.
/// \param[in] _signal Signal received.
static void signal_handler(const int _signal)
{
if (_signal == SIGINT || _signal == SIGTERM)
{
g_shutdown_mutex.lock();
g_shutdown = true;
g_shutdown_mutex.unlock();
g_shutdown_cv.notify_all();
}
}
//////////////////////////////////////////////////
int rcvHwm()
{
return NodeShared::Instance()->RcvHwm();
}
//////////////////////////////////////////////////
int sndHwm()
{
return NodeShared::Instance()->SndHwm();
}
//////////////////////////////////////////////////
void waitForShutdown()
{
// Install a signal handler for SIGINT and SIGTERM.
std::signal(SIGINT, signal_handler);
std::signal(SIGTERM, signal_handler);
std::unique_lock<std::mutex> lk(g_shutdown_mutex);
g_shutdown_cv.wait(lk, []{return g_shutdown;});
}
//////////////////////////////////////////////////
/// \internal
/// \brief Private data for Node::Publisher class.
class Node::PublisherPrivate
{
/// \brief Default constructor.
public: PublisherPrivate()
: shared(NodeShared::Instance())
{
}
/// \brief Constructor
/// \param[in] _publisher The message publisher.
public: explicit PublisherPrivate(const MessagePublisher &_publisher)
: shared(NodeShared::Instance()),
publisher(_publisher)
{
}
/// \brief Check if this Publisher is ready to send an update based on
/// publication settings and the clock.
///
/// \return True if it is okay to publish, false otherwise.
public: bool ThrottledUpdateReady() const
{
if (!this->publisher.Options().Throttled())
return true;
Timestamp now = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lk(this->mutex);
auto elapsed = now - this->lastCbTimestamp;
return std::chrono::duration_cast<std::chrono::nanoseconds>(
elapsed).count() >= this->periodNs;
}
/// \brief Check if this Publisher is ready to send an update based on
/// publication settings and the clock.
///
/// This additionally advances the internal timestamp by one period.
///
/// \return True if it is okay to publish, false otherwise.
public: bool UpdateThrottling()
{
if (!this->publisher.Options().Throttled())
return true;
if (!this->ThrottledUpdateReady())
return false;
// Update the last callback execution.
std::lock_guard<std::mutex> lk(this->mutex);
this->lastCbTimestamp = std::chrono::steady_clock::now();
return true;
}
/// \brief Check if this Publisher is valid
/// \return True if we have a topic to publish to, otherwise false.
public: bool Valid()
{
return !this->publisher.Topic().empty();
}
/// \brief Destructor.
public: virtual ~PublisherPrivate()
{
std::lock_guard<std::recursive_mutex> lk(this->shared->mutex);
// Notify the discovery service to unregister and unadvertise my topic.
if (!this->shared->dataPtr->msgDiscovery->Unadvertise(
this->publisher.Topic(), this->publisher.NUuid()))
{
std::cerr << "~PublisherPrivate() Error unadvertising topic ["
<< this->publisher.Topic() << "]" << std::endl;
}
}
/// \brief Create a MessageInfo object for this Publisher
MessageInfo CreateMessageInfo()
{
MessageInfo info;
// Set the topic and the partition at the same time
info.SetTopicAndPartition(this->publisher.Topic());
// Set the message type name
info.SetType(this->publisher.MsgTypeName());
return info;
}
/// \brief Pointer to the object shared between all the nodes within the
/// same process.
public: NodeShared *shared = nullptr;
/// \brief The message publisher.
public: MessagePublisher publisher;
/// \brief Timestamp of the last callback executed.
public: Timestamp lastCbTimestamp;
/// \brief If throttling is enabled, the minimum period for receiving a
/// message in nanoseconds.
public: double periodNs = 0.0;
/// \brief Mutex to protect the node::publisher from race conditions.
public: mutable std::mutex mutex;
};
}
}
}
//////////////////////////////////////////////////
Node::Publisher::Publisher()
: dataPtr(std::make_shared<PublisherPrivate>())
{
}
//////////////////////////////////////////////////
Node::Publisher::Publisher(const MessagePublisher &_publisher)
: dataPtr(std::make_shared<PublisherPrivate>(_publisher))
{
if (this->dataPtr->publisher.Options().Throttled())
{
this->dataPtr->periodNs =
1e9 / this->dataPtr->publisher.Options().MsgsPerSec();
}
}
//////////////////////////////////////////////////
Node::Publisher::~Publisher()
{
}
//////////////////////////////////////////////////
Node::Publisher::operator bool()
{
return this->Valid();
}
//////////////////////////////////////////////////
Node::Publisher::operator bool() const
{
return this->Valid();
}
//////////////////////////////////////////////////
bool Node::Publisher::Valid() const
{
return this->dataPtr->Valid();
}
//////////////////////////////////////////////////
bool Node::Publisher::HasConnections() const
{
auto &publisher = this->dataPtr->publisher;
const std::string &topic = publisher.Topic();
const std::string &msgType = publisher.MsgTypeName();
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
/// \todo(anyone): Checking "remoteSubscribers.HasTopic()" will return
/// true even
/// if the subscriber has not successfully authenticated with the
/// publisher.
/// See Issue #73
return this->Valid() &&
(this->dataPtr->shared->localSubscribers.HasSubscriber(topic, msgType) ||
this->dataPtr->shared->remoteSubscribers.HasTopic(topic, msgType));
}
//////////////////////////////////////////////////
bool Node::Publisher::Publish(const ProtoMsg &_msg)
{
if (!this->Valid())
return false;
const std::string &publisherMsgType = this->dataPtr->publisher.MsgTypeName();
// Check that the msg type matches the topic type previously advertised.
if (publisherMsgType != _msg.GetTypeName())
{
std::cerr << "Node::Publisher::Publish() Type mismatch.\n"
<< "\t* Type advertised: "
<< this->dataPtr->publisher.MsgTypeName()
<< "\n\t* Type published: " << _msg.GetTypeName() << std::endl;
return false;
}
// Check the publication throttling option.
if (!this->UpdateThrottling())
return true;
const std::string &publisherTopic = this->dataPtr->publisher.Topic();
const NodeShared::SubscriberInfo &subscribers =
this->dataPtr->shared->CheckSubscriberInfo(
publisherTopic, publisherMsgType);
// The serialized message size and buffer.
#if GOOGLE_PROTOBUF_VERSION >= 3004000
const std::size_t msgSize = static_cast<std::size_t>(_msg.ByteSizeLong());
#else
const std::size_t msgSize = static_cast<std::size_t>(_msg.ByteSize());
#endif
char *msgBuffer = nullptr;
// Only serialize the message if we have a raw subscriber or a remote
// subscriber.
if (subscribers.haveRaw || subscribers.haveRemote)
{
// Allocate the buffer to store the serialized data.
msgBuffer = static_cast<char *>(new char[msgSize]);
// Fail out early if we are unable to serialize the message. We do not
// want to send a corrupt/bad message to some subscribers and not others.
if (!_msg.SerializeToArray(msgBuffer, msgSize))
{
delete[] msgBuffer;
std::cerr << "Node::Publisher::Publish(): Error serializing data"
<< std::endl;
return false;
}
}
// Local and raw subscribers.
if (subscribers.haveLocal || subscribers.haveRaw)
{
std::unique_ptr<NodeSharedPrivate::PublishMsgDetails> pubMsgDetails(
new NodeSharedPrivate::PublishMsgDetails);
// Create and populate the message information object.
// This must be a shared pointer so that we can pass it to
// multiple threads below, and then allow this function to go
// out of scope.
pubMsgDetails->info.SetTopicAndPartition(this->dataPtr->publisher.Topic());
pubMsgDetails->info.SetType(this->dataPtr->publisher.MsgTypeName());
pubMsgDetails->info.SetIntraProcess(true);
pubMsgDetails->msgCopy.reset(_msg.New());
pubMsgDetails->msgCopy->CopyFrom(_msg);
if (subscribers.haveLocal)
{
for (const std::pair<std::string, ISubscriptionHandler_M> &node :
subscribers.localHandlers)
{
for (const std::pair<std::string, ISubscriptionHandlerPtr> &handler :
node.second)
{
if (!handler.second)
{
std::cerr << "Node::Publisher::Publish(): "
<< "NULL local subscription handler" << std::endl;
continue;
}
if (handler.second->TypeName() != kGenericMessageType &&
handler.second->TypeName() != _msg.GetTypeName())
{
continue;
}
pubMsgDetails->localHandlers.push_back(handler.second);
}
}
}
if (subscribers.haveRaw)
{
for (auto &node : subscribers.rawHandlers)
{
for (auto &handler : node.second)
{
const RawSubscriptionHandlerPtr &rawHandler = handler.second;
if (!rawHandler)
{
std::cerr << "Node::Publisher::Publish(): "
<< "NULL raw subscription handler" << std::endl;
continue;
}
if (rawHandler->TypeName() != kGenericMessageType &&
rawHandler->TypeName() != _msg.GetTypeName())
{
continue;
}
if (!pubMsgDetails->sharedBuffer)
{
pubMsgDetails->msgSize = msgSize;
// If the sharedBuffer has not been created, do so now.
pubMsgDetails->sharedBuffer.reset(new char[msgSize]);
memcpy(pubMsgDetails->sharedBuffer.get(), msgBuffer, msgSize);
}
pubMsgDetails->rawHandlers.push_back(rawHandler);
}
}
}
// Add the publish message details to the publish queue. The message
// will be published asynchronously to the local and raw callbacks.
{
std::unique_lock<std::mutex> queueLock(
this->dataPtr->shared->dataPtr->pubThreadMutex);
this->dataPtr->shared->dataPtr->pubQueue.push(std::move(pubMsgDetails));
}
this->dataPtr->shared->dataPtr->signalNewPub.notify_one();
}
// Handle remote subscribers.
if (subscribers.haveRemote)
{
// Zmq will call this lambda when the message is published.
// We use it to deallocate the buffer.
auto myDeallocator = [](void *_buffer, void *)
{
delete[] reinterpret_cast<char*>(_buffer);
};
if (!this->dataPtr->shared->Publish(this->dataPtr->publisher.Topic(),
msgBuffer, msgSize, myDeallocator, _msg.GetTypeName()))
{
return false;
}
}
else
{
delete[] msgBuffer;
}
return true;
}
//////////////////////////////////////////////////
bool Node::Publisher::PublishRaw(
const std::string &_msgData,
const std::string &_msgType)
{
if (!this->dataPtr->Valid())
return false;
const std::string &publisherMsgType = this->dataPtr->publisher.MsgTypeName();
if (publisherMsgType != _msgType && publisherMsgType != kGenericMessageType)
{
std::cerr << "Node::Publisher::PublishRaw() type mismatch.\n"
<< "\t* Type advertised: "
<< this->dataPtr->publisher.MsgTypeName()
<< "\n\t* Type published: " << _msgType << std::endl;
return false;
}
if (!this->dataPtr->UpdateThrottling())
return true;
const std::string &topic = this->dataPtr->publisher.Topic();
const NodeShared::SubscriberInfo &subscribers =
this->dataPtr->shared->CheckSubscriberInfo(topic, _msgType);
MessageInfo info;
info.SetTopicAndPartition(topic);
info.SetType(_msgType);
info.SetIntraProcess(true);
// Trigger local subscribers.
this->dataPtr->shared->TriggerCallbacks(info, _msgData, subscribers);
// Remote subscribers. Note that the data is already presumed to be
// serialized, so we just pass it along for publication.
if (subscribers.haveRemote)
{
const std::size_t msgSize = _msgData.size();
char *msgBuffer = static_cast<char *>(new char[msgSize]);
memcpy(msgBuffer, _msgData.c_str(), msgSize);
auto myDeallocator = [](void *_buffer, void * /*_hint*/)
{
delete[] reinterpret_cast<char*>(_buffer);
};
// Note: This will copy _msgData (i.e. not zero copy)
if (!this->dataPtr->shared->Publish(
this->dataPtr->publisher.Topic(),
msgBuffer, msgSize, myDeallocator, _msgType))
{
return false;
}
}
return true;
}
//////////////////////////////////////////////////
bool Node::Publisher::ThrottledUpdateReady() const
{
return this->dataPtr->ThrottledUpdateReady();
}
//////////////////////////////////////////////////
bool Node::Publisher::UpdateThrottling()
{
return this->dataPtr->UpdateThrottling();
}
//////////////////////////////////////////////////
Node::Node(const NodeOptions &_options)
: dataPtr(new NodePrivate())
{
// Generate the node UUID.
Uuid uuid;
this->dataPtr->nUuid = uuid.ToString();
// Save the options.
this->dataPtr->options = _options;
}
//////////////////////////////////////////////////
Node::~Node()
{
// Unsubscribe from all the topics.
auto subsTopics = this->SubscribedTopics();
for (auto const &topic : subsTopics)
this->Unsubscribe(topic);
// The list of subscribed topics should be empty.
assert(this->SubscribedTopics().empty());
// Unadvertise all my services.
auto advServices = this->AdvertisedServices();
for (auto const &service : advServices)
{
if (!this->UnadvertiseSrv(service))
{
std::cerr << "Node::~Node(): Error unadvertising service ["
<< service << "]" << std::endl;
}
}
// The list of advertised services should be empty.
assert(this->AdvertisedServices().empty());
}
//////////////////////////////////////////////////
std::vector<std::string> Node::AdvertisedTopics() const
{
std::vector<std::string> v;
std::unordered_set<std::string> result;
std::vector<MessagePublisher> pubs;
{
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
auto pUUID = this->dataPtr->shared->pUuid;
auto &info = this->dataPtr->shared->dataPtr->msgDiscovery->Info();
info.PublishersByNode(pUUID, this->NodeUuid(), pubs);
}
// Copy the topics to a std::set for removing duplications.
for (auto const &pub : pubs)
result.insert(pub.Topic());
// Remove the partition information and convert to std::vector.
for (auto topic : result)
{
topic.erase(0, topic.find_last_of("@") + 1);
v.push_back(topic);
}
return v;
}
//////////////////////////////////////////////////
std::vector<std::string> Node::SubscribedTopics() const
{
std::vector<std::string> v;
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
// I'm a real subscriber if I have interest in a topic and I know a publisher.
for (auto topic : this->dataPtr->topicsSubscribed)
{
// Remove the partition information from the topic.
topic.erase(0, topic.find_last_of("@") + 1);
v.push_back(topic);
}
return v;
}
//////////////////////////////////////////////////
bool Node::Unsubscribe(const std::string &_topic)
{
// Topic remapping.
std::string topic = _topic;
this->Options().TopicRemap(_topic, topic);
std::string fullyQualifiedTopic;
if (!TopicUtils::FullyQualifiedName(this->Options().Partition(),
this->Options().NameSpace(), _topic, fullyQualifiedTopic))
{
std::cerr << "Topic [" << _topic << "] is not valid." << std::endl;
return false;
}
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
// Remove the subscribers for the given topic that belong to this node.
this->dataPtr->shared->localSubscribers.RemoveHandlersForNode(
fullyQualifiedTopic, this->dataPtr->nUuid);
// Remove the topic from the list of subscribed topics in this node.
this->dataPtr->topicsSubscribed.erase(fullyQualifiedTopic);
// Remove the filter for this topic if I am the last subscriber.
if (!this->dataPtr->shared->localSubscribers
.HasSubscriber(fullyQualifiedTopic))
{
#if (CPPZMQ_VERSION >= 40700)
this->dataPtr->shared->dataPtr->subscriber->set(
zmq::sockopt::unsubscribe, fullyQualifiedTopic);
#else
this->dataPtr->shared->dataPtr->subscriber->setsockopt(
ZMQ_UNSUBSCRIBE, fullyQualifiedTopic.data(), fullyQualifiedTopic.size());
#endif
}
// Notify to the publishers that I am no longer interested in the topic.
MsgAddresses_M addresses;
if (!this->dataPtr->shared->dataPtr->msgDiscovery->Publishers(
fullyQualifiedTopic, addresses))
{
return false;
}
for (auto &proc : addresses)
{
std::string dstPUuid = proc.first;
MessagePublisher pub(fullyQualifiedTopic, this->dataPtr->shared->myAddress,
dstPUuid, this->dataPtr->shared->pUuid, this->dataPtr->nUuid,
kGenericMessageType, AdvertiseMessageOptions());
this->Shared()->dataPtr->msgDiscovery->Unregister(pub);
}
return true;
}
//////////////////////////////////////////////////
std::vector<std::string> Node::AdvertisedServices() const
{
std::vector<std::string> v;
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
for (auto service : this->dataPtr->srvsAdvertised)
{
// Remove the partition information from the service name.
service.erase(0, service.find_last_of("@") + 1);
v.push_back(service);
}
return v;
}
//////////////////////////////////////////////////
bool Node::UnadvertiseSrv(const std::string &_topic)
{
// Topic remapping.
std::string topic = _topic;
this->Options().TopicRemap(_topic, topic);
std::string fullyQualifiedTopic;
if (!TopicUtils::FullyQualifiedName(this->Options().Partition(),
this->Options().NameSpace(), _topic, fullyQualifiedTopic))
{
std::cerr << "Service [" << _topic << "] is not valid." << std::endl;
return false;
}
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
// Remove the topic from the list of advertised topics in this node.
this->dataPtr->srvsAdvertised.erase(fullyQualifiedTopic);
// Remove all the REP handlers for this node.
this->dataPtr->shared->repliers.RemoveHandlersForNode(
fullyQualifiedTopic, this->dataPtr->nUuid);
// Notify the discovery service to unregister and unadvertise my services.
if (!this->dataPtr->shared->dataPtr->srvDiscovery->Unadvertise(
fullyQualifiedTopic, this->dataPtr->nUuid))
{
return false;
}
return true;
}
//////////////////////////////////////////////////
void Node::TopicList(std::vector<std::string> &_topics) const
{
std::vector<std::string> allTopics;
_topics.clear();
this->dataPtr->shared->dataPtr->msgDiscovery->TopicList(allTopics);
for (const auto &fullyQualifiedTopic : allTopics)
{
std::string partition;
std::string topic;
TopicUtils::DecomposeFullyQualifiedTopic(
fullyQualifiedTopic, partition, topic);
// Remove the front '/'
if (!partition.empty())
partition.erase(partition.begin());
// Discard if the partition name does not match this node's partition.
if (partition != this->Options().Partition())
continue;
_topics.push_back(topic);
}
}
//////////////////////////////////////////////////
void Node::ServiceList(std::vector<std::string> &_services) const
{
std::vector<std::string> allServices;
_services.clear();
this->dataPtr->shared->dataPtr->srvDiscovery->TopicList(allServices);
for (auto &service : allServices)
{
// Get the partition name.
std::string partition = service.substr(1, service.find_last_of("@") - 1);
// Remove the front '/'
if (!partition.empty())
partition.erase(partition.begin());
// Discard if the partition name does not match this node's partition.
if (partition != this->Options().Partition())
continue;
// Remove the partition part from the service.
service.erase(0, service.find_last_of("@") + 1);
_services.push_back(service);
}
}
//////////////////////////////////////////////////
bool Node::SubscribeRaw(
const std::string &_topic,
const RawCallback &_callback,
const std::string &_msgType,
const SubscribeOptions &_opts)
{
// Topic remapping.
std::string topic = _topic;
this->Options().TopicRemap(_topic, topic);
std::string fullyQualifiedTopic;
if (!TopicUtils::FullyQualifiedName(this->dataPtr->options.Partition(),
this->dataPtr->options.NameSpace(),
_topic, fullyQualifiedTopic))
{
std::cerr << "Topic [" << _topic << "] is not valid." << std::endl;
return false;
}
const std::shared_ptr<RawSubscriptionHandler> handlerPtr =
std::make_shared<RawSubscriptionHandler>(
this->dataPtr->nUuid, _msgType, _opts);
handlerPtr->SetCallback(_callback);
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
this->dataPtr->shared->localSubscribers.raw.AddHandler(
fullyQualifiedTopic, this->dataPtr->nUuid, handlerPtr);
return this->dataPtr->SubscribeHelper(fullyQualifiedTopic);
}
//////////////////////////////////////////////////
const NodeOptions &Node::Options() const
{
return this->dataPtr->options;
}
//////////////////////////////////////////////////
NodeShared *Node::Shared() const
{
return this->dataPtr->shared;
}
//////////////////////////////////////////////////
const std::string &Node::NodeUuid() const
{
return this->dataPtr->nUuid;
}
//////////////////////////////////////////////////
std::unordered_set<std::string> &Node::TopicsSubscribed() const
{
return this->dataPtr->topicsSubscribed;
}
//////////////////////////////////////////////////
std::unordered_set<std::string> &Node::SrvsAdvertised() const
{
return this->dataPtr->srvsAdvertised;
}
//////////////////////////////////////////////////
bool Node::TopicInfo(const std::string &_topic,
std::vector<MessagePublisher> &_publishers) const
{
this->dataPtr->shared->dataPtr->msgDiscovery->WaitForInit();
// Construct a topic name with the partition and namespace
std::string fullyQualifiedTopic;
if (!TopicUtils::FullyQualifiedName(this->Options().Partition(),
this->Options().NameSpace(), _topic, fullyQualifiedTopic))
{
return false;
}
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
// Get all the publishers on the given topics
MsgAddresses_M pubs;
if (!this->dataPtr->shared->dataPtr->msgDiscovery->Publishers(
fullyQualifiedTopic, pubs))
{
return false;
}
_publishers.clear();
// Copy the publishers.
for (MsgAddresses_M::iterator iter = pubs.begin(); iter != pubs.end(); ++iter)
{
for (std::vector<MessagePublisher>::iterator pubIter = iter->second.begin();
pubIter != iter->second.end(); ++pubIter)
{
// Add the publisher if it doesn't already exist.
if (std::find(_publishers.begin(), _publishers.end(), *pubIter) ==
_publishers.end())
{
_publishers.push_back(*pubIter);
}
}
}
return true;
}
//////////////////////////////////////////////////
bool Node::ServiceInfo(const std::string &_service,
std::vector<ServicePublisher> &_publishers) const
{
this->dataPtr->shared->dataPtr->srvDiscovery->WaitForInit();
// Construct a topic name with the partition and namespace
std::string fullyQualifiedTopic;
if (!TopicUtils::FullyQualifiedName(this->Options().Partition(),
this->Options().NameSpace(), _service, fullyQualifiedTopic))
{
return false;
}
std::lock_guard<std::recursive_mutex> lk(this->dataPtr->shared->mutex);
// Get all the publishers on the given service.
SrvAddresses_M pubs;
if (!this->dataPtr->shared->dataPtr->srvDiscovery->Publishers(
fullyQualifiedTopic, pubs))
{
return false;
}
_publishers.clear();
// Copy the publishers.
for (SrvAddresses_M::iterator iter = pubs.begin(); iter != pubs.end(); ++iter)
{
for (std::vector<ServicePublisher>::iterator pubIter = iter->second.begin();
pubIter != iter->second.end(); ++pubIter)
{
// Add the publisher if it doesn't already exist.
if (std::find(_publishers.begin(), _publishers.end(), *pubIter) ==
_publishers.end())
{
_publishers.push_back(*pubIter);
}
}
}
return true;
}
/////////////////////////////////////////////////
Node::Publisher Node::Advertise(const std::string &_topic,
const std::string &_msgTypeName, const AdvertiseMessageOptions &_options)
{
// Topic remapping.
std::string topic = _topic;
this->Options().TopicRemap(_topic, topic);
std::string fullyQualifiedTopic;
if (!TopicUtils::FullyQualifiedName(this->Options().Partition(),
this->Options().NameSpace(), topic, fullyQualifiedTopic))
{
std::cerr << "Topic [" << topic << "] is not valid." << std::endl;
return Publisher();
}
auto currentTopics = this->AdvertisedTopics();
if (std::find(currentTopics.begin(), currentTopics.end(),
fullyQualifiedTopic) != currentTopics.end())
{
std::cerr << "Topic [" << topic << "] already advertised. You cannot"
<< " advertise the same topic twice on the same node."
<< " If you want to advertise the same topic with different"
<< " types, use separate nodes" << std::endl;
return Publisher();
}
std::lock_guard<std::recursive_mutex> lk(this->Shared()->mutex);
// Notify the discovery service to register and advertise my topic.
MessagePublisher publisher(fullyQualifiedTopic,
this->Shared()->myAddress,
// this->Shared()->myControlAddress,
"unused",
this->Shared()->pUuid, this->NodeUuid(), _msgTypeName, _options);
if (!this->Shared()->dataPtr->msgDiscovery->Advertise(publisher))
{
std::cerr << "Node::Advertise(): Error advertising topic ["
<< topic
<< "]. Did you forget to start the discovery service?"
<< std::endl;
return Publisher();
}
return Publisher(publisher);
}
//////////////////////////////////////////////////
bool NodePrivate::SubscribeHelper(const std::string &_fullyQualifiedTopic)
{
// Add the topic to the list of subscribed topics (if it was not before).
this->topicsSubscribed.insert(_fullyQualifiedTopic);
// Discover the list of nodes that publish on the topic.
if (!this->shared->dataPtr->msgDiscovery->Discover(_fullyQualifiedTopic))
{
std::cerr << "Node::Subscribe(): Error discovering topic ["
<< _fullyQualifiedTopic
<< "]. Did you forget to start the discovery service?"
<< std::endl;
return false;
}
return true;
}
/////////////////////////////////////////////////
bool Node::SubscribeHelper(const std::string &_fullyQualifiedTopic)
{
return this->dataPtr->SubscribeHelper(_fullyQualifiedTopic);
}