-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathmqba_clientsession.cpp
3237 lines (2764 loc) · 125 KB
/
mqba_clientsession.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 2014-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.
// mqba_clientsession.cpp -*-C++-*-
#include <mqba_clientsession.h>
#include <mqbscm_version.h>
/// Implementation Notes
///====================
//
/// Threading
///---------
// In order to be lock free, *all* methods are or must be executed on the
// *client dispatcher thread*. The only exceptions are:
//: o processEvent: main entry of processing of data from the channel, executes
//: on the IO thread and does basic safe processing before enqueuing for the
//: client dispatcher
//: o onHighWatermark / onLowWatermark: notification event on the IO thread
//: o tearDown: executes on the IO thread when the channel went down
//
/// Shutdown
///--------
// At a high level, a graceful shutdown has the following flow:
// - The client sends a 'Disconnect' control message
// - The broker replies with a 'DisconnectResponse' control message
// - In response to that message, the client closes the channel
// - This triggers execution of the 'teardown' method
// However, an ungraceful shutdown can happen at any time (including in the
// middle of the above described sequence).
//
// The following defines the contract between the client and the broker with
// regards to graceful shutdown:
//: o The 'Disconnect' control message is the last packet sent by the client
//: (note that it may not even be sent if the client didn't go down cleanly).
//: o The 'DisconnectResponse' control message is the last one sent by the
//: broker to the client.
//
// During disconnect processing / teardown, we leverage the dispatcher queues
// to synchronize and ensure no more messages or events are pending for the
// client, so we can safely destroy it. However, this solution will not work
// for remotely activated asynchronous requests (such as 'openQueue' which
// could be sending an async request to the cluster, and deliver the response
// through the proxyBroker<->clusterBroker IO channel). For those kind of
// requests, the 'bmqu::SharedResource' must be used. All callbacks having the
// shared resource bound and which will be invoked through the dispatcher must
// do so by using the 'e_DISPATCHER' dispatcher event type, to ensure the
// client will not be added to the dispatcher's flush list: the client may
// potentially have been destroyed prior to invocation of the callback.
//
// As soon as a queue handle has been dropped, it may be deleted. Client
// session holds raw pointers to the handle. There could be a race situation
// where Queue has enqueued some PUSH (or ACK) events to the dispatcher queue
// of the client; while the client dropped the handle (due to ungraceful
// shutdown), and the drop and handle deletion will be processed before those
// PUSH/ACK events, leading to dangling pointer access. That is why the handle
// pointer is nilled immediately after a call to drop, and checked before
// access.
//
// The following variables are used for keeping track of the shutdown state:
//: o d_self:
//: This is used, as described above, for the situation of remotely activated
//: asynchronous messages, which can't be synchronized by enqueuing a marker
//: in the dispatcher's queue.
//: o d_operationState:
//: This enum is only set and checked in the client thread. By default it
//: has e_RUNNING value corresponding to the state when the session is
//: running normally. It is changed when the session is shutting down by one
//: of the reasons:
//: o e_SHUTTING_DOWN - when 'initiateShutdown' is called and graceful
//: shutdown is performed. All the queue handles get deconfigured and the
//: session is waiting for the unconfirmed messages if there are any;
//: o e_DISCONNECTING - when disconnect request comes from the client. All
//: the queue handles get dropped and when done the disconnect response is
//: sent back to the client;
//: o e_DISCONNECTED - in case of the channel went down, or right after
//: sending the 'DisconnectResponse' message to the client. Once set to
//: e_DISCONNECTED, no messages should ever be delivered to the client.
//: Since the above events may happen concurrently (e.g. disconnect request
//: comes when the graceful shutdown is in progress) the following state
//: transitions are possible:
//: e_RUNNING -> e_SHUTTING_DOWN
//: e_RUNNING -> e_DISCONNECTING
//: e_RUNNING -> e_DISCONNECTED
//: e_SHUTTING_DOWN -> e_DISCONNECTING
//: e_SHUTTING_DOWN -> e_DISCONNECTED
//: e_DISCONNECTING -> e_DISCONNECTED
//: This means that the e_SHUTTING_DOWN has the lowest priority, i.e. the
//: graceful shutdown sequence is started only if the session was running
//: normally, and the sequence is interrupted once disconnect or channel down
//: events come.
//: o d_isDisconnecting:
//: This boolean is only set and checked in 'processEvent', executing on the
//: IO thread, to validate and safe-guard against a client misbehaving and
//: sending messages after sending a 'Disconnect' request message.
//
// NOTE: the last 'hop' in the openQueue/closeQueue methods (the one that will
// enqueue back to execute in the client dispatcher thread) doesn't need
// to use the 'd_self', because it already holds the shared resource, and
// in 'teardown', we ensure to drain the client dispatcher thread before
// returning. However that last method must verify the
// 'd_operationState' because after enqueuing to dispatch, the client may
// be dying.
//
///'d_operationState' in onConfirmEvent / onPutEvent:
///------------------------------------------------------
// We should NOT check for 'd_operationState' enum in those two methods:
// those are downstream to upstream events and if the client sent us such
// messages, we should honor them even if the client crashed right after.
//
// 'd_operationState' is set to 'e_DISCONNECTED' under two conditions:
// 1) at the end of the processing of a client Disconnect request, after which,
// per contract, no messages (especially no 'Confirm' nor 'Put' events are
// expected to be received). The 'd_isDisconnecting' check in
// 'processEvent' guarantees that.
// 2) when the channel drops, which is synchronizing on the client dispatcher
// thread where this value is set.
// In this case, the only possible sequence of event is the following:
// - ProcessEvent(IO thread)
// |-> enqueue 'onConfirmEvent/onPutEvent' to be processed on the
// client dispatcher thread
// - 'teardown' and then enqueuing a 'teardownImpl' to be processed on the
// client dispatcher thread where d_operationState is set. This can
// only happen after 'processEvent' finished because both executes on
// the IO thread.
// - The client dispatcher queue now looks like:
// |...|tearDownImpl|onConfirm/PutEvent| ->>
// We therefore have guarantees that the onConfirm/PutEvent will be
// processed before the queue handles are dropped (which happens in
// teardownImpl).
//
// NOTE:
// - Not checking the 'd_operationState' everytime in those methods is also a
// welcome micro optimization as those are on the critical message path.
// - for the case of 'PutEvent', we will have to check, and not send NACKs if
// the 'd_operationState' is set to 'e_DISCONNECTED'.
// MQB
#include <mqbblp_clustercatalog.h>
#include <mqbblp_queueengineutil.h>
#include <mqbcfg_brokerconfig.h>
#include <mqbi_cluster.h>
#include <mqbi_queue.h>
#include <mqbnet_tcpsessionfactory.h>
#include <mqbstat_brokerstats.h>
#include <mqbu_messageguidutil.h>
// BMQ
#include <bmqp_compression.h>
#include <bmqp_confirmmessageiterator.h>
#include <bmqp_controlmessageutil.h>
#include <bmqp_event.h>
#include <bmqp_messageproperties.h>
#include <bmqp_protocolutil.h>
#include <bmqp_putmessageiterator.h>
#include <bmqp_queueid.h>
#include <bmqp_queueutil.h>
#include <bmqp_rejectmessageiterator.h>
#include <bmqt_messageguid.h>
#include <bmqt_resultcode.h>
#include <bmqt_uri.h>
#include <bmqio_status.h>
#include <bmqst_statcontext.h>
#include <bmqtsk_alarmlog.h>
#include <bmqu_blob.h>
#include <bmqu_printutil.h>
#include <bmqu_weakmemfn.h>
// BDE
#include <ball_log.h>
#include <ball_logthrottle.h>
#include <bdlb_nullablevalue.h>
#include <bdlb_scopeexit.h>
#include <bdld_datum.h>
#include <bdld_datummapbuilder.h>
#include <bdld_manageddatum.h>
#include <bdlf_bind.h>
#include <bdlf_noop.h>
#include <bdlf_placeholder.h>
#include <bdlma_localsequentialallocator.h>
#include <bdlt_timeunitratio.h>
#include <bsl_iostream.h>
#include <bsl_limits.h>
#include <bsl_memory.h>
#include <bsl_vector.h>
#include <bslma_managedptr.h>
#include <bslmt_semaphore.h>
#include <bsls_annotation.h>
#include <bsls_assert.h>
#include <bsls_performancehint.h>
namespace BloombergLP {
namespace mqba {
namespace {
BALL_LOG_SET_NAMESPACE_CATEGORY("MQBA.CLIENTSESSION");
const int k_NAGLE_PACKET_SIZE = 1024 * 1024; // 1MB
/// This method does nothing other than calling the 'initiateShutdown' callback
/// if it is present; it is just used so that we can control when the session
/// can be destroyed, during the shutdown flow, by binding the specified
/// `session` (which is a shared_ptr to the session itself) to events being
/// enqueued to the dispatcher and let it die `naturally` when all threads are
/// drained up to the event.
void sessionHolderDummy(
const mqba::ClientSession::ShutdownCb& shutdownCallback,
BSLS_ANNOTATION_UNUSED const bsl::shared_ptr<void>& session)
{
if (shutdownCallback) {
shutdownCallback();
}
}
/// Create the queue stats datum associated with the specified `statContext`
/// and having the specified `domain`, `cluster`, and `queueFlags`.
void createQueueStatsDatum(bmqst::StatContext* statContext,
const bsl::string& domain,
const bsl::string& cluster,
bsls::Types::Uint64 queueFlags)
{
typedef bslma::ManagedPtr<bdld::ManagedDatum> ManagedDatumMp;
bslma::Allocator* alloc = statContext->datumAllocator();
ManagedDatumMp datum = statContext->datum();
bdld::DatumMapBuilder builder(alloc);
builder.pushBack("queueFlags",
bdld::Datum::createInteger64(queueFlags, alloc));
builder.pushBack("domain", bdld::Datum::copyString(domain, alloc));
builder.pushBack("cluster", bdld::Datum::copyString(cluster, alloc));
datum->adopt(builder.commit());
}
bmqp_ctrlmsg::ClientIdentity* extractClientIdentity(
const bmqp_ctrlmsg::NegotiationMessage& negotiationMessage)
// Based on the client type, return the pointer to the correct identity field
// of the specified 'negotiationMesage'.
{
switch (negotiationMessage.selectionId()) {
case bmqp_ctrlmsg::NegotiationMessage::SELECTION_INDEX_CLIENT_IDENTITY: {
return const_cast<bmqp_ctrlmsg::ClientIdentity*>(
&negotiationMessage.clientIdentity()); // RETURN
}
case bmqp_ctrlmsg::NegotiationMessage::SELECTION_INDEX_BROKER_RESPONSE: {
return const_cast<bmqp_ctrlmsg::ClientIdentity*>(
&negotiationMessage.brokerResponse().brokerIdentity()); // RETURN
}
default: {
BSLS_ASSERT_OPT(false && "Invalid negotiation message");
return 0; // RETURN
}
};
}
bool isClientGeneratingGUIDs(
const bmqp_ctrlmsg::ClientIdentity& clientIdentity)
// Return true when the client identity 'guidInfo' struct contains non-empty
// 'clientId' field
{
return !clientIdentity.guidInfo().clientId().empty(); // RETURN
}
// Finalize the specified 'handle' associated with the specified 'description'
void finalizeClosedHandle(bsl::string description,
const bsl::shared_ptr<mqbi::QueueHandle>& handle)
{
// executed by ONE of the *QUEUE* dispatcher threads
BSLS_ASSERT_SAFE(
handle->queue()->dispatcher()->inDispatcherThread(handle->queue()));
BALL_LOG_INFO << description << ": Closed queue handle is finalized: "
<< handle->handleParameters();
}
/// Stack-built functor to pass to `bmqp::ProtocolUtil::buildEvent`
struct BuildAckFunctor {
// DATA
bmqp::AckEventBuilder& d_ackBuilder;
int d_status;
int d_correlationId;
const bmqt::MessageGUID& d_messageGUID;
int d_queueId;
// CREATORS
inline explicit BuildAckFunctor(bmqp::AckEventBuilder& ackBuilder,
int status,
int correlationId,
const bmqt::MessageGUID& messageGUID,
int queueId)
: d_ackBuilder(ackBuilder)
, d_status(status)
, d_correlationId(correlationId)
, d_messageGUID(messageGUID)
, d_queueId(queueId)
{
// NOTHING
}
// MANIPULATORS
inline bmqt::EventBuilderResult::Enum operator()()
{
return d_ackBuilder.appendMessage(d_status,
d_correlationId,
d_messageGUID,
d_queueId);
}
};
/// Stack-built functor to pass to `bmqp::ProtocolUtil::buildEvent`
struct BuildAckOverflowFunctor {
// DATA
mqba::ClientSession& d_session;
// CREATORS
inline explicit BuildAckOverflowFunctor(mqba::ClientSession& session)
: d_session(session)
{
// NOTHING
}
// MANIPULATORS
inline void operator()() { d_session.flush(); }
};
} // close unnamed namespace
// -------------------------
// struct ClientSessionState
// -------------------------
ClientSessionState::ClientSessionState(
bslma::ManagedPtr<bmqst::StatContext>& clientStatContext,
BlobSpPool* blobSpPool,
bdlbb::BlobBufferFactory* bufferFactory,
bmqp::EncodingType::Enum encodingType,
bslma::Allocator* allocator)
: d_allocator_p(allocator)
, d_channelBufferQueue(allocator)
, d_unackedMessageInfos(d_allocator_p)
, d_dispatcherClientData()
, d_statContext_mp(clientStatContext)
, d_bufferFactory_p(bufferFactory)
, d_blobSpPool_p(blobSpPool)
, d_schemaEventBuilder(blobSpPool, encodingType, allocator)
, d_pushBuilder(blobSpPool, allocator)
, d_ackBuilder(blobSpPool, allocator)
{
// PRECONDITIONS
BSLS_ASSERT_SAFE(encodingType != bmqp::EncodingType::e_UNKNOWN);
}
// -------------------
// class ClientSession
// -------------------
// PRIVATE MANIPULATORS
void ClientSession::sendErrorResponse(
bmqp_ctrlmsg::StatusCategory::Value failureCategory,
const bslstl::StringRef& errorDescription,
const int code,
const bmqp_ctrlmsg::ControlMessage& request)
{
// executed by the *CLIENT* dispatcher thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
bdlma::LocalSequentialAllocator<2048> localAllocator(
d_state.d_allocator_p);
bmqp_ctrlmsg::ControlMessage response(&localAllocator);
response.rId() = request.rId().value();
response.choice().makeStatus();
response.choice().status().category() = failureCategory;
response.choice().status().message() = errorDescription;
response.choice().status().code() = code;
d_state.d_schemaEventBuilder.reset();
int rc = d_state.d_schemaEventBuilder.setMessage(
response,
bmqp::EventType::e_CONTROL);
if (rc != 0) {
BALL_LOG_ERROR << "#CLIENT_SEND_FAILURE " << description()
<< ": Unable to send "
<< request.choice().selectionName()
<< " failure response [reason: ENCODING_FAILED, rc: "
<< rc << "]: " << response;
return; // RETURN
}
BALL_LOG_INFO << description() << ": Sending "
<< request.choice().selectionName()
<< " failure response: " << response;
// Send the response
sendPacketDispatched(d_state.d_schemaEventBuilder.blob(), true);
}
void ClientSession::sendPacket(const bsl::shared_ptr<bdlbb::Blob>& blob,
bool flushBuilders)
{
dispatcher()->execute(
bdlf::BindUtil::bind(&ClientSession::sendPacketDispatched,
this,
blob,
flushBuilders),
this);
}
void ClientSession::sendPacketDispatched(
const bsl::shared_ptr<bdlbb::Blob>& blob,
bool flushBuilders)
{
// executed by the *CLIENT* dispatcher thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
// This method is the centralized *single* place where we should try to
// send data to the client over the channel.
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(isDisconnected())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
return; // RETURN
}
// NOTE: By any means, blobs in the channelBufferQueue should be considered
// by other parts of the broker (queueHandle for example) as if they
// have been sent out to the client. The sole purpose of this logic
// is to smooth out the send of huge burst of data, with respect to
// the Channel watermarks limits and the rate at which data can be
// written to the channel. Messages should never be staying more
// than a couple milliseconds (or eventually seconds if there are
// gigabytes of data) in this buffer queue.
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(
!d_state.d_channelBufferQueue.empty())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// If the channelBuffer is not empty, we can't send, we have to enqueue
// to guarantee ordering of messages.
d_state.d_channelBufferQueue.push_back(blob);
return; // RETURN
}
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(flushBuilders)) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// 'flushBuilders' should only be used when sending control messages,
// so not on the likely path.
flush();
// If 'flush' wasn't able to send all the data, some might now be
// buffered in the 'channelBufferQueue', so check for it again.
if (!d_state.d_channelBufferQueue.empty()) {
d_state.d_channelBufferQueue.push_back(blob);
return; // RETURN
}
}
// Try to send the data, if we fail due to high watermark limit, enqueue
// the message to the channelBufferQueue, and we'll send it later, once we
// get the lowWatermark notification.
bmqio::Status status;
d_channel_sp->write(&status, *blob);
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(
status.category() != bmqio::StatusCategory::e_SUCCESS)) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
if (status.category() == bmqio::StatusCategory::e_CONNECTION) {
// This code relies on the fact that `e_CONNECTION` error cannot be
// returned without calling `tearDown`.
return; // RETURN
}
if (status.category() == bmqio::StatusCategory::e_LIMIT) {
BALL_LOG_WARN << "#CLIENT_SEND_FAILURE " << description()
<< ": Failed to send data [size: "
<< bmqu::PrintUtil::prettyNumber(blob->length())
<< " bytes] to client due to channel watermark limit"
<< "; enqueuing to the ChannelBufferQueue.";
d_state.d_channelBufferQueue.push_back(blob);
}
else {
BALL_LOG_INFO << "#CLIENT_SEND_FAILURE " << description()
<< ": Failed to send data [size: "
<< bmqu::PrintUtil::prettyNumber(blob->length())
<< " bytes] to client with status: " << status;
}
}
}
void ClientSession::flushChannelBufferQueue()
{
// executed by the *CLIENT* dispatcher thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(isDisconnected())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
return; // RETURN
}
BALL_LOG_INFO << description() << ": Flushing ChannelBufferQueue ("
<< d_state.d_channelBufferQueue.size() << " items)";
// Try to send as many data as possible
while (!d_state.d_channelBufferQueue.empty()) {
const bsl::shared_ptr<bdlbb::Blob>& blob_sp =
d_state.d_channelBufferQueue.front();
bmqio::Status status;
d_channel_sp->write(&status, *blob_sp);
if (status.category() == bmqio::StatusCategory::e_LIMIT) {
// We are hitting the limit again, can't continue.. stop sending
// and we'll resume with the next lowWatermark notification.
BALL_LOG_WARN
<< "#CLIENT_SEND_FAILURE " << description()
<< ": Failed to send data to client due to channel "
<< "watermark limit while flushing ChannelBufferQueue"
"; will continue later";
break; // BREAK
}
d_state.d_channelBufferQueue.pop_front();
}
}
void ClientSession::sendAck(bmqt::AckResult::Enum status,
int correlationId,
const bmqt::MessageGUID& messageGUID,
const QueueState* queueState,
int queueId,
bool isSelfGenerated,
const bslstl::StringRef& source)
{
// executed by the *CLIENT* dispatcher thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
// NOTE: if this is the first hop, 'messageGUID' will be unset. If this is
// not the first hop, correlationId will be NULL. But this method
// does not care about them.
bmqt::Uri uri;
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(status !=
bmqt::AckResult::e_SUCCESS)) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// When we receive a PUT event for an unknown queue (likely the queue
// was already closed), we NACK it with e_INVALID_ARGUMENT; in this
// case, the queue is expected not to be found in the d_queues map, and
// therefore we expect to be passed a null pointer for the
// 'queueState'; otherwise we expect a valid queue state, with a valid
// non-closed queue handle.
if (queueState) {
BSLS_ASSERT_SAFE(queueState->d_handle_p);
uri = queueState->d_handle_p->queue()->uri();
// If queue is found, report locally generated NACK
if (isSelfGenerated) {
queueState->d_handle_p->queue()
->stats()
->onEvent<mqbstat::QueueStatsDomain::EventType::e_NACK>(
1);
}
}
// Throttle error log if this is a 'failed Ack': note that we log at
// INFO level in order not to overwhelm the dashboard, if a queue is
// full, every post will nack, which could be a lot.
BALL_LOGTHROTTLE_INFO(1, 5 * bdlt::TimeUnitRatio::k_NS_PER_S)
<< description() << ": failed Ack " << "[status: " << status
<< ", source: '" << source << "'"
<< ", correlationId: " << correlationId
<< ", GUID: " << messageGUID << ", queue: '" << uri << "' "
<< "(id: " << queueId << ")]";
}
// Always print at trace level
BALL_LOG_TRACE << description() << ": sending Ack "
<< "[status: " << status << ", source: '" << source << "'"
<< ", correlationId: " << correlationId
<< ", GUID: " << messageGUID << ", queue: '" << uri
<< "' (id: " << queueId << ")]";
// Append the ACK to the ackBuilder
bmqt::EventBuilderResult::Enum rc = bmqp::ProtocolUtil::buildEvent(
BuildAckFunctor(d_state.d_ackBuilder,
bmqp::ProtocolUtil::ackResultToCode(status),
correlationId,
messageGUID,
queueId),
BuildAckOverflowFunctor(*this));
if (rc != bmqt::EventBuilderResult::e_SUCCESS) {
BALL_LOG_ERROR << "Failed to append ACK [rc: " << rc << ", source: '"
<< source << "'"
<< ", correlationId: " << correlationId
<< ", GUID: " << messageGUID << ", queue: '" << uri
<< "' (id: " << queueId << ")]";
}
if (d_state.d_ackBuilder.eventSize() >= k_NAGLE_PACKET_SIZE) {
flush();
}
mqbstat::QueueStatsClient* queueStats = 0;
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(queueState == 0)) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// Invalid/unknown queue
queueStats = invalidQueueStats();
}
else {
// Known queue (or subStream of the queue)
StreamsMap::const_iterator subQueueCiter =
queueState->d_subQueueInfosMap.findBySubIdSafe(
bmqp::QueueId::k_DEFAULT_SUBQUEUE_ID);
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(
subQueueCiter == queueState->d_subQueueInfosMap.end())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
// Invalid/unknown subStream
// Producer has closed the queue before receiving ACKs
queueStats = invalidQueueStats();
}
else {
queueStats = subQueueCiter->value().d_stats.get();
}
}
queueStats->onEvent(mqbstat::QueueStatsClient::EventType::e_ACK, 1);
}
void ClientSession::tearDownImpl(bslmt::Semaphore* semaphore,
const bsl::shared_ptr<void>& session,
bool isBrokerShutdown)
{
// executed by the *CLIENT* dispatcher thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
BALL_LOG_INFO << description() << ": tearDownImpl";
bdlb::ScopeExitAny guard(bdlf::BindUtil::bind(
static_cast<void (bslmt::Semaphore::*)()>(&bslmt::Semaphore::post),
semaphore));
if (d_operationState == e_DEAD) {
// Cannot do any work anymore
return; // RETURN
}
// If stop request handling is in progress cancel checking for the
// unconfirmed messages.
if (d_periodicUnconfirmedCheckHandler) {
d_scheduler_p->cancelEventAndWait(d_periodicUnconfirmedCheckHandler);
}
d_self.invalidate();
// Invalidating this CS in CS thread for the sake of synchronization
// with `finishCheckUnconfirmed / finishCheckUnconfirmedDispatched` and
// `checkUnconfirmed` / `checkUnconfirmedDispatched`. Otherwise, they
// need `weakMemFn`.
// Stop the graceful shutdown chain (no-op if not started)
d_shutdownChain.stop();
d_shutdownChain.removeAll();
// Drop all *applicable* queue handles, ie, all those handles for which
// either a final close-queue request has not been received, or those
// handles which haven't been dropped yet (eg, via
// 'processDisconnectAllQueues'). Use 'drop' instead of 'release' because
// client is going down, we don't need the QueueEngine to call us back to
// notify the handle can be deleted because once this 'tearDownImpl' method
// returns, this entire object is destroyed. We also don't need to send a
// close queue response since this release is not initiated by the client,
// but by the broker upon client's disconnect. Finally, we need to use
// 'drop' to prevent a double release: if the client sent a closeQueue
// request and immediately after the channel went down (i.e., the
// closeQueue request is in process in the queue thread, so the handle is
// still active at the time tearDown is processed).
const bool hasLostTheClient = (!isBrokerShutdown && !isProxy());
// Set up the 'd_operationState' to indicate that the channel is dying and
// we should not use it anymore trying to send any messages and should also
// stop enqueuing 'callbacks' to the client dispatcher thread ...
const bool doDeconfigure = d_operationState == e_RUNNING;
int numHandlesDropped = dropAllQueueHandles(doDeconfigure,
hasLostTheClient);
BALL_LOG_INFO << description() << ": Dropped " << numHandlesDropped
<< " queue handles.";
// Set up the 'd_operationState' to indicate that the channel is dying and
// we should not use it anymore trying to send any messages and should also
// stop enqueuing 'callbacks' to the client dispatcher thread ...
d_operationState = e_DEAD;
// Invalidating 'd_queueSessionManager' _after_ calling 'clearClient',
// otherwise handle can get destructed because of
// 'QueueSessionManager::onHandleReleased' early exit.
d_queueSessionManager.tearDown();
// Now that we enqueued a 'drop' for all applicable queue handles, we need
// to synchronize on all queues, to make sure this drop event has been
// processed. We do so by enqueuing an event to all queues dispatchers
// with the 'tearDownAllQueuesDone' finalize callback having the 'handle'
// bound to it (so that the session is not yet destroyed).
dispatcher()->execute(
mqbi::Dispatcher::ProcessorFunctor(), // empty
mqbi::DispatcherClientType::e_QUEUE,
bdlf::BindUtil::bind(&ClientSession::tearDownAllQueuesDone,
this,
session));
}
void ClientSession::tearDownAllQueuesDone(const bsl::shared_ptr<void>& session)
{
// executed by ONE of the *QUEUE* dispatcher threads
// At this point, all queues dispatcher have been drained, we now need to
// synchronize with the client's dispatcher thread: an event emanating from
// a queue may have enqueued something to this client's events queue, so we
// need to keep the session alive until all such events have been
// processed. Enqueue an event to the dispatcher associated to this
// client, binding to it the 'handle' in the finalize callback. Only after
// this event has been processed will we have the guarantee that nothing
// else references the session and we can therefore let it being destroyed,
// by having the 'handle' go out of scope. This dispatcher event must be
// of type 'e_DISPATCHER' to make sure this client will not be added to the
// dispatcher's flush list, since it is being destroyed.
dispatcher()->execute(
bdlf::BindUtil::bind(&sessionHolderDummy, d_shutdownCallback, session),
this,
mqbi::DispatcherEventType::e_DISPATCHER);
}
void ClientSession::onHandleConfigured(
const bmqp_ctrlmsg::Status& status,
const bmqp_ctrlmsg::StreamParameters& streamParameters,
const bmqp_ctrlmsg::ControlMessage& streamParamsCtrlMsg)
{
// executed by the *ANY* thread
dispatcher()->execute(
bdlf::BindUtil::bind(&ClientSession::onHandleConfiguredDispatched,
this,
status,
streamParameters,
streamParamsCtrlMsg),
this);
}
void ClientSession::onHandleConfiguredDispatched(
const bmqp_ctrlmsg::Status& status,
const bmqp_ctrlmsg::StreamParameters& streamParameters,
const bmqp_ctrlmsg::ControlMessage& streamParamsCtrlMsg)
{
// executed by the *CLIENT* dispatcher thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
const unsigned int qId =
streamParamsCtrlMsg.choice().isConfigureQueueStreamValue()
? streamParamsCtrlMsg.choice().configureQueueStream().qId()
: streamParamsCtrlMsg.choice().configureStream().qId();
ClientSessionState::QueueStateMap::iterator queueStateIter =
d_queueSessionManager.queues().find(qId);
d_currentOpDescription << "Configure queue [qId=" << qId;
if (queueStateIter != d_queueSessionManager.queues().end()) {
if (queueStateIter->second.d_handle_p) {
d_currentOpDescription
<< ", uri='"
<< queueStateIter->second.d_handle_p->queue()->uri() << "'";
}
}
d_currentOpDescription << "]";
if (isDisconnected()) {
// The client is disconnected or the channel is down
logOperationTime(d_currentOpDescription);
return; // RETURN
}
// Send success/error response to client
bdlma::LocalSequentialAllocator<2048> localAlloc(d_state.d_allocator_p);
bmqp_ctrlmsg::ControlMessage response(&localAlloc);
response.rId() = streamParamsCtrlMsg.rId().value();
if (status.category() != bmqp_ctrlmsg::StatusCategory::E_SUCCESS) {
// Failure ...
response.choice().makeStatus(status);
BALL_LOG_ERROR << "#CLIENT_CONFIGUREQUEUE_FAILURE " << description()
<< ": Error while configuring queue: [reason: '"
<< status << "', request: " << streamParamsCtrlMsg
<< "]";
}
else {
if (streamParamsCtrlMsg.choice().isConfigureQueueStreamValue()) {
bmqp_ctrlmsg::ConfigureQueueStream& configureQueueStream =
response.choice().makeConfigureQueueStreamResponse().request();
configureQueueStream.qId() = qId;
bmqp::ProtocolUtil::convert(
&configureQueueStream.streamParameters(),
streamParameters,
streamParamsCtrlMsg.choice()
.configureQueueStream()
.streamParameters()
.subIdInfo());
}
else {
bmqp_ctrlmsg::ConfigureStream& configureStream =
response.choice().makeConfigureStreamResponse().request();
configureStream.qId() = qId;
configureStream.streamParameters() = streamParameters;
}
if (queueStateIter == d_queueSessionManager.queues().end()) {
// Failure to find queue
BALL_LOG_WARN
<< "#CLIENT_UNKNOWN_QUEUE " << description()
<< ": Response to configure a queue with unknown Id (" << qId
<< ")";
}
else {
queueStateIter->second.d_subQueueInfosMap.addSubscriptions(
streamParameters);
}
}
d_state.d_schemaEventBuilder.reset();
int rc = d_state.d_schemaEventBuilder.setMessage(
response,
bmqp::EventType::e_CONTROL);
if (rc != 0) {
BALL_LOG_WARN << "#CLIENT_SEND_FAILURE " << description()
<< ": Unable to send configureQueue response [reason: "
<< "ENCODING_FAILED, rc: " << rc
<< ", request: " << streamParamsCtrlMsg
<< "]: " << response;
logOperationTime(d_currentOpDescription);
return; // RETURN
}
BALL_LOG_INFO << description()
<< ": Sending configureQueue response: " << response
<< " for request: " << streamParamsCtrlMsg;
// Send the response
sendPacketDispatched(d_state.d_schemaEventBuilder.blob(), true);
logOperationTime(d_currentOpDescription);
}
void ClientSession::initiateShutdownDispatched(
const ShutdownCb& callback,
const bsls::TimeInterval& timeout,
bool supportShutdownV2)
{
// executed by the *CLIENT* dispatcher thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
BSLS_ASSERT_SAFE(callback);
BALL_LOG_INFO << description()
<< ": initiateShutdownDispatched. Timeout: " << timeout;
if (d_operationState == e_DEAD) {
// The client is disconnected. No need to wait for tearDown.
callback();
return; // RETURN
}
if (d_operationState == e_SHUTTING_DOWN) {
// More than one cluster calls 'initiateShutdown'?
callback();
return; // RETURN
}
if (d_operationState == e_SHUTTING_DOWN_V2) {
// More than one cluster calls 'initiateShutdown'?
callback();
return; // RETURN
}
flush(); // Flush any pending messages
// 'tearDown' should invoke the 'callback'
d_shutdownCallback = callback;
if (d_operationState == e_DISCONNECTING) {
// Not teared down yet. No need to wait for unconfirmed messages.
// Wait for tearDown.
closeChannel();
return; // RETURN
}
if (supportShutdownV2) {
d_operationState = e_SHUTTING_DOWN_V2;
d_queueSessionManager.shutDown();
callback();
}
else {
// After de-configuring (below), wait for unconfirmed messages.
// Once the wait for unconfirmed is over, close the channel
ShutdownContextSp context;
context.createInplace(
d_state.d_allocator_p,
bdlf::BindUtil::bind(&ClientSession::closeChannel, this),
timeout);
deconfigureAndWait(context);
}
}
void ClientSession::deconfigureAndWait(ShutdownContextSp& context)
{
// executed by the *CLIENT* dispatcher thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
BSLS_ASSERT_SAFE(context);
// Use the same 'e_SHUTTING_DOWN' state for both shutting down and
// StopRequest processing.
d_operationState = e_SHUTTING_DOWN;
// Fill the first link with handle deconfigure operations
bmqu::OperationChainLink link(d_shutdownChain.allocator());
for (QueueStateMapIter it = d_queueSessionManager.queues().begin();
it != d_queueSessionManager.queues().end();
++it) {
if (!it->second.d_hasReceivedFinalCloseQueue) {
link.insert(
bdlf::BindUtil::bind(&mqbi::QueueHandle::deconfigureAll,
it->second.d_handle_p,
bdlf::PlaceHolders::_1));
}
}
// No-op if the link is empty
d_shutdownChain.append(&link);
d_shutdownChain.appendInplace(
bdlf::BindUtil::bind(&ClientSession::checkUnconfirmed,
this,
context,
bdlf::PlaceHolders::_1));
d_shutdownChain.start();
}
void ClientSession::invalidateDispatched()
{
// PRECONDITIONS
BSLS_ASSERT_SAFE(dispatcher()->inDispatcherThread(this));
if (d_operationState == e_DEAD) {
return; // RETURN
}
d_self.invalidate();
d_operationState = e_DEAD;
}