-
Notifications
You must be signed in to change notification settings - Fork 939
Expand file tree
/
Copy pathDataWriterImpl.cpp
More file actions
2348 lines (2049 loc) · 77.3 KB
/
Copy pathDataWriterImpl.cpp
File metadata and controls
2348 lines (2049 loc) · 77.3 KB
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019, 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/*
* DataWriterImpl.cpp
*
*/
#include <fastdds/publisher/DataWriterImpl.hpp>
#include <functional>
#include <iostream>
#include <fastdds/core/condition/StatusConditionImpl.hpp>
#include <fastdds/core/policy/ParameterSerializer.hpp>
#include <fastdds/core/policy/QosPolicyUtils.hpp>
#include <fastdds/dds/domain/DomainParticipant.hpp>
#include <fastdds/dds/log/Log.hpp>
#include <fastdds/dds/publisher/DataWriter.hpp>
#include <fastdds/dds/publisher/Publisher.hpp>
#include <fastdds/dds/publisher/PublisherListener.hpp>
#include <fastdds/dds/topic/TypeSupport.hpp>
#include <fastdds/domain/DomainParticipantImpl.hpp>
#include <fastdds/publisher/filtering/DataWriterFilteredChangePool.hpp>
#include <fastdds/publisher/PublisherImpl.hpp>
#include <fastdds/rtps/builtin/liveliness/WLP.h>
#include <fastdds/rtps/common/Time_t.h>
#include <fastdds/rtps/participant/RTPSParticipant.h>
#include <fastdds/rtps/resources/ResourceEvent.h>
#include <fastdds/rtps/resources/TimedEvent.h>
#include <fastdds/rtps/RTPSDomain.h>
#include <fastdds/rtps/writer/RTPSWriter.h>
#include <fastdds/rtps/writer/StatefulWriter.h>
#include <fastrtps/attributes/TopicAttributes.h>
#include <fastrtps/config.h>
#include <fastrtps/utils/TimeConversion.h>
#include <rtps/DataSharing/DataSharingPayloadPool.hpp>
#include <rtps/history/CacheChangePool.h>
#include <rtps/history/TopicPayloadPoolRegistry.hpp>
#include <rtps/participant/RTPSParticipantImpl.h>
#include <rtps/RTPSDomainImpl.hpp>
#ifdef FASTDDS_STATISTICS
#include <statistics/fastdds/domain/DomainParticipantImpl.hpp>
#include <statistics/types/monitorservice_types.h>
#endif // FASTDDS_STATISTICS
using namespace eprosima::fastrtps;
using namespace eprosima::fastrtps::rtps;
using namespace std::chrono;
namespace eprosima {
namespace fastdds {
namespace dds {
static ChangeKind_t unregister_change_kind(
bool dispose,
const DataWriterQos& qos)
{
if (dispose)
{
return NOT_ALIVE_DISPOSED;
}
return qos.writer_data_lifecycle().autodispose_unregistered_instances ?
NOT_ALIVE_DISPOSED_UNREGISTERED : NOT_ALIVE_UNREGISTERED;
}
static bool qos_has_pull_mode_request(
const DataWriterQos& qos)
{
auto push_mode = PropertyPolicyHelper::find_property(qos.properties(), "fastdds.push_mode");
return (nullptr != push_mode) && ("false" == *push_mode);
}
class DataWriterImpl::LoanCollection
{
public:
explicit LoanCollection(
const PoolConfig& config)
: loans_(get_collection_limits(config))
{
}
bool add_loan(
void* data,
PayloadInfo_t& payload)
{
static_cast<void>(data);
assert(data == payload.payload.data + SerializedPayload_t::representation_header_size);
return loans_.push_back(payload);
}
bool check_and_remove_loan(
void* data,
PayloadInfo_t& payload)
{
octet* payload_data = static_cast<octet*>(data) - SerializedPayload_t::representation_header_size;
for (auto it = loans_.begin(); it != loans_.end(); ++it)
{
if (it->payload.data == payload_data)
{
payload = *it;
loans_.erase(it);
return true;
}
}
return false;
}
bool is_empty() const
{
return loans_.empty();
}
private:
static ResourceLimitedContainerConfig get_collection_limits(
const PoolConfig& config)
{
return
{
config.initial_size,
config.maximum_size,
config.initial_size == config.maximum_size ? 0u : 1u
};
}
ResourceLimitedVector<PayloadInfo_t> loans_;
};
DataWriterImpl::DataWriterImpl(
PublisherImpl* p,
TypeSupport type,
Topic* topic,
const DataWriterQos& qos,
DataWriterListener* listen,
std::shared_ptr<fastrtps::rtps::IPayloadPool> payload_pool)
: publisher_(p)
, type_(type)
, topic_(topic)
, qos_(get_datawriter_qos_from_settings(qos))
, listener_(listen)
, history_(get_topic_attributes(qos_, *topic_, type_), type_->m_typeSize, qos_.endpoint().history_memory_policy,
[this](
const InstanceHandle_t& handle) -> void
{
if (nullptr != listener_)
{
listener_->on_unacknowledged_sample_removed(user_datawriter_, handle);
}
})
#pragma warning (disable : 4355 )
, writer_listener_(this)
, deadline_duration_us_(qos_.deadline().period.to_ns() * 1e-3)
, lifespan_duration_us_(qos_.lifespan().duration.to_ns() * 1e-3)
{
EndpointAttributes endpoint_attributes;
endpoint_attributes.endpointKind = WRITER;
endpoint_attributes.topicKind = type_->m_isGetKeyDefined ? WITH_KEY : NO_KEY;
endpoint_attributes.setEntityID(qos_.endpoint().entity_id);
endpoint_attributes.setUserDefinedID(qos_.endpoint().user_defined_id);
fastrtps::rtps::RTPSParticipantImpl::preprocess_endpoint_attributes<WRITER, 0x03, 0x02>(
EntityId_t::unknown(), publisher_->get_participant_impl()->id_counter(), endpoint_attributes, guid_.entityId);
guid_.guidPrefix = publisher_->get_participant_impl()->guid().guidPrefix;
if (payload_pool != nullptr)
{
is_custom_payload_pool_ = true;
payload_pool_ = payload_pool;
}
}
DataWriterImpl::DataWriterImpl(
PublisherImpl* p,
TypeSupport type,
Topic* topic,
const DataWriterQos& qos,
const fastrtps::rtps::EntityId_t& entity_id,
DataWriterListener* listen)
: publisher_(p)
, type_(type)
, topic_(topic)
, qos_(get_datawriter_qos_from_settings(qos))
, listener_(listen)
, history_(get_topic_attributes(qos_, *topic_, type_), type_->m_typeSize, qos_.endpoint().history_memory_policy,
[this](
const InstanceHandle_t& handle) -> void
{
if (nullptr != listener_)
{
listener_->on_unacknowledged_sample_removed(user_datawriter_, handle);
}
})
#pragma warning (disable : 4355 )
, writer_listener_(this)
, deadline_duration_us_(qos_.deadline().period.to_ns() * 1e-3)
, lifespan_duration_us_(qos_.lifespan().duration.to_ns() * 1e-3)
{
guid_ = { publisher_->get_participant_impl()->guid().guidPrefix, entity_id};
}
DataWriterQos DataWriterImpl::get_datawriter_qos_from_settings(
const DataWriterQos& qos)
{
DataWriterQos return_qos;
if (&DATAWRITER_QOS_DEFAULT == &qos)
{
return_qos = publisher_->get_default_datawriter_qos();
}
else if (&DATAWRITER_QOS_USE_TOPIC_QOS == &qos)
{
return_qos = publisher_->get_default_datawriter_qos();
publisher_->copy_from_topic_qos(return_qos, topic_->get_qos());
}
else
{
return_qos = qos;
}
return return_qos;
}
ReturnCode_t DataWriterImpl::enable()
{
assert(writer_ == nullptr);
pool_config_ = PoolConfig::from_history_attributes(history_.m_att);
// When the user requested PREALLOCATED_WITH_REALLOC, but we know the type cannot
// grow, we translate the policy into bare PREALLOCATED
if (PREALLOCATED_WITH_REALLOC_MEMORY_MODE == pool_config_.memory_policy &&
(type_->is_bounded() || type_->is_plain(data_representation_)))
{
pool_config_.memory_policy = PREALLOCATED_MEMORY_MODE;
}
WriterAttributes w_att;
w_att.throughputController = qos_.throughput_controller();
w_att.endpoint.durabilityKind = qos_.durability().durabilityKind();
w_att.endpoint.endpointKind = WRITER;
w_att.endpoint.reliabilityKind = qos_.reliability().kind == RELIABLE_RELIABILITY_QOS ? RELIABLE : BEST_EFFORT;
w_att.endpoint.topicKind = type_->m_isGetKeyDefined ? WITH_KEY : NO_KEY;
w_att.endpoint.multicastLocatorList = qos_.endpoint().multicast_locator_list;
w_att.endpoint.unicastLocatorList = qos_.endpoint().unicast_locator_list;
w_att.endpoint.remoteLocatorList = qos_.endpoint().remote_locator_list;
w_att.endpoint.external_unicast_locators = qos_.endpoint().external_unicast_locators;
w_att.endpoint.ignore_non_matching_locators = qos_.endpoint().ignore_non_matching_locators;
w_att.mode = qos_.publish_mode().kind == SYNCHRONOUS_PUBLISH_MODE ? SYNCHRONOUS_WRITER : ASYNCHRONOUS_WRITER;
w_att.flow_controller_name = qos_.publish_mode().flow_controller_name;
w_att.endpoint.properties = qos_.properties();
w_att.endpoint.ownershipKind = qos_.ownership().kind;
w_att.endpoint.setEntityID(qos_.endpoint().entity_id);
w_att.endpoint.setUserDefinedID(qos_.endpoint().user_defined_id);
w_att.times = qos_.reliable_writer_qos().times;
w_att.liveliness_kind = qos_.liveliness().kind;
w_att.liveliness_lease_duration = qos_.liveliness().lease_duration;
w_att.liveliness_announcement_period = qos_.liveliness().announcement_period;
w_att.matched_readers_allocation = qos_.writer_resource_limits().matched_subscriber_allocation;
w_att.disable_heartbeat_piggyback = qos_.reliable_writer_qos().disable_heartbeat_piggyback;
// TODO(Ricardo) Remove in future
// Insert topic_name and partitions
Property property;
property.name("topic_name");
property.value(topic_->get_name().c_str());
w_att.endpoint.properties.properties().push_back(std::move(property));
std::string* endpoint_partitions = PropertyPolicyHelper::find_property(qos_.properties(), "partitions");
if (endpoint_partitions)
{
property.name("partitions");
property.value(*endpoint_partitions);
w_att.endpoint.properties.properties().push_back(std::move(property));
}
else if (publisher_->get_qos().partition().names().size() > 0)
{
property.name("partitions");
std::string partitions;
bool is_first_partition = true;
for (auto partition : publisher_->get_qos().partition().names())
{
partitions += (is_first_partition ? "" : ";") + partition;
is_first_partition = false;
}
property.value(std::move(partitions));
w_att.endpoint.properties.properties().push_back(std::move(property));
}
if (qos_.reliable_writer_qos().disable_positive_acks.enabled &&
qos_.reliable_writer_qos().disable_positive_acks.duration != c_TimeInfinite)
{
w_att.disable_positive_acks = true;
w_att.keep_duration = qos_.reliable_writer_qos().disable_positive_acks.duration;
}
ReturnCode_t ret_code = check_datasharing_compatible(w_att, is_data_sharing_compatible_);
if (ret_code != ReturnCode_t::RETCODE_OK)
{
return ret_code;
}
if (is_data_sharing_compatible_)
{
DataSharingQosPolicy datasharing(qos_.data_sharing());
if (datasharing.domain_ids().empty())
{
datasharing.add_domain_id(utils::default_domain_id());
}
w_att.endpoint.set_data_sharing_configuration(datasharing);
// Update pool config for KEEP_ALL when max_samples is infinite
if ((0 >= pool_config_.maximum_size) && (KEEP_ALL_HISTORY_QOS == qos_.history().kind))
{
// Override infinite with old default value for max_samples + extra samples
pool_config_.maximum_size = 5000;
if (0 < qos_.resource_limits().extra_samples)
{
pool_config_.maximum_size += static_cast<uint32_t>(qos_.resource_limits().extra_samples);
}
EPROSIMA_LOG_ERROR(DATA_WRITER,
"DataWriter with KEEP_ALL history and infinite max_samples is not compatible with DataSharing. "
"Setting max_samples to " << pool_config_.maximum_size);
}
}
else
{
DataSharingQosPolicy datasharing;
datasharing.off();
w_att.endpoint.set_data_sharing_configuration(datasharing);
}
bool filtering_enabled =
qos_.liveliness().lease_duration.is_infinite() &&
(0 < qos_.writer_resource_limits().reader_filters_allocation.maximum);
if (filtering_enabled)
{
reader_filters_.reset(new ReaderFilterCollection(qos_.writer_resource_limits().reader_filters_allocation));
}
// Set Datawriter's DataRepresentationId taking into account the QoS.
data_representation_ = qos_.representation().m_value.empty()
|| XCDR_DATA_REPRESENTATION == qos_.representation().m_value.at(0)
? XCDR_DATA_REPRESENTATION : XCDR2_DATA_REPRESENTATION;
auto change_pool = get_change_pool();
if (!change_pool)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Problem creating change pool for associated Writer");
return ReturnCode_t::RETCODE_ERROR;
}
auto pool = get_payload_pool();
if (!pool)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Problem creating payload pool for associated Writer");
return ReturnCode_t::RETCODE_ERROR;
}
RTPSWriter* writer = RTPSDomainImpl::create_rtps_writer(
publisher_->rtps_participant(),
guid_.entityId,
w_att,
pool,
change_pool,
static_cast<WriterHistory*>(&history_),
static_cast<WriterListener*>(&writer_listener_));
if (writer == nullptr &&
w_att.endpoint.data_sharing_configuration().kind() == DataSharingKind::AUTO)
{
EPROSIMA_LOG_INFO(DATA_WRITER, "Trying with a non-datasharing pool");
release_payload_pool();
is_data_sharing_compatible_ = false;
DataSharingQosPolicy datasharing;
datasharing.off();
w_att.endpoint.set_data_sharing_configuration(datasharing);
pool = get_payload_pool();
if (!pool)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Problem creating payload pool for associated Writer");
return ReturnCode_t::RETCODE_ERROR;
}
writer = RTPSDomainImpl::create_rtps_writer(
publisher_->rtps_participant(),
guid_.entityId,
w_att,
pool,
change_pool,
static_cast<WriterHistory*>(&history_),
static_cast<WriterListener*>(&writer_listener_));
}
if (writer == nullptr)
{
release_payload_pool();
EPROSIMA_LOG_ERROR(DATA_WRITER, "Problem creating associated Writer");
return ReturnCode_t::RETCODE_ERROR;
}
writer_ = writer;
if (filtering_enabled)
{
writer_->reader_data_filter(this);
}
// In case it has been loaded from the persistence DB, rebuild instances on history
history_.rebuild_instances();
configure_deadline_timer_();
lifespan_timer_ = new TimedEvent(publisher_->get_participant()->get_resource_event(),
[&]() -> bool
{
return lifespan_expired();
},
qos_.lifespan().duration.to_ns() * 1e-6);
// In case it has been loaded from the persistence DB, expire old samples.
if (qos_.lifespan().duration != c_TimeInfinite)
{
if (lifespan_expired())
{
lifespan_timer_->restart_timer();
}
}
// REGISTER THE WRITER
WriterQos wqos = qos_.get_writerqos(get_publisher()->get_qos(), topic_->get_qos());
if (!is_data_sharing_compatible_)
{
wqos.data_sharing.off();
}
if (endpoint_partitions)
{
std::istringstream partition_string(*endpoint_partitions);
std::string partition_name;
wqos.m_partition.clear();
while (std::getline(partition_string, partition_name, ';'))
{
wqos.m_partition.push_back(partition_name.c_str());
}
}
publisher_->rtps_participant()->registerWriter(writer_, get_topic_attributes(qos_, *topic_, type_), wqos);
return ReturnCode_t::RETCODE_OK;
}
void DataWriterImpl::disable()
{
set_listener(nullptr);
if (writer_ != nullptr)
{
writer_->set_listener(nullptr);
}
}
ReturnCode_t DataWriterImpl::check_delete_preconditions()
{
if (loans_ && !loans_->is_empty())
{
return ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
return ReturnCode_t::RETCODE_OK;
}
DataWriterImpl::~DataWriterImpl()
{
delete lifespan_timer_;
delete deadline_timer_;
if (writer_ != nullptr)
{
EPROSIMA_LOG_INFO(DATA_WRITER, guid().entityId << " in topic: " << type_->getName());
RTPSDomain::removeRTPSWriter(writer_);
release_payload_pool();
}
delete user_datawriter_;
}
ReturnCode_t DataWriterImpl::loan_sample(
void*& sample,
LoanInitializationKind initialization)
{
// Block lowlevel writer
auto max_blocking_time = steady_clock::now() +
microseconds(::TimeConv::Time_t2MicroSecondsInt64(qos_.reliability().max_blocking_time));
// Type should be plain and have space for the representation header
if (!type_->is_plain(data_representation_) || SerializedPayload_t::representation_header_size > type_->m_typeSize)
{
return ReturnCode_t::RETCODE_ILLEGAL_OPERATION;
}
// Writer should be enabled
if (nullptr == writer_)
{
return ReturnCode_t::RETCODE_NOT_ENABLED;
}
#if HAVE_STRICT_REALTIME
std::unique_lock<RecursiveTimedMutex> lock(writer_->getMutex(), std::defer_lock);
if (!lock.try_lock_until(max_blocking_time))
{
return ReturnCode_t::RETCODE_TIMEOUT;
}
#else
static_cast<void>(max_blocking_time);
std::lock_guard<RecursiveTimedMutex> lock(writer_->getMutex());
#endif // if HAVE_STRICT_REALTIME
// Get one payload from the pool
PayloadInfo_t payload;
uint32_t size = type_->m_typeSize;
if (!get_free_payload_from_pool([size]()
{
return size;
}, payload))
{
return ReturnCode_t::RETCODE_OUT_OF_RESOURCES;
}
// Leave payload state as if serialization has already been performed
payload.payload.length = size;
payload.payload.pos = size;
payload.payload.data[1] = DEFAULT_ENCAPSULATION;
payload.payload.encapsulation = DEFAULT_ENCAPSULATION;
// Sample starts after representation header
sample = payload.payload.data + SerializedPayload_t::representation_header_size;
// Add to loans collection
if (!add_loan(sample, payload))
{
sample = nullptr;
return_payload_to_pool(payload);
return ReturnCode_t::RETCODE_OUT_OF_RESOURCES;
}
switch (initialization)
{
default:
EPROSIMA_LOG_WARNING(DATA_WRITER, "Using wrong LoanInitializationKind value ("
<< static_cast<int>(initialization) << "). Using default NO_LOAN_INITIALIZATION");
break;
case LoanInitializationKind::NO_LOAN_INITIALIZATION:
break;
case LoanInitializationKind::ZERO_LOAN_INITIALIZATION:
if (SerializedPayload_t::representation_header_size < size)
{
size -= SerializedPayload_t::representation_header_size;
memset(sample, 0, size);
}
break;
case LoanInitializationKind::CONSTRUCTED_LOAN_INITIALIZATION:
if (!type_->construct_sample(sample))
{
check_and_remove_loan(sample, payload);
return_payload_to_pool(payload);
sample = nullptr;
return ReturnCode_t::RETCODE_UNSUPPORTED;
}
break;
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DataWriterImpl::discard_loan(
void*& sample)
{
// Type should be plain and have space for the representation header
if (!type_->is_plain(data_representation_) || SerializedPayload_t::representation_header_size > type_->m_typeSize)
{
return ReturnCode_t::RETCODE_ILLEGAL_OPERATION;
}
// Writer should be enabled
if (nullptr == writer_)
{
return ReturnCode_t::RETCODE_NOT_ENABLED;
}
std::lock_guard<RecursiveTimedMutex> lock(writer_->getMutex());
// Remove sample from loans collection
PayloadInfo_t payload;
if ((nullptr == sample) || !check_and_remove_loan(sample, payload))
{
return ReturnCode_t::RETCODE_BAD_PARAMETER;
}
// Return payload to pool
return_payload_to_pool(payload);
sample = nullptr;
return ReturnCode_t::RETCODE_OK;
}
bool DataWriterImpl::write(
void* data)
{
if (writer_ == nullptr)
{
return false;
}
EPROSIMA_LOG_INFO(DATA_WRITER, "Writing new data");
return ReturnCode_t::RETCODE_OK == create_new_change(ALIVE, data);
}
bool DataWriterImpl::write(
void* data,
fastrtps::rtps::WriteParams& params)
{
if (writer_ == nullptr)
{
return false;
}
EPROSIMA_LOG_INFO(DATA_WRITER, "Writing new data with WriteParams");
return ReturnCode_t::RETCODE_OK == create_new_change_with_params(ALIVE, data, params);
}
ReturnCode_t DataWriterImpl::check_write_preconditions(
void* data,
const InstanceHandle_t& handle,
InstanceHandle_t& instance_handle)
{
if (writer_ == nullptr)
{
return ReturnCode_t::RETCODE_NOT_ENABLED;
}
if (type_.get()->m_isGetKeyDefined)
{
bool is_key_protected = false;
#if HAVE_SECURITY
is_key_protected = writer_->getAttributes().security_attributes().is_key_protected;
#endif // if HAVE_SECURITY
type_.get()->getKey(data, &instance_handle, is_key_protected);
}
// Check if the Handle is different from the special value HANDLE_NIL and
// does not correspond with the instance referred by the data
if (handle.isDefined() && handle != instance_handle)
{
return ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DataWriterImpl::write(
void* data,
const InstanceHandle_t& handle)
{
InstanceHandle_t instance_handle;
ReturnCode_t ret = check_write_preconditions(data, handle, instance_handle);
if (ReturnCode_t::RETCODE_OK == ret)
{
EPROSIMA_LOG_INFO(DATA_WRITER, "Writing new data with Handle");
WriteParams wparams;
ret = create_new_change_with_params(ALIVE, data, wparams, instance_handle);
}
return ret;
}
ReturnCode_t DataWriterImpl::write_w_timestamp(
void* data,
const InstanceHandle_t& handle,
const fastrtps::Time_t& timestamp)
{
InstanceHandle_t instance_handle;
ReturnCode_t ret = ReturnCode_t::RETCODE_OK;
if (timestamp.is_infinite() || timestamp.seconds < 0)
{
ret = ReturnCode_t::RETCODE_BAD_PARAMETER;
}
if (ReturnCode_t::RETCODE_OK == ret)
{
ret = check_write_preconditions(data, handle, instance_handle);
}
if (ReturnCode_t::RETCODE_OK == ret)
{
EPROSIMA_LOG_INFO(DATA_WRITER, "Writing new data with Handle and timestamp");
WriteParams wparams;
wparams.source_timestamp(timestamp);
ret = create_new_change_with_params(ALIVE, data, wparams, instance_handle);
}
return ret;
}
ReturnCode_t DataWriterImpl::check_instance_preconditions(
void* data,
const InstanceHandle_t& handle,
InstanceHandle_t& instance_handle)
{
if (nullptr == writer_)
{
return ReturnCode_t::RETCODE_NOT_ENABLED;
}
if (nullptr == data)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Data pointer not valid");
return ReturnCode_t::RETCODE_BAD_PARAMETER;
}
if (!type_->m_isGetKeyDefined)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Topic is NO_KEY, operation not permitted");
return ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
instance_handle = handle;
#if defined(NDEBUG)
if (!instance_handle.isDefined())
#endif // if !defined(NDEBUG)
{
bool is_key_protected = false;
#if HAVE_SECURITY
is_key_protected = writer_->getAttributes().security_attributes().is_key_protected;
#endif // if HAVE_SECURITY
type_->getKey(data, &instance_handle, is_key_protected);
}
#if !defined(NDEBUG)
if (handle.isDefined() && instance_handle != handle)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "handle differs from data's key.");
return ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
#endif // if !defined(NDEBUG)
return ReturnCode_t::RETCODE_OK;
}
InstanceHandle_t DataWriterImpl::register_instance(
void* key)
{
/// Preconditions
InstanceHandle_t instance_handle;
if (ReturnCode_t::RETCODE_OK != check_instance_preconditions(key, HANDLE_NIL, instance_handle))
{
return HANDLE_NIL;
}
WriteParams wparams;
return do_register_instance(key, instance_handle, wparams);
}
InstanceHandle_t DataWriterImpl::register_instance_w_timestamp(
void* key,
const fastrtps::Time_t& timestamp)
{
/// Preconditions
InstanceHandle_t instance_handle;
if (timestamp.is_infinite() || timestamp.seconds < 0 ||
(ReturnCode_t::RETCODE_OK != check_instance_preconditions(key, HANDLE_NIL, instance_handle)))
{
return HANDLE_NIL;
}
WriteParams wparams;
wparams.source_timestamp(timestamp);
return do_register_instance(key, instance_handle, wparams);
}
InstanceHandle_t DataWriterImpl::do_register_instance(
void* key,
const InstanceHandle_t instance_handle,
WriteParams& wparams)
{
// TODO(MiguelCompany): wparams should be used when propagating the register_instance operation to the DataReader.
// See redmine issue #14494
static_cast<void>(wparams);
// Block lowlevel writer
auto max_blocking_time = std::chrono::steady_clock::now() +
std::chrono::microseconds(::TimeConv::Time_t2MicroSecondsInt64(qos_.reliability().max_blocking_time));
#if HAVE_STRICT_REALTIME
std::unique_lock<RecursiveTimedMutex> lock(writer_->getMutex(), std::defer_lock);
if (lock.try_lock_until(max_blocking_time))
#else
std::unique_lock<RecursiveTimedMutex> lock(writer_->getMutex());
#endif // if HAVE_STRICT_REALTIME
{
SerializedPayload_t* payload = nullptr;
if (history_.register_instance(instance_handle, lock, max_blocking_time, payload))
{
// Keep serialization of sample inside the instance
assert(nullptr != payload);
if (0 == payload->length || nullptr == payload->data)
{
uint32_t size = fixed_payload_size_ ? fixed_payload_size_ : type_->getSerializedSizeProvider(key)();
payload->reserve(size);
if (!type_->serialize(key, payload))
{
EPROSIMA_LOG_WARNING(DATA_WRITER, "Key data serialization failed");
// Serialization of the sample failed. Remove the instance to keep original state.
// Note that we will only end-up here if the instance has just been created, so it will be empty
// and removing its changes will remove the instance completely.
history_.remove_instance_changes(instance_handle, SequenceNumber_t());
}
}
return instance_handle;
}
}
return HANDLE_NIL;
}
ReturnCode_t DataWriterImpl::unregister_instance(
void* instance,
const InstanceHandle_t& handle,
bool dispose)
{
// Preconditions
InstanceHandle_t ih;
ReturnCode_t returned_value = check_instance_preconditions(instance, handle, ih);
if (ReturnCode_t::RETCODE_OK == returned_value && !history_.is_key_registered(ih))
{
returned_value = ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
// Operation
if (ReturnCode_t::RETCODE_OK == returned_value)
{
WriteParams wparams;
ChangeKind_t change_kind = unregister_change_kind(dispose, qos_);
returned_value = create_new_change_with_params(change_kind, instance, wparams, ih);
}
return returned_value;
}
ReturnCode_t DataWriterImpl::unregister_instance_w_timestamp(
void* instance,
const InstanceHandle_t& handle,
const fastrtps::Time_t& timestamp,
bool dispose)
{
// Preconditions
InstanceHandle_t instance_handle;
ReturnCode_t ret = ReturnCode_t::RETCODE_OK;
if (timestamp.is_infinite() || timestamp.seconds < 0)
{
ret = ReturnCode_t::RETCODE_BAD_PARAMETER;
}
if (ReturnCode_t::RETCODE_OK == ret)
{
ret = check_instance_preconditions(instance, handle, instance_handle);
}
if (ReturnCode_t::RETCODE_OK == ret && !history_.is_key_registered(instance_handle))
{
ret = ReturnCode_t::RETCODE_PRECONDITION_NOT_MET;
}
// Operation
if (ReturnCode_t::RETCODE_OK == ret)
{
WriteParams wparams;
wparams.source_timestamp(timestamp);
ChangeKind_t change_kind = unregister_change_kind(dispose, qos_);
ret = create_new_change_with_params(change_kind, instance, wparams, instance_handle);
}
return ret;
}
ReturnCode_t DataWriterImpl::get_key_value(
void* key_holder,
const InstanceHandle_t& handle)
{
/// Preconditions
if (key_holder == nullptr || !handle.isDefined())
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Key holder pointer not valid");
return ReturnCode_t::RETCODE_BAD_PARAMETER;
}
if (!type_->m_isGetKeyDefined)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Topic is NO_KEY, operation not permitted");
return ReturnCode_t::RETCODE_ILLEGAL_OPERATION;
}
if (writer_ == nullptr)
{
return ReturnCode_t::RETCODE_NOT_ENABLED;
}
// Block lowlevel writer
#if HAVE_STRICT_REALTIME
auto max_blocking_time = std::chrono::steady_clock::now() +
std::chrono::microseconds(::TimeConv::Time_t2MicroSecondsInt64(qos_.reliability().max_blocking_time));
std::unique_lock<RecursiveTimedMutex> lock(writer_->getMutex(), std::defer_lock);
if (!lock.try_lock_until(max_blocking_time))
{
return ReturnCode_t::RETCODE_TIMEOUT;
}
#else
std::lock_guard<RecursiveTimedMutex> lock(writer_->getMutex());
#endif // if HAVE_STRICT_REALTIME
SerializedPayload_t* payload = history_.get_key_value(handle);
if (nullptr == payload)
{
return ReturnCode_t::RETCODE_BAD_PARAMETER;
}
type_->deserialize(payload, key_holder);
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DataWriterImpl::create_new_change(
ChangeKind_t changeKind,
void* data)
{
WriteParams wparams;
return create_new_change_with_params(changeKind, data, wparams);
}
ReturnCode_t DataWriterImpl::check_new_change_preconditions(
ChangeKind_t change_kind,
void* data)
{
// Preconditions
if (data == nullptr)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Data pointer not valid");
return ReturnCode_t::RETCODE_BAD_PARAMETER;
}
if (change_kind == NOT_ALIVE_UNREGISTERED
|| change_kind == NOT_ALIVE_DISPOSED
|| change_kind == NOT_ALIVE_DISPOSED_UNREGISTERED)
{
if (!type_->m_isGetKeyDefined)
{
EPROSIMA_LOG_ERROR(DATA_WRITER, "Topic is NO_KEY, operation not permitted");
return ReturnCode_t::RETCODE_ILLEGAL_OPERATION;
}
}
return ReturnCode_t::RETCODE_OK;
}
ReturnCode_t DataWriterImpl::perform_create_new_change(
ChangeKind_t change_kind,
void* data,
WriteParams& wparams,
const InstanceHandle_t& handle)
{
// Block lowlevel writer
auto max_blocking_time = steady_clock::now() +
microseconds(::TimeConv::Time_t2MicroSecondsInt64(qos_.reliability().max_blocking_time));
#if HAVE_STRICT_REALTIME
std::unique_lock<RecursiveTimedMutex> lock(writer_->getMutex(), std::defer_lock);
if (!lock.try_lock_until(max_blocking_time))
{
return ReturnCode_t::RETCODE_TIMEOUT;
}
#else
std::unique_lock<RecursiveTimedMutex> lock(writer_->getMutex());
#endif // if HAVE_STRICT_REALTIME
PayloadInfo_t payload;
bool was_loaned = check_and_remove_loan(data, payload);
if (!was_loaned)
{
// Initialize payload to null state