forked from bloomberg/blazingmq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqbnet_tcpsessionfactory.cpp
1562 lines (1338 loc) · 58.4 KB
/
mqbnet_tcpsessionfactory.cpp
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 2015-2023 Bloomberg Finance L.P.
// SPDX-License-Identifier: Apache-2.0
//
// 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.
// mqbnet_tcpsessionfactory.cpp -*-C++-*-
#include <mqbnet_tcpsessionfactory.h>
#include <mqbscm_version.h>
/// Implementation Notes
///====================
/// When a channel is being created, the following methods are always called,
/// in order, regardless of the success or failure of the negotiation:
/// - `channelStateCallback`
/// - `negotiate`
/// - `negotiationComplete`
///
/// When a channel goes down, `onClose()` is the only method being invoked.
// MQB
#include <mqbcfg_brokerconfig.h>
#include <mqbcfg_messages.h>
#include <mqbcfg_tcpinterfaceconfigvalidator.h>
#include <mqbnet_cluster.h>
#include <mqbnet_session.h>
// BMQ
#include <bmqex_executionutil.h>
#include <bmqex_systemexecutor.h>
#include <bmqio_channelutil.h>
#include <bmqio_connectoptions.h>
#include <bmqio_ntcchannel.h>
#include <bmqio_ntcchannelfactory.h>
#include <bmqio_resolveutil.h>
#include <bmqio_statchannel.h>
#include <bmqio_tcpendpoint.h>
#include <bmqp_event.h>
#include <bmqp_protocol.h>
#include <bmqp_protocolutil.h>
#include <bmqsys_threadutil.h>
#include <bmqsys_time.h>
#include <bmqu_blob.h>
#include <bmqu_memoutstream.h>
#include <bmqu_printutil.h>
// BDE
#include <ball_log.h>
#include <bdlb_scopeexit.h>
#include <bdlb_string.h>
#include <bdlf_bind.h>
#include <bdlf_placeholder.h>
#include <bdlma_localsequentialallocator.h>
#include <bdlt_timeunitratio.h>
#include <bsl_algorithm.h>
#include <bsl_cstdlib.h>
#include <bsl_iostream.h>
#include <bsl_limits.h>
#include <bsl_utility.h>
#include <bslalg_swaputil.h>
#include <bslmf_movableref.h>
#include <bslmt_lockguard.h>
#include <bslmt_once.h>
#include <bsls_annotation.h>
#include <bsls_performancehint.h>
#include <bsls_platform.h>
#include <bsls_systemclocktype.h>
#include <bsls_systemtime.h>
#include <bsls_timeinterval.h>
#include <bsls_types.h>
// NTC
#include <ntsa_error.h>
#include <ntsa_ipaddress.h>
namespace BloombergLP {
namespace mqbnet {
const char* TCPSessionFactory::k_CHANNEL_PROPERTY_PEER_IP = "tcp.peer.ip";
const char* TCPSessionFactory::k_CHANNEL_PROPERTY_LOCAL_PORT =
"tcp.local.port";
const char* TCPSessionFactory::k_CHANNEL_PROPERTY_CHANNEL_ID =
"channelpool.channel.id";
const char* TCPSessionFactory::k_CHANNEL_STATUS_CLOSE_REASON =
"reason.brokershutdown";
namespace {
BALL_LOG_SET_NAMESPACE_CATEGORY("MQBNET.TCPSESSIONFACTORY");
const int k_CONNECT_INTERVAL = 2;
const int k_SESSION_DESTROY_WAIT = 20;
// Maximum time to wait (in seconds) for all session to be destroyed
// during stop sequence.
const int k_CLIENT_CLOSE_WAIT = 20;
// Time to wait incrementally (in seconds) for all clients and
// proxies to be destroyed during stop sequence.
int calculateInitialMissedHbCounter(const mqbcfg::TcpInterfaceConfig& config)
{
// Calculate the value with which 'ChannelInfo.d_missedHeartbeatCounter'
// should be initialized when a channel is established. We want to give
// the peer a grace of 3 minutes before we take into account peer's
// heartbeats. This is needed so that if the peer is just starting up and
// is doing heavy lifting (connecting and negotiating with 100s of other
// peers, syncing storage files, etc), it has enough time to initiate the
// logic of periodic heartbeats. Specifically, if the peer connected to
// self node, it will schedule periodic heartbeat event only after it has
// received and processed negotiation response from self node (the
// 'server'). This can take several seconds, specially if peer's IO
// threads are busy with other connections as well.
// Based on this formula:
//..
// MaxInactivityIntervalSec = MissedHbCount * HbIntervalSec
//..
// we calculate initial value of 'MissedHbCount' like so (taking into
// account the possibility of overflow):
const int retVal = bsl::min(
bsl::numeric_limits<int>::max(),
static_cast<int>((3 * bdlt::TimeUnitRatio::k_MS_PER_M) /
config.heartbeatIntervalMs()));
return -retVal;
}
bsl::ostream& operator<<(bsl::ostream& os, const bmqio::Channel* channel)
{
// 'pretty-print' the specified 'channel' to the specified 'os'. The
// printed channel from that function includes the address of the channel
// for easy tracking and matching of logs.
if (channel) {
os << channel->peerUri() << "#" << static_cast<const void*>(channel);
}
else {
os << "*null*";
}
return os;
}
/// Callback invoked when the specified `channel` is created, as a result of
/// the operation with the specified `operationHandle`. This is used to set
/// a property on the channel, that higher levels (such as the
/// `SessionNegotiator` can extract and leverage).
void ntcChannelPreCreation(
const bsl::shared_ptr<bmqio::NtcChannel>& channel,
BSLS_ANNOTATION_UNUSED const
bsl::shared_ptr<bmqio::ChannelFactory::OpHandle>& operationHandle)
{
ntsa::Endpoint peerEndpoint = channel->peerEndpoint();
ntsa::Endpoint sourceEndpoint = channel->sourceEndpoint();
if (peerEndpoint.isIp() && peerEndpoint.ip().host().isV4()) {
channel->properties().set(
TCPSessionFactory::k_CHANNEL_PROPERTY_PEER_IP,
static_cast<int>(peerEndpoint.ip().host().v4().value()));
}
if (sourceEndpoint.isIp()) {
channel->properties().set(
TCPSessionFactory::k_CHANNEL_PROPERTY_LOCAL_PORT,
static_cast<int>(sourceEndpoint.ip().port()));
}
channel->properties().set(TCPSessionFactory::k_CHANNEL_PROPERTY_CHANNEL_ID,
channel->channelId());
}
/// Create the ntca::InterfaceConfig to use given the specified
/// `tcpConfig`
ntca::InterfaceConfig
ntcCreateInterfaceConfig(const mqbcfg::TcpInterfaceConfig& tcpConfig)
{
ntca::InterfaceConfig config;
config.setThreadName("mqbnet");
config.setMinThreads(tcpConfig.ioThreads());
config.setMaxThreads(tcpConfig.ioThreads());
config.setMaxConnections(tcpConfig.maxConnections());
config.setWriteQueueLowWatermark(tcpConfig.lowWatermark());
config.setWriteQueueHighWatermark(tcpConfig.highWatermark());
config.setAcceptGreedily(false);
config.setSendGreedily(false);
config.setReceiveGreedily(false);
config.setNoDelay(true);
config.setKeepAlive(true);
config.setKeepHalfOpen(false);
return config;
}
/// Load into the specified `resolvedUri` the reverse-DNS resolved URI of
/// the remote peer represented by the specified `baseChannel`. This is a
/// thin wrapper around the default DNS resolution from
/// `bmqio::ResolvingChannelFactoryUtil` that just adds final resolution
/// logging with time instrumentation.
void monitoredDNSResolution(bsl::string* resolvedUri,
const bmqio::Channel& baseChannel)
{
const bsls::Types::Int64 start = bmqsys::Time::highResolutionTimer();
bmqio::ResolvingChannelFactoryUtil::defaultResolutionFn(
resolvedUri,
baseChannel,
&bmqio::ResolveUtil::getDomainName,
true);
const bsls::Types::Int64 end = bmqsys::Time::highResolutionTimer();
BALL_LOG_INFO << "Channel " << static_cast<const void*>(&baseChannel)
<< " with remote peer " << baseChannel.peerUri()
<< " resolved to '" << *resolvedUri << "' (took: "
<< bmqu::PrintUtil::prettyTimeInterval(end - start) << ", "
<< (end - start) << " nanoseconds)";
// NOTE: cast the channel to actually just print the address and not the
// overload << operator. The channel's address printed here is that
// one of the 'bmqio::TcpChannel', while application will actually
// only see the 'bmqio::ResolvingChannelFactory_Channel'.
}
bool isClientOrProxy(const mqbnet::Session* session)
{
return mqbnet::ClusterUtil::isClientOrProxy(session->negotiationMessage());
}
void stopChannelFactory(bmqio::ChannelFactory* channelFactory)
{
bmqio::NtcChannelFactory* factory =
dynamic_cast<bmqio::NtcChannelFactory*>(channelFactory);
BSLS_ASSERT_SAFE(factory);
factory->stop();
}
/// A predicate functor for comparing a [mqbcfg::TcpInterfaceListener] by their
/// `port()` member.
struct PortMatcher {
int d_port;
PortMatcher(int port)
: d_port(port)
{
}
bool operator()(const mqbcfg::TcpInterfaceListener& listener)
{
return listener.port() == d_port;
}
};
} // close unnamed namespace
// -----------------------------------------
// struct TCPSessionFactory_OperationContext
// -----------------------------------------
/// Structure holding a context associated to each individual call to either
/// `listen` or `connect`.
struct TCPSessionFactory_OperationContext {
TCPSessionFactory::ResultCallback d_resultCb;
// Callback to invoke when a session is
// created/failed.
bool d_isIncoming;
// True if for incoming session (i.e., associated to
// a 'listen' operation); false for an outgoing
// session (i.e., associated to a 'connect'
// operation).
bsl::shared_ptr<void> d_negotiationUserData_sp;
// The negotiation user data, if any, provided by
// the caller (for the 'connect' operation); unused
// for a 'listen' operation. This is the user data
// that will be passed to the
// 'Negotiator::negotiate'.
void* d_resultState_p;
// The result state cookie, if any, provided by the
// caller (for the 'connect' operation); unused for
// a 'listen' operation. This is the initial value
// that will be set for the
// 'NegotiatorContext::resultState' passed to the
// 'Negotiator::negotiate'.
};
// -----------------------
// class TCPSessionFactory
// -----------------------
bslma::ManagedPtr<bmqst::StatContext>
TCPSessionFactory::channelStatContextCreator(
const bsl::shared_ptr<bmqio::Channel>& channel,
const bsl::shared_ptr<bmqio::StatChannelFactoryHandle>& handle)
{
int peerAddress;
channel->properties().load(&peerAddress, k_CHANNEL_PROPERTY_PEER_IP);
ntsa::Ipv4Address ipv4Address(static_cast<bsl::uint32_t>(peerAddress));
ntsa::IpAddress ipAddress(ipv4Address);
bmqst::StatContext* parent = d_statController_p->channelsStatContext(
bmqio::ChannelUtil::isLocalHost(ipAddress)
? mqbstat::StatController::ChannelSelector::e_LOCAL
: mqbstat::StatController::ChannelSelector::e_REMOTE);
BSLS_ASSERT_SAFE(parent);
bsl::string endpoint =
handle->options().is<bmqio::ConnectOptions>()
? handle->options().the<bmqio::ConnectOptions>().endpoint()
: channel->peerUri();
int localPort;
channel->properties().load(
&localPort,
TCPSessionFactory::k_CHANNEL_PROPERTY_LOCAL_PORT);
bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex); // LOCK
return d_ports.addChannelContext(parent,
endpoint,
static_cast<bsl::uint16_t>(localPort));
}
void TCPSessionFactory::negotiate(
const bsl::shared_ptr<bmqio::Channel>& channel,
const bsl::shared_ptr<OperationContext>& context)
{
// executed by one of the *IO* threads
BALL_LOG_INFO << "TCPSessionFactory '" << d_config.name()
<< "': allocating a channel with '" << channel.get() << "' ["
<< d_nbActiveChannels << " active channels]";
// Create a unique NegotiatorContext for the channel, from the
// OperationContext. This shared_ptr is bound to the 'negotiationComplete'
// callback below, which is what scopes its lifetime.
bsl::shared_ptr<NegotiatorContext> negotiatorContextSp;
negotiatorContextSp.createInplace(d_allocator_p, context->d_isIncoming);
(*negotiatorContextSp)
.setUserData(context->d_negotiationUserData_sp.get())
.setResultState(context->d_resultState_p);
// NOTE: we must ensure the 'negotiationCb' can be invoked from the
// 'negotiate()' call as specified on the 'Negotiator::negotiate'
// method contract (this means we can't have mutex lock around the
// call to 'negotiate').
d_negotiator_p->negotiate(
negotiatorContextSp.get(),
channel,
bdlf::BindUtil::bind(&TCPSessionFactory::negotiationComplete,
this,
bdlf::PlaceHolders::_1, // status
bdlf::PlaceHolders::_2, // errorDescription
bdlf::PlaceHolders::_3, // session
channel,
context,
negotiatorContextSp));
}
void TCPSessionFactory::readCallback(const bmqio::Status& status,
int* numNeeded,
bdlbb::Blob* blob,
ChannelInfo* channelInfo)
{
// executed by one of the *IO* threads
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(
status.category() == bmqio::StatusCategory::e_CANCELED)) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// There is nothing to do in the event of a 'e_CANCELED' event, so
// simply return.
return; // RETURN
}
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(
status.category() == bmqio::StatusCategory::e_CONNECTION)) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// There is a slight difference in behavior between BTE and NTZ when
// the peer shuts down the connection. BTE implicitly calls channel
// close(), and vast majority of the time does not trigger a read
// callback with CLOSED event (translated to a bmqio e_CONNECTION event
// by bmqio::Channel); OTH, NTZ always trigger a CLOSED event, but
// doesn't call close(). We explicitly call close() on the channel
// here to preserve the same behavior in NTZ as BTE and prevent a
// warning from being logged.
channelInfo->d_channel_p->close();
return; // RETURN
}
// PRECONDITIONS
BSLS_ASSERT_SAFE(channelInfo->d_eventProcessor_p &&
"EventProcessor must be set at this point");
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(!status)) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
BALL_LOG_ERROR << "#TCP_READ_ERROR "
<< channelInfo->d_session_sp->description()
<< ": ReadCallback error [status: " << status
<< ", channel: '" << channelInfo->d_channel_p << "']";
// Nothing much we can do, close the channel
channelInfo->d_channel_p->close();
return; // RETURN
}
bdlma::LocalSequentialAllocator<32 * sizeof(bdlbb::Blob) +
sizeof(bsl::vector<bdlbb::Blob>)>
lsa(d_allocator_p);
bsl::vector<bdlbb::Blob> readBlobs(&lsa);
readBlobs.reserve(32);
const int rc = bmqio::ChannelUtil::handleRead(&readBlobs, numNeeded, blob);
// NOTE: The blobs in readBlobs will be created using the vector's
// allocator, which is LSA, but that is ok because the blobs at the
// end are passed as pointer (through bmqp::Event) to the
// 'eventProcess::processEvent' which makes a full copy if it needs
// to async process the blob.
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(rc != 0)) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
BALL_LOG_ERROR << "#TCP_READ_ERROR "
<< channelInfo->d_session_sp->description()
<< ": ReadCallback unrecoverable error "
<< "[status: " << status << ", channel: '"
<< channelInfo->d_channel_p << "']:\n"
<< bmqu::BlobStartHexDumper(blob);
// Nothing much we can do, close the channel
channelInfo->d_channel_p->close();
return; // RETURN
}
// Not updating d_heartbeatMonitor until there is a valid event
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(readBlobs.empty())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// Don't yet have a full blob
return; // RETURN
}
for (size_t i = 0; i < readBlobs.size(); ++i) {
const bdlbb::Blob& readBlob = readBlobs[i];
BALL_LOG_TRACE << channelInfo->d_session_sp->description()
<< ": ReadCallback got a blob\n"
<< bmqu::BlobStartHexDumper(&readBlob);
bmqp::Event event(&readBlob, d_allocator_p);
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(!event.isValid())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
BALL_LOG_ERROR << "#TCP_INVALID_PACKET "
<< channelInfo->d_session_sp->description()
<< ": Received an invalid packet:\n"
<< bmqu::BlobStartHexDumper(&readBlob);
continue; // CONTINUE
}
if (channelInfo->d_monitor.checkData(channelInfo->d_channel_p,
event)) {
channelInfo->d_eventProcessor_p->processEvent(
event,
channelInfo->d_session_sp->clusterNode());
}
}
}
void TCPSessionFactory::negotiationComplete(
int statusCode,
const bsl::string& errorDescription,
const bsl::shared_ptr<Session>& session,
const bsl::shared_ptr<bmqio::Channel>& channel,
const bsl::shared_ptr<OperationContext>& context,
const bsl::shared_ptr<NegotiatorContext>& negotiatorContext)
{
// executed by one of the *IO* threads
if (statusCode != 0) {
// Failed to negotiate
BALL_LOG_WARN << "#SESSION_NEGOTIATION "
<< "TCPSessionFactory '" << d_config.name() << "' "
<< "failed to negotiate a session "
<< "[channel: '" << channel.get()
<< "', status: " << statusCode << ", error: '"
<< errorDescription << "']";
bmqio::Status status(bmqio::StatusCategory::e_GENERIC_ERROR,
"negotiationError",
statusCode,
d_allocator_p);
channel->close(status);
bdlma::LocalSequentialAllocator<64> localAlloc(d_allocator_p);
bmqu::MemOutStream logStream(&localAlloc);
logStream << "[channel: '" << channel.get() << "]";
logOpenSessionTime(logStream.str(), channel);
return; // RETURN
}
// Successful negotiation
BALL_LOG_INFO << "TCPSessionFactory '" << d_config.name()
<< "' successfully negotiated a session [session: '"
<< session->description() << "', channel: '" << channel.get()
<< "', maxMissedHeartbeat: "
<< negotiatorContext->maxMissedHeartbeat() << "]";
// Session is established; keep a hold to it.
// First, 'decorate' the session shared_ptr's destructor so that we can
// get a notification upon its destruction.
// We could have const_cast the supplied 'session', but the below release
// would then have potential side-effect on the caller if it wanted to
// still use the object after invoking the negotiation callback.
bsl::shared_ptr<Session> tmpSession = session;
bsl::pair<Session*, bslma::SharedPtrRep*> rawSession =
tmpSession.release();
bsl::shared_ptr<Session> monitoredSession(
rawSession.first,
bdlf::BindUtil::bind(&TCPSessionFactory::onSessionDestroyed,
this,
d_self.acquireWeak(),
bdlf::PlaceHolders::_1, // ptr
rawSession.second)); // rep
ChannelInfoSp info;
bsl::pair<ChannelMap::iterator, bool> inserted;
{
bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex); // LOCK
++d_nbSessions;
info.createInplace(d_allocator_p,
channel,
*negotiatorContext,
d_initialMissedHeartbeatCounter,
monitoredSession);
// See comments in 'calculateInitialMissedHbCounter'.
bsl::pair<bmqio::Channel*, ChannelInfoSp> toInsert(channel.get(),
info);
inserted = d_channels.insert(toInsert);
info = inserted.first->second;
if (isClientOrProxy(info->d_session_sp.get())) {
++d_nbOpenClients;
}
} // close mutex lock guard // UNLOCK
// Do not initiate reading from the channel. Transport observer(s) will
// enable the read when they are ready.
bool result = context->d_resultCb(
bmqio::ChannelFactoryEvent::e_CHANNEL_UP,
bmqio::Status(),
monitoredSession,
negotiatorContext->cluster(),
negotiatorContext->resultState(),
bdlf::BindUtil::bind(&TCPSessionFactory::readCallback,
this,
bdlf::PlaceHolders::_1, // status
bdlf::PlaceHolders::_2, // numNeeded
bdlf::PlaceHolders::_3, // blob
info.get()));
if (!result || !d_isListening) {
// TODO: Revisit if still needed, following move to bmqio.
//
// If 'stopListening' have been called, 'tearDown' may or may not
// have been called, depending whether the 'callback' has been
// called before or after 'stopListening'. Invoke 'tearDown'
// explicitly (it supports subsequent calls).
BALL_LOG_WARN << "#TCP_UNEXPECTED_STATE "
<< "TCPSessionFactory '" << d_config.name()
<< (result ? "' has initiated shutdown "
: "' has encountered an error ")
<< "while negotiating a session [session: '"
<< monitoredSession->description() << "', channel: '"
<< channel.get() << "']";
// This will eventually call 'btemt_ChannelPool::shutdown' which will
// schedule channelStateCb/poolSessionStateCb/onClose/tearDown
channel->close();
logOpenSessionTime(session->description(), channel);
return; // RETURN
}
if (info->d_monitor.isHearbeatEnabled()) {
// Enable heartbeating
d_scheduler_p->scheduleEvent(
bsls::TimeInterval(0),
bdlf::BindUtil::bind(&TCPSessionFactory::enableHeartbeat,
this,
info.get()));
}
logOpenSessionTime(session->description(), channel);
}
void TCPSessionFactory::onSessionDestroyed(
const bsl::weak_ptr<TCPSessionFactory>& self,
void* session,
void* sprep)
{
// Delete the session object by releasing its associated rep.
bslma::SharedPtrRep* rep = static_cast<bslma::SharedPtrRep*>(sprep);
bool isClient = isClientOrProxy(static_cast<Session*>(session));
rep->releaseRef();
bsl::shared_ptr<TCPSessionFactory> strongSelf = self.lock();
if (!strongSelf) {
// The TCPSessionFactory object was destroyed: this could happen
// because in stop, we timeWait on all sessions to have been destroyed,
// so if a session takes longer to be destroyed, this method could be
// invoked after the factory has been deleted, in this case, nothing
// more to do here.
return; // RETURN
}
bslmt::LockGuard<bslmt::Mutex> counterGuard(&d_mutex); // LOCK
if (isClient) {
if (--d_nbOpenClients == 0) {
d_noClientCondition.signal();
}
}
if (--d_nbSessions == 0) {
d_noSessionCondition.signal();
}
}
void TCPSessionFactory::channelStateCallback(
bmqio::ChannelFactoryEvent::Enum event,
const bmqio::Status& status,
const bsl::shared_ptr<bmqio::Channel>& channel,
const bsl::shared_ptr<OperationContext>& context)
{
// This function (over time) will be executed by each of the IO threads.
// This is an infrequent enough operation (compared to a 'readCb') that it
// is fine to do this here (since we have no other ways to
// proactively-execute code in the IO threads created by the channelPool).
bmqsys::ThreadUtil::setCurrentThreadNameOnce(d_threadName);
BALL_LOG_TRACE << "TCPSessionFactory '" << d_config.name()
<< "': channelStateCallback [event: " << event
<< ", status: " << status << ", channel: '" << channel.get()
<< "', " << d_nbActiveChannels << " active channels]";
switch (event) {
case bmqio::ChannelFactoryEvent::e_CHANNEL_UP: {
BSLS_ASSERT_SAFE(status); // got a channel up, it must be success
BSLS_ASSERT_SAFE(channel);
if (channel->peerUri().empty()) {
BALL_LOG_ERROR << "#SESSION_NEGOTIATION "
<< "TCPSessionFactory '" << d_config.name() << "' "
<< "rejecting empty peer URI: '" << channel.get()
<< "'";
bmqio::Status closeStatus(bmqio::StatusCategory::e_GENERIC_ERROR,
d_allocator_p);
channel->close(closeStatus);
}
else {
{ // Save begin session timestamp
// TODO: it's possible to store this timestamp directly in one
// of the bmqio::Channel implementations, so we don't need a
// mutex synchronization for them at all.
bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex); // LOCK
d_timestampMap[channel.get()] =
bmqsys::Time::highResolutionTimer();
} // close mutex lock guard // UNLOCK
// Keep track of active channels, for logging purposes
++d_nbActiveChannels;
// Register as observer of the channel to get the 'onClose'
channel->onClose(bdlf::BindUtil::bindS(
d_allocator_p,
&TCPSessionFactory::onClose,
this,
channel,
bdlf::PlaceHolders::_1 /* bmqio::Status */));
negotiate(channel, context);
}
} break;
case bmqio::ChannelFactoryEvent::e_CONNECT_ATTEMPT_FAILED: {
// Nothing
} break;
case bmqio::ChannelFactoryEvent::e_CONNECT_FAILED: {
// This means the session in 'listen' or 'connect' failed to
// negotiate (maybe rejected by the remote peer..)
context->d_resultCb(event,
status,
bsl::shared_ptr<Session>(),
0, // Cluster*
context->d_resultState_p,
bmqio::Channel::ReadCallback());
} break;
}
}
void TCPSessionFactory::onClose(const bsl::shared_ptr<bmqio::Channel>& channel,
const bmqio::Status& status)
{
--d_nbActiveChannels;
int port;
channel->properties().load(
&port,
TCPSessionFactory::k_CHANNEL_PROPERTY_LOCAL_PORT);
ChannelInfoSp channelInfo;
{
// Lookup the session and remove it from internal map
bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex); // LOCK
ChannelMap::const_iterator it = d_channels.find(channel.get());
if (it != d_channels.end()) {
channelInfo = it->second;
d_channels.erase(it);
}
d_ports.onDeleteChannelContext(port);
} // close mutex lock guard // UNLOCK
if (!channelInfo) {
// We register to the close event as soon as the channel is up;
// however, we insert in the d_channels only upon successful
// negotiation; therefore a failed to negotiate channel (like during
// intrusion testing) would trigger this trace.
BALL_LOG_INFO << "#TCP_UNEXPECTED_STATE "
<< "TCPSessionFactory '" << d_config.name()
<< "': OnClose channel for an unknown channel '"
<< channel.get() << "', " << d_nbActiveChannels
<< " active channels, status: " << status;
}
else {
BALL_LOG_INFO << "TCPSessionFactory '" << d_config.name()
<< "': OnClose channel [session: '"
<< channelInfo->d_session_sp->description()
<< "', channel: '" << channel.get() << "', "
<< d_nbActiveChannels << " active channels"
<< ", status: " << status << "]";
// Synchronously remove from heartbeat monitored channels
if (channelInfo->d_monitor.isHearbeatEnabled() &&
d_heartbeatSchedulerActive) {
// NOTE: When shutting down, we don't care about heartbeat
// verifying the channel, therefore, as an optimization to
// avoid the one-by-one disable for each channel (as they all
// will get closed at this time), the 'stop()' sequence
// cancels the recurring event and wait before closing the
// channels, so we don't need to 'disableHeartbeat' in this
// case.
d_scheduler_p->scheduleEvent(
bsls::TimeInterval(0),
bdlf::BindUtil::bind(&TCPSessionFactory::disableHeartbeat,
this,
channelInfo));
}
// TearDown the session
int isBrokerShutdown = false;
if (status.category() == bmqio::StatusCategory::e_SUCCESS) {
status.properties().load(&isBrokerShutdown,
k_CHANNEL_STATUS_CLOSE_REASON);
}
channelInfo->d_session_sp->tearDown(channelInfo->d_session_sp,
isBrokerShutdown);
}
}
void TCPSessionFactory::onHeartbeatSchedulerEvent()
{
// executed by the *SCHEDULER* thread
for (bsl::unordered_map<bmqio::Channel*, ChannelInfo*>::const_iterator it =
d_heartbeatChannels.begin();
it != d_heartbeatChannels.end();) {
ChannelInfo* info = it->second;
if (!info->d_monitor.checkHeartbeat(info->d_channel_p)) {
const Session* session = info->d_session_sp.get();
BSLS_ASSERT_SAFE(session);
const ClusterNode* node = session->clusterNode();
BALL_LOG_WARN << "#TCP_DEAD_CHANNEL " << "TCPSessionFactory '"
<< d_config.name() << "'"
<< ": Closing unresponsive channel after "
<< info->d_monitor.maxMissedHeartbeats()
<< " missed heartbeats [session: '"
<< session->description() << "', channel: '"
<< info->d_channel_p << "', node: '"
<< (node ? node->nodeDescription() : "") << "' ]";
info->d_channel_p->close();
// Avoid interference with new connection on the channel
it = d_heartbeatChannels.erase(it);
}
else {
++it;
}
}
}
void TCPSessionFactory::enableHeartbeat(ChannelInfo* channelInfo)
{
// executed by the *SCHEDULER* thread
d_heartbeatChannels[channelInfo->d_channel_p] = channelInfo;
}
void TCPSessionFactory::disableHeartbeat(
const bsl::shared_ptr<ChannelInfo>& channelInfo)
{
// executed by the *SCHEDULER* thread
BSLS_ASSERT_SAFE(channelInfo);
BSLS_ASSERT_SAFE(channelInfo->d_session_sp);
BALL_LOG_INFO << "Disabling TCPSessionFactory '" << d_config.name()
<< "' Heartbeat for [session: '"
<< channelInfo->d_session_sp->description()
<< "', channel: '" << channelInfo->d_channel_p << "' ]";
d_heartbeatChannels.erase(channelInfo->d_channel_p);
}
void TCPSessionFactory::logOpenSessionTime(
const bsl::string& sessionDescription,
const bsl::shared_ptr<bmqio::Channel>& channel)
{
bsls::Types::Int64 begin = 0;
{
bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex); // LOCK
TimestampMap::const_iterator it = d_timestampMap.find(channel.get());
if (it != d_timestampMap.end()) {
begin = it->second;
d_timestampMap.erase(it);
}
} // close mutex lock guard // UNLOCK
if (begin) {
BALL_LOG_INFO_BLOCK
{
const bsls::Types::Int64 elapsed =
bmqsys::Time::highResolutionTimer() - begin;
BALL_LOG_OUTPUT_STREAM
<< "Open session '" << sessionDescription
<< "' took: " << bmqu::PrintUtil::prettyTimeInterval(elapsed)
<< " (" << elapsed << " nanoseconds)";
}
}
}
TCPSessionFactory::TCPSessionFactory(
const mqbcfg::TcpInterfaceConfig& config,
bdlmt::EventScheduler* scheduler,
bdlbb::BlobBufferFactory* blobBufferFactory,
Negotiator* negotiator,
mqbstat::StatController* statController,
bslma::Allocator* allocator)
: d_self(this) // use default allocator
, d_isStarted(false)
, d_config(config, allocator)
, d_scheduler_p(scheduler)
, d_blobBufferFactory_p(blobBufferFactory)
, d_negotiator_p(negotiator)
, d_statController_p(statController)
, d_tcpChannelFactory_mp()
, d_resolutionContext(allocator)
, d_resolvingChannelFactory_mp()
, d_reconnectingChannelFactory_mp()
, d_statChannelFactory_mp()
, d_threadName(allocator)
, d_nbActiveChannels(0)
, d_nbOpenClients(0)
, d_nbSessions(0)
, d_noSessionCondition(bsls::SystemClockType::e_MONOTONIC)
, d_noClientCondition(bsls::SystemClockType::e_MONOTONIC)
, d_channels(allocator)
, d_ports(allocator)
, d_heartbeatSchedulerActive(false)
, d_heartbeatChannels(allocator)
, d_initialMissedHeartbeatCounter(calculateInitialMissedHbCounter(config))
, d_listeningHandles(allocator)
, d_isListening(false)
, d_listenContexts(allocator)
, d_timestampMap(allocator)
, d_allocator_p(allocator)
{
// PRECONDITIONS
BSLS_ASSERT_SAFE(scheduler->clockType() ==
bsls::SystemClockType::e_MONOTONIC);
// Resolve the default address of this host
bsl::string hostname;
ntsa::Error error = bmqio::ResolveUtil::getHostname(&hostname);
if (error.code() != ntsa::Error::e_OK) {
BALL_LOG_ERROR << "Failed to get local hostname, error: " << error;
BSLS_ASSERT_OPT(false && "Failed to get local host name");
return; // RETURN
}
ntsa::Ipv4Address defaultIP;
error = bmqio::ResolveUtil::getIpAddress(&defaultIP, hostname);
if (error.code() != ntsa::Error::e_OK) {
BALL_LOG_ERROR << "Failed to get IP address of the host '" << hostname
<< "' error: " << error;
BSLS_ASSERT_OPT(false && "Failed to get IP address of the host.");
return; // RETURN
}
BALL_LOG_INFO << "TcpSessionFactory '" << d_config.name() << "' "
<< "[Hostname: " << hostname << ", ipAddress: " << defaultIP
<< "]";
// Thread name
d_threadName = "bmqIO_" + d_config.name().substr(0, 15 - 6);
// on Linux, a thread name is limited to 16 characters,
// including the \0.
}
TCPSessionFactory::~TCPSessionFactory()
{
// PRECONDITIONS
BSLS_ASSERT_OPT(!d_isStarted &&
"stop() must be called before destroying this object");
BALL_LOG_INFO << "Destructing TCPSessionFactory '" << d_config.name()
<< "'";
d_self.invalidate();
}
int TCPSessionFactory::validateTcpInterfaces() const
{
mqbcfg::TcpInterfaceConfigValidator validator;
return validator(d_config);
}
void TCPSessionFactory::cancelListeners()
{
for (ListeningHandleMap::iterator it = d_listeningHandles.begin(),
end = d_listeningHandles.end();
it != end;
++it) {
BSLS_ASSERT_SAFE(it->second);
it->second->cancel();
it->second.reset();
}
d_listeningHandles.clear();
d_listenContexts.clear();
}
int TCPSessionFactory::start(bsl::ostream& errorDescription)
{
// PRECONDITIONS
BSLS_ASSERT_OPT(!d_isStarted &&
"start() can only be called once on this object");
BALL_LOG_INFO << "Starting TCPSessionFactory '" << d_config.name() << "'";
int rc = 0;
rc = validateTcpInterfaces();
if (rc != 0) {
errorDescription << "Failed to validate the TCP interface config for "
<< "TCPSessionFactory '" << d_config.name()
<< "' [rc: " << rc << "]";
return rc; // RETURN
}
ntca::InterfaceConfig interfaceConfig = ntcCreateInterfaceConfig(d_config);
bslma::ManagedPtr<bmqio::NtcChannelFactory> channelFactory;
channelFactory.load(new (*d_allocator_p)
bmqio::NtcChannelFactory(interfaceConfig,
d_blobBufferFactory_p,
d_allocator_p),