-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathmqbc_storageutil.cpp
3974 lines (3371 loc) · 157 KB
/
mqbc_storageutil.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 2021-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.
// mqbc_storageutil.cpp -*-C++-*-
#include <mqbc_storageutil.h>
#include <mqbscm_version.h>
// MQB
#include <mqbi_queueengine.h>
#include <mqbnet_cluster.h>
#include <mqbs_datastore.h>
#include <mqbs_filestoreprotocol.h>
#include <mqbs_filestoreutil.h>
#include <mqbs_filesystemutil.h>
#include <mqbs_storagecollectionutil.h>
#include <mqbstat_clusterstats.h>
#include <mqbu_exit.h>
// BMQ
#include <bmqp_protocolutil.h>
#include <bmqp_recoverymessageiterator.h>
#include <bmqt_messageguid.h>
#include <bmqtsk_alarmlog.h>
#include <bmqu_memoutstream.h>
#include <bmqu_printutil.h>
#include <bmqu_throttledaction.h>
// BDE
#include <bdlb_print.h>
#include <bdlb_scopeexit.h>
#include <bdlb_stringrefutil.h>
#include <bdlf_bind.h>
#include <bdlf_memfn.h>
#include <bdlma_localsequentialallocator.h>
#include <bdls_filesystemutil.h>
#include <bdlt_currenttime.h>
#include <bdlt_epochutil.h>
#include <bsl_unordered_map.h>
#include <bslma_allocator.h>
#include <bslmt_lockguard.h>
#include <bslmt_mutex.h>
#include <bsls_annotation.h>
#include <bsls_types.h>
namespace BloombergLP {
namespace mqbc {
namespace {
/// Post on the optionally specified `semaphore`.
void optionalSemaphorePost(bslmt::Semaphore* semaphore)
{
if (semaphore) {
semaphore->post();
}
}
} // close unnamed namespace
// ------------------
// struct StorageUtil
// ------------------
// PRIVATE FUNCTIONS
bool StorageUtil::loadDifference(mqbi::Storage::AppInfos* result,
const mqbi::Storage::AppInfos& baseSet,
const mqbi::Storage::AppInfos& subtractionSet,
bool findConflicts)
{
bool noConflicts = true;
for (mqbi::Storage::AppInfos::const_iterator cit = baseSet.cbegin();
cit != baseSet.cend();
++cit) {
mqbi::Storage::AppInfos::const_iterator match = subtractionSet.find(
cit->first);
if (subtractionSet.end() == match) {
result->insert(bsl::make_pair(cit->first, cit->second));
}
else if (findConflicts && match->second != cit->second) {
BALL_LOG_ERROR << "appId [" << cit->first
<< "] has conflicting appKeys [" << cit->second
<< " vs " << match->second << "]. Ignoring ["
<< cit->second << "]";
noConflicts = false;
}
}
return noConflicts;
}
void StorageUtil::loadDifference(
bsl::unordered_set<bsl::string>* result,
const bsl::unordered_set<bsl::string>& baseSet,
const bsl::unordered_set<bsl::string>& subtractionSet)
{
for (bsl::unordered_set<bsl::string>::const_iterator cit =
baseSet.cbegin();
cit != baseSet.cend();
++cit) {
if (subtractionSet.end() == subtractionSet.find(*cit)) {
result->emplace(*cit);
}
}
}
bool StorageUtil::loadAddedAndRemovedEntries(
mqbi::Storage::AppInfos* addedEntries,
mqbi::Storage::AppInfos* removedEntries,
const mqbi::Storage::AppInfos& existingEntries,
const mqbi::Storage::AppInfos& newEntries)
{
// PRECONDITIONS
BSLS_ASSERT_SAFE(addedEntries);
BSLS_ASSERT_SAFE(removedEntries);
// Find newly added entries.
bool noConflicts =
loadDifference(addedEntries, newEntries, existingEntries, true);
// Find removed entries.
loadDifference(removedEntries, existingEntries, newEntries, false);
return noConflicts;
}
void StorageUtil::loadAddedAndRemovedEntries(
bsl::unordered_set<bsl::string>* addedEntries,
bsl::unordered_set<bsl::string>* removedEntries,
const bsl::unordered_set<bsl::string>& existingEntries,
const bsl::unordered_set<bsl::string>& newEntries)
{
// PRECONDITIONS
BSLS_ASSERT_SAFE(addedEntries);
BSLS_ASSERT_SAFE(removedEntries);
// Find newly added entries.
loadDifference(addedEntries, newEntries, existingEntries);
// Find removed entries.
loadDifference(removedEntries, existingEntries, newEntries);
}
bool StorageUtil::loadUpdatedAppInfos(AppInfos* addedAppInfos,
AppInfos* removedAppInfos,
const AppInfos& existingAppInfos,
const AppInfos& newAppInfos)
{
// executed by the *QUEUE_DISPATCHER* thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(addedAppInfos);
BSLS_ASSERT_SAFE(removedAppInfos);
BSLS_ASSERT_SAFE(!newAppInfos.empty());
// This function is invoked by 'StorageManager::registerQueue' if the queue
// with specified 'storage' is in fanout mode, in order to add or remove
// any appIds which are not part of the currently configured appIds.
// Here's the scenario: A broker is up and running and has a fanout queue
// with 3 appIds: A, B and C. Clients and broker shut down. A new domain
// config for the queue is deployed which removes appIds B and C, and adds
// appId D. So now, the effective appIds are A and D. Now broker is
// started, it recovers appIds A, B and C and creates 3 virtual storages,
// one for each appId. Then queue is opened and eventually,
// 'registerQueue' is invoked. At this time, broker needs to remove appIds
// B and C, and add D. This routine takes care of that, by retrieving the
// list of newly added and removed appIds, and then invoking 'updateQueue'
// in the appropriate thread.
loadAddedAndRemovedEntries(addedAppInfos,
removedAppInfos,
existingAppInfos,
newAppInfos);
// TEMPORARY: if duplicate AppKey values exist for the same AppId, ignore
// the one in 'newAppInfos'.
if (addedAppInfos->empty() && removedAppInfos->empty()) {
// No appIds to add or remove.
return false; // RETURN
}
return true;
}
void StorageUtil::registerQueueDispatched(
BSLS_ANNOTATION_UNUSED const mqbi::Dispatcher::ProcessorHandle& processor,
mqbs::FileStore* fs,
mqbs::ReplicatedStorage* storage,
const bsl::string& clusterDescription,
int partitionId,
const AppInfos& appIdKeyPairs)
{
// executed by *QUEUE_DISPATCHER* thread with the specified 'partitionId'
// PRECONDITIONS
BSLS_ASSERT_SAFE(fs->inDispatcherThread());
BSLS_ASSERT_SAFE(fs);
BSLS_ASSERT_SAFE(storage);
BSLS_ASSERT_SAFE(0 <= partitionId);
// Irrespective of the type of 'storage' (in-memory vs file-backed), the
// appIds/VirtualStorages which were supposed to be added or removed
// to/from 'storage' have already been added/removed (ie, virtual storages
// have been created/removed).
// Register storage with the partition.
bsls::Types::Uint64 timestamp = bdlt::EpochUtil::convertToTimeT64(
bdlt::CurrentTime::utc());
mqbs::DataStoreRecordHandle handle;
// TODO_CSL Do not write this record when we logically delete the QLIST
// file
int rc = fs->writeQueueCreationRecord(&handle,
storage->queueUri(),
storage->queueKey(),
appIdKeyPairs,
timestamp,
true); // Is new storage?
if (0 != rc) {
BMQTSK_ALARMLOG_ALARM("FILE_IO")
<< clusterDescription << ": Partition [" << partitionId
<< "] failed to write QueueCreationRecord for queue ["
<< storage->queueUri() << "] queueKey [" << storage->queueKey()
<< "], rc: " << rc << BMQTSK_ALARMLOG_END;
return; // RETURN
}
storage->addQueueOpRecordHandle(handle);
fs->registerStorage(storage);
// Flush the partition. This routine ('registerQueue[Dispatched]') is
// invoked only at the primary (we can assert that using
// 'd_partitionInfoVec'), when a LocalQueue is being created. If this
// storage belongs to the first instance of LocalQueue mapped to this
// partition, we want to make sure that queue creation record written to
// the partition above is sent to the replicas as soon as possible.
fs->flushStorage();
BALL_LOG_INFO << clusterDescription << ": Partition [" << partitionId
<< "] registered [" << storage->queueUri() << "], queueKey ["
<< storage->queueKey() << "] with the storage as primary.";
}
void StorageUtil::updateQueuePrimaryDispatched(
BSLS_ANNOTATION_UNUSED const mqbi::Dispatcher::ProcessorHandle& processor,
mqbs::ReplicatedStorage* storage,
bslmt::Mutex* storagesLock,
mqbs::FileStore* fs,
const bsl::string& clusterDescription,
int partitionId,
const AppInfos& appIdKeyPairs,
bool isFanout)
{
// executed by *QUEUE_DISPATCHER* thread with the specified 'partitionId'
// PRECONDITIONS
BSLS_ASSERT_SAFE(0 <= partitionId);
BSLS_ASSERT_SAFE(fs);
BSLS_ASSERT_SAFE(fs->inDispatcherThread());
BSLS_ASSERT_SAFE(storage);
bslmt::LockGuard<bslmt::Mutex> guard(storagesLock); // LOCK
AppInfos existingAppInfos;
storage->loadVirtualStorageDetails(&existingAppInfos);
bmqu::Printer<AppInfos> printer2(&existingAppInfos);
BALL_LOG_INFO << clusterDescription << " Partition [" << partitionId
<< "]: Existing queue '" << storage->queueUri()
<< "', queueKey: '" << storage->queueKey() << "' "
<< printer2 << " in the storage.";
AppInfos addedAppInfos, removedAppInfos;
bool hasUpdate = loadUpdatedAppInfos(&addedAppInfos,
&removedAppInfos,
existingAppInfos,
appIdKeyPairs);
if (!hasUpdate) {
// No update needed for AppId/Key pairs.
return; // RETURN
}
// Simply forward to 'updateQueuePrimaryRaw'.
updateQueuePrimaryRaw(storage,
fs,
clusterDescription,
partitionId,
addedAppInfos,
removedAppInfos,
isFanout);
}
int StorageUtil::updateQueuePrimaryRaw(mqbs::ReplicatedStorage* storage,
mqbs::FileStore* fs,
const bsl::string& clusterDescription,
int partitionId,
const AppInfos& addedIdKeyPairs,
const AppInfos& removedIdKeyPairs,
bool isFanout)
{
// executed by *QUEUE_DISPATCHER* thread with the specified 'partitionId'
// PRECONDITIONS
BSLS_ASSERT_SAFE(0 <= partitionId);
BSLS_ASSERT_SAFE(fs);
BSLS_ASSERT_SAFE(fs->inDispatcherThread());
BSLS_ASSERT_SAFE(storage);
int rc = 0;
bsls::Types::Uint64 timestamp = bdlt::EpochUtil::convertToTimeT64(
bdlt::CurrentTime::utc());
if (!addedIdKeyPairs.empty()) {
// Write QueueCreation record to data store for added appIds.
//
// TODO_CSL Do not write this record when we logically delete the QLIST
// file
mqbs::DataStoreRecordHandle handle;
rc = fs->writeQueueCreationRecord(&handle,
storage->queueUri(),
storage->queueKey(),
addedIdKeyPairs,
timestamp,
false); // is new queue?
if (0 != rc) {
BMQTSK_ALARMLOG_ALARM("FILE_IO")
<< clusterDescription << ": Partition [" << partitionId
<< "] failed to write QueueCreationRecord for new appIds "
<< "for queue [" << storage->queueUri() << "] queueKey ["
<< storage->queueKey() << "], rc: " << rc
<< BMQTSK_ALARMLOG_END;
return rc; // RETURN
}
storage->addQueueOpRecordHandle(handle);
rc = addVirtualStoragesInternal(storage,
addedIdKeyPairs,
clusterDescription,
partitionId,
isFanout);
if (0 != rc) {
return rc; // RETURN
}
BALL_LOG_INFO_BLOCK
{
bmqu::Printer<AppInfos> printer(&addedIdKeyPairs);
BALL_LOG_OUTPUT_STREAM
<< clusterDescription << ": Partition [" << partitionId
<< "] For an already registered queue [" << storage->queueUri()
<< "], queueKey [" << storage->queueKey() << "], added ["
<< addedIdKeyPairs.size() << "] new appId/appKey "
<< "pairs:" << printer;
}
}
if (!removedIdKeyPairs.empty()) {
for (AppInfosCIter cit = removedIdKeyPairs.begin();
cit != removedIdKeyPairs.end();
++cit) {
rc = removeVirtualStorageInternal(storage,
cit->second,
partitionId,
true); // asPrimary
if (0 != rc) {
BALL_LOG_ERROR
<< clusterDescription << " Partition [" << partitionId
<< "]: Failed to remove virtual storage for " << "appKey ["
<< cit->second << "], appId [" << cit->first
<< "], for queue [" << storage->queueUri()
<< "], queueKey [" << storage->queueKey()
<< "], rc: " << rc << ".";
return rc; // RETURN
}
}
BALL_LOG_INFO_BLOCK
{
bmqu::Printer<AppInfos> printer(&removedIdKeyPairs);
BALL_LOG_OUTPUT_STREAM
<< clusterDescription << ": Partition [" << partitionId
<< "] For an already registered queue [" << storage->queueUri()
<< "], queueKey [" << storage->queueKey() << "], removed ["
<< removedIdKeyPairs.size() << "] existing appId/appKey "
<< "pairs:" << printer;
}
}
// Flush the partition for records written above to reach replicas right
// away.
fs->flushStorage();
bmqu::Printer<AppInfos> printer1(&addedIdKeyPairs);
bmqu::Printer<AppInfos> printer2(&removedIdKeyPairs);
BALL_LOG_INFO << clusterDescription << ": Partition [" << partitionId
<< "] updated [" << storage->queueUri() << "], queueKey ["
<< storage->queueKey() << "] with the storage as primary: "
<< "addedIdKeyPairs:" << printer1
<< ", removedIdKeyPairs:" << printer2;
return 0;
}
int StorageUtil::addVirtualStoragesInternal(
mqbs::ReplicatedStorage* storage,
const AppInfos& appIdKeyPairs,
const bsl::string& clusterDescription,
int partitionId,
bool isFanout)
{
// executed by *QUEUE_DISPATCHER* thread with the specified 'partitionId'
// PRECONDITIONS
BSLS_ASSERT_SAFE(0 <= partitionId);
BSLS_ASSERT_SAFE(storage);
enum {
rc_SUCCESS = 0,
rc_APP_KEY_COLLISION = -1,
rc_VIRTUAL_STORAGE_CREATION_FAILURE = -2
};
int rc = -1;
bmqu::MemOutStream errorDesc;
if (isFanout) {
// Register appKeys with with the underlying physical 'storage'.
for (AppInfosCIter cit = appIdKeyPairs.begin();
cit != appIdKeyPairs.end();
++cit) {
if (0 != (rc = storage->addVirtualStorage(errorDesc,
cit->first,
cit->second))) {
BALL_LOG_WARN
<< clusterDescription << " Partition [" << partitionId
<< "]: " << "Failed to add virtual storage for AppKey ["
<< cit->second << "], appId [" << cit->first
<< "], for queue [" << storage->queueUri()
<< "], queueKey [" << storage->queueKey() << "]. Reason: ["
<< errorDesc.str() << "], rc: " << rc << ".";
return rc_VIRTUAL_STORAGE_CREATION_FAILURE; // RETURN
}
}
}
else {
rc = storage->addVirtualStorage(errorDesc,
bmqp::ProtocolUtil::k_DEFAULT_APP_ID,
mqbi::QueueEngine::k_DEFAULT_APP_KEY);
// Unlike fanout queue above, we don't care about the returned value
// for priority queue, since there is only one appId (default) which
// could be added more than once in the startup sequence. Its better
// to ignore the return value instead of raising a useless warning.
}
return rc_SUCCESS;
}
int StorageUtil::removeVirtualStorageInternal(mqbs::ReplicatedStorage* storage,
const mqbu::StorageKey& appKey,
int partitionId,
bool asPrimary)
{
// executed by *QUEUE_DISPATCHER* thread with the specified 'partitionId'
// PRECONDITIONS
BSLS_ASSERT_SAFE(0 <= partitionId);
BSLS_ASSERT_SAFE(storage);
BSLS_ASSERT_SAFE(!appKey.isNull());
// We should never have to remove a default appKey (for non-fanout queues)
BSLS_ASSERT_SAFE(appKey != mqbi::QueueEngine::k_DEFAULT_APP_KEY);
enum { rc_SUCCESS = 0, rc_VIRTUAL_STORAGE_DOES_NOT_EXIST = -1 };
bool existed = storage->removeVirtualStorage(appKey, asPrimary);
if (!existed) {
return rc_VIRTUAL_STORAGE_DOES_NOT_EXIST; // RETURN
}
return rc_SUCCESS;
}
void StorageUtil::getStoragesDispatched(StorageLists* storageLists,
bslmt::Latch* latch,
const FileStores& fileStores,
int partitionId,
const StorageFilters& filters)
{
// executed by *QUEUE_DISPATCHER* thread with the specified 'partitionId'
// PRECONDITIONS
BSLS_ASSERT_SAFE(storageLists);
BSLS_ASSERT_SAFE(latch);
BSLS_ASSERT_SAFE(0 <= partitionId);
BSLS_ASSERT_SAFE(fileStores.size() >
static_cast<unsigned int>(partitionId));
BSLS_ASSERT_SAFE(storageLists->size() == fileStores.size());
const mqbs::FileStore& fs =
*fileStores[static_cast<unsigned int>(partitionId)];
BSLS_ASSERT_SAFE(fs.inDispatcherThread());
fs.getStorages(&((*storageLists)[partitionId]), filters);
latch->arrive();
}
void StorageUtil::loadStorages(bsl::vector<mqbcmd::StorageQueueInfo>* storages,
const bsl::string& domainName,
const FileStores& fileStores)
{
// executed by cluster *DISPATCHER* thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(storages);
StorageLists storageLists;
StorageFilters filters;
filters.push_back(
mqbs::StorageCollectionUtilFilterFactory::byDomain(domainName));
filters.push_back(
mqbs::StorageCollectionUtilFilterFactory::byMessageCount(1));
storageLists.resize(fileStores.size());
executeForEachPartitions(
bdlf::BindUtil::bind(&getStoragesDispatched,
&storageLists,
bdlf::PlaceHolders::_2, // latch
fileStores,
bdlf::PlaceHolders::_1, // partitionId
filters),
fileStores);
// Merge vector of vectors into a single vector
StorageList storageList;
for (StorageListsConstIter cit = storageLists.cbegin();
cit != storageLists.cend();
++cit) {
bsl::copy(cit->cbegin(), cit->cend(), bsl::back_inserter(storageList));
}
mqbs::StorageCollectionUtil::sortStorages(
&storageList,
mqbs::StorageCollectionUtilSortMetric::e_BYTE_COUNT);
storages->reserve(storageList.size());
for (StorageList::const_iterator cit = storageList.begin();
cit != storageList.end();
++cit) {
storages->resize(storages->size() + 1);
mqbcmd::StorageQueueInfo& storage = storages->back();
bmqu::MemOutStream os;
os << (*cit)->queueKey();
storage.queueKey() = os.str();
storage.partitionId() = (*cit)->partitionId();
storage.numMessages() = (*cit)->numMessages(
mqbu::StorageKey::k_NULL_KEY);
storage.numBytes() = (*cit)->numBytes(mqbu::StorageKey::k_NULL_KEY);
storage.queueUri() = (*cit)->queueUri().asString();
storage.isPersistent() = (*cit)->isPersistent();
}
}
void StorageUtil::loadPartitionStorageSummary(
mqbcmd::StorageResult* result,
FileStores* fileStores,
int partitionId,
const bslstl::StringRef& partitionLocation)
{
// executed by cluster *DISPATCHER* thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(result);
BSLS_ASSERT_SAFE(fileStores);
mqbcmd::ClusterStorageSummary& summary =
result->makeClusterStorageSummary();
summary.clusterFileStoreLocation() = partitionLocation;
summary.fileStores().resize(fileStores->size());
bslmt::Latch latch(1);
fileStores->at(partitionId)
->execute(bdlf::BindUtil::bind(&loadStorageSummaryDispatched,
&summary,
&latch,
partitionId,
*fileStores));
// Wait
latch.wait();
// As we loaded information about only one partition (with 'partitionId'),
// the 'summary.fileStores()' in general contains incomplete information
// about all the partitions. So we make sure that only meaningful
// information will stay in the end.
bsl::swap(summary.fileStores()[0], summary.fileStores()[partitionId]);
summary.fileStores().resize(1);
}
void StorageUtil::loadStorageSummary(mqbcmd::StorageResult* result,
const FileStores& fileStores,
const bslstl::StringRef location)
{
// executed by cluster *DISPATCHER* thread
// This command needs to forward the 'SUMMARY' command to all partitions,
// wait for all of them to finish executing it, and then aggregate the
// output.
mqbcmd::ClusterStorageSummary& summary =
result->makeClusterStorageSummary();
summary.clusterFileStoreLocation() = location;
summary.fileStores().resize(fileStores.size());
executeForEachPartitions(
bdlf::BindUtil::bind(&loadStorageSummaryDispatched,
&summary,
bdlf::PlaceHolders::_2, // latch
bdlf::PlaceHolders::_1, // partitionId
fileStores),
fileStores);
}
void StorageUtil::loadStorageSummaryDispatched(
mqbcmd::ClusterStorageSummary* summary,
bslmt::Latch* latch,
int partitionId,
const FileStores& fileStores)
{
// executed by *QUEUE_DISPATCHER* thread with the specified 'partitionId'
// PRECONDITIONS
BSLS_ASSERT_SAFE(summary);
BSLS_ASSERT_SAFE(latch);
BSLS_ASSERT_SAFE(0 <= partitionId);
BSLS_ASSERT_SAFE(fileStores.size() >
static_cast<unsigned int>(partitionId));
BSLS_ASSERT_SAFE(fileStores[partitionId]->inDispatcherThread());
fileStores[partitionId]->loadSummary(&summary->fileStores()[partitionId]);
latch->arrive();
}
void StorageUtil::executeForEachPartitions(const PerPartitionFunctor& job,
const FileStores& fileStores)
{
// executed by cluster *DISPATCHER* thread
bslmt::Latch latch(fileStores.size());
for (unsigned int i = 0; i < fileStores.size(); ++i) {
fileStores[i]->execute(bdlf::BindUtil::bind(job, i, &latch));
}
// Wait
latch.wait();
}
void StorageUtil::executeForValidPartitions(const PerPartitionFunctor& job,
const FileStores& fileStores)
{
// executed by cluster *DISPATCHER* thread
bsl::vector<int> validPartitionIds;
validPartitionIds.reserve(fileStores.size());
for (unsigned int i = 0; i < fileStores.size(); ++i) {
FileStoreSp fileStore = fileStores[i];
if (fileStore->primaryNode() && fileStore->primaryNode()->nodeId() ==
fileStore->config().nodeId()) {
validPartitionIds.push_back(i);
}
}
bslmt::Latch latch(validPartitionIds.size());
BALL_LOG_INFO << "StorageUtil::executeForValidPartitions for "
<< fileStores.size() << " partitions!";
for (unsigned int i = 0; i < validPartitionIds.size(); ++i) {
int partitionId = validPartitionIds[i];
fileStores[partitionId]->execute(
bdlf::BindUtil::bind(job, partitionId, &latch));
}
// Wait
latch.wait();
}
int StorageUtil::processReplicationCommand(
mqbcmd::ReplicationResult* replicationResult,
int* replicationFactor,
FileStores* fileStores,
const mqbcmd::ReplicationCommand& command)
{
// executed by cluster *DISPATCHER* thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(replicationResult);
BSLS_ASSERT_SAFE(replicationFactor);
BSLS_ASSERT_SAFE(fileStores);
if (command.isSetTunableValue()) {
const mqbcmd::SetTunable& tunable = command.setTunable();
if (bdlb::StringRefUtil::areEqualCaseless(tunable.name(), "QUORUM")) {
if (!tunable.value().isTheIntegerValue() ||
tunable.value().theInteger() < 0) {
bmqu::MemOutStream output;
output << "The QUORUM tunable must be a non-negative integer, "
"but instead the following was specified: "
<< tunable.value();
replicationResult->makeError();
replicationResult->error().message() = output.str();
return -1; // RETURN
}
mqbcmd::TunableConfirmation& tunableConfirmation =
replicationResult->makeTunableConfirmation();
tunableConfirmation.name() = "Quorum";
tunableConfirmation.oldValue().makeTheInteger(*replicationFactor);
*replicationFactor = tunable.value().theInteger();
for (FileStores::iterator it = fileStores->begin();
it != fileStores->end();
++it) {
(*it)->execute(bdlf::BindUtil::bind(
&mqbs::FileStore::setReplicationFactor,
*it,
tunable.value().theInteger())); // partitionId
}
tunableConfirmation.newValue().makeTheInteger(*replicationFactor);
return 0; // RETURN
}
bmqu::MemOutStream output;
output << "Unknown tunable name '" << tunable.name() << "'";
replicationResult->makeError();
replicationResult->error().message() = output.str();
return -1; // RETURN
}
else if (command.isGetTunableValue()) {
const bsl::string& tunable = command.getTunable().name();
if (bdlb::StringRefUtil::areEqualCaseless(tunable, "QUORUM")) {
mqbcmd::Tunable& tunableObj = replicationResult->makeTunable();
tunableObj.name() = "Quorum";
tunableObj.value().makeTheInteger(*replicationFactor);
return 0; // RETURN
}
bmqu::MemOutStream output;
output << "Unsupported tunable '" << tunable << "': Issue the "
<< "LIST_TUNABLES command for the list of supported tunables.";
replicationResult->makeError();
replicationResult->error().message() = output.str();
return -1; // RETURN
}
else if (command.isListTunablesValue()) {
mqbcmd::Tunables& tunables = replicationResult->makeTunables();
tunables.tunables().resize(tunables.tunables().size() + 1);
mqbcmd::Tunable& tunable = tunables.tunables().back();
tunable.name() = "QUORUM";
tunable.value().makeTheInteger(*replicationFactor);
tunable.description() = "non-negative integer count of the number of"
" peers required to persist each message";
return 0; // RETURN
}
bmqu::MemOutStream output;
output << "Unknown command '" << command << "'";
replicationResult->makeError();
replicationResult->error().message() = output.str();
return -1;
}
// FUNCTIONS
bool StorageUtil::isStorageEmpty(bslmt::Mutex* storagesLock,
const StorageSpMap& storageMap,
const bmqt::Uri& uri,
int partitionId)
{
// executed by the *CLUSTER DISPATCHER* thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(uri.isValid());
BSLS_ASSERT_SAFE(0 <= partitionId);
bslmt::LockGuard<bslmt::Mutex> guard(storagesLock); // LOCK
StorageSpMapConstIter cit = storageMap.find(uri);
if (cit == storageMap.end()) {
return true; // RETURN
}
BSLS_ASSERT_SAFE(cit->second);
return cit->second->isEmpty();
}
void StorageUtil::storageMonitorCb(
bool* lowDiskspaceWarning,
const bsls::AtomicBool* isManagerStarted,
bsls::Types::Uint64 minimumRequiredDiskSpace,
const bslstl::StringRef& clusterDescription,
const mqbcfg::PartitionConfig& partitionConfig)
{
// executed by the scheduler's *DISPATCHER* thread
// PRECONDITIONS
BSLS_ASSERT_SAFE(lowDiskspaceWarning);
BSLS_ASSERT_SAFE(isManagerStarted);
if (!*isManagerStarted) {
return; // RETURN
}
// Delete archived files.
mqbs::FileStoreUtil::deleteArchiveFiles(partitionConfig,
clusterDescription);
// Check available diskspace.
bsls::Types::Int64 availableSpace = 0;
bsls::Types::Int64 totalSpace = 0;
bmqu::MemOutStream errorDesc;
const bsl::string& clusterFileStoreLocation = partitionConfig.location();
int rc = mqbs::FileSystemUtil::loadFileSystemSpace(
errorDesc,
&availableSpace,
&totalSpace,
clusterFileStoreLocation.c_str());
if (0 != rc) {
BMQTSK_ALARMLOG_ALARM("FILE_IO")
<< clusterDescription
<< ": Failed to retrieve available space on file system where "
<< "storage files reside: [" << clusterFileStoreLocation
<< "]. This is not fatal but broker may not be able to handle "
<< "disk-space issues gracefully. Reason: " << errorDesc.str()
<< ", rc: " << rc << "." << BMQTSK_ALARMLOG_END;
return; // RETURN
}
if (static_cast<bsls::Types::Uint64>(availableSpace) <
minimumRequiredDiskSpace) {
*lowDiskspaceWarning = true;
BMQU_THROTTLEDACTION_THROTTLE(
bmqu::ThrottledActionParams(5 * 1000 * 60, 1),
// 1 log per 5min interval
BALL_LOG_INFO << "[INSUFFICIENT_DISK_SPACE] " << clusterDescription
<< ": Not enough disk space on file system ["
<< clusterFileStoreLocation << "]. Required: "
<< bmqu::PrintUtil::prettyBytes(
minimumRequiredDiskSpace)
<< ", available: "
<< bmqu::PrintUtil::prettyBytes(availableSpace););
}
else {
if (*lowDiskspaceWarning) {
// Print trace displaying disk space.
BALL_LOG_INFO << clusterDescription
<< ": Disk space on file system ["
<< clusterFileStoreLocation
<< "] has gone back to normal. " << "Required: "
<< bmqu::PrintUtil::prettyBytes(
minimumRequiredDiskSpace)
<< ", available: "
<< bmqu::PrintUtil::prettyBytes(availableSpace);
}
*lowDiskspaceWarning = false;
}
}
bsl::ostream&
StorageUtil::printRecoveryPhaseOneBanner(bsl::ostream& out,
const bsl::string& clusterDescription,
int partitionId)
{
const int level = 0;
const int spacesPerLevel = 4;
bmqu::MemOutStream header;
header << "RECOVERY PHASE 1: " << clusterDescription << " Partition ["
<< partitionId << "]";
bdlb::Print::newlineAndIndent(out, level + 1, spacesPerLevel);
out << bsl::string(header.length(), '-');
bdlb::Print::newlineAndIndent(out, level + 1, spacesPerLevel);
out << header.str();
bdlb::Print::newlineAndIndent(out, level + 1, spacesPerLevel);
out << bsl::string(header.length(), '-');
return out;
}
int StorageUtil::validatePartitionDirectory(
const mqbcfg::PartitionConfig& config,
bsl::ostream& errorDescription)
{
enum RcEnum {
// Value for the various RC error categories
rc_SUCCESS = 0,
rc_PARTITION_LOCATION_NONEXISTENT = -1
};
// Ensure partition directory exist
const bsl::string& clusterFileStoreLocation = config.location();
if (!bdls::FilesystemUtil::isDirectory(clusterFileStoreLocation, true)) {
errorDescription << "Cluster's partition location ('"
<< clusterFileStoreLocation << "') doesn't exist !";
return rc_PARTITION_LOCATION_NONEXISTENT; // RETURN
}
// Ensure partition's archive directory exist
const bsl::string& clusterFileStoreArchiveLocation =
config.archiveLocation();
if (!bdls::FilesystemUtil::isDirectory(clusterFileStoreArchiveLocation,
true)) {
errorDescription << "Cluster's archive partition location ('"
<< clusterFileStoreArchiveLocation
<< "') doesn't exist !";
return rc_PARTITION_LOCATION_NONEXISTENT; // RETURN
}
return rc_SUCCESS;
}
int StorageUtil::validateDiskSpace(const mqbcfg::PartitionConfig& config,
const mqbc::ClusterData& clusterData,
const bsls::Types::Uint64& minDiskSpace)
{
// executed by the *CLUSTER DISPATCHER* thread
enum RcEnum {
// Value for the various RC error categories
rc_SUCCESS = 0,
rc_NOT_ENOUGH_DISK_SPACE = -1
};
// Print file-system names for cluster storage location.
const bsl::string& clusterFileStoreLocation = config.location();
bsl::string fsname;
mqbs::FileSystemUtil::loadFileSystemName(&fsname,
clusterFileStoreLocation.c_str());
BALL_LOG_INFO << clusterData.identity().description()
<< ": file system type for cluster's storage location ["
<< clusterFileStoreLocation << "] is [" << fsname << "].";
// Raise low disk space warning, if applicable.
bsls::Types::Int64 availableSpace = 0;
bsls::Types::Int64 totalSpace = 0;
bmqu::MemOutStream errorDesc;
int rc = mqbs::FileSystemUtil::loadFileSystemSpace(
errorDesc,
&availableSpace,
&totalSpace,
clusterFileStoreLocation.c_str());
if (0 != rc) {
BALL_LOG_WARN << "Failed to retrieve total and available space on "
<< "file system where storage files for cluster ["
<< clusterData.identity().name() << "] reside: ["
<< clusterFileStoreLocation << "], rc: " << rc
<< ", reason: " << errorDesc.str()
<< ". This is not a fatal issue but broker may not be "
<< "able to handle disk-space issues gracefully.";
}
else {
BALL_LOG_INFO << clusterData.identity().description()
<< ": file system for cluster's storage location ["
<< clusterFileStoreLocation << "] has total space: "
<< bmqu::PrintUtil::prettyBytes(totalSpace)
<< ", and available space: "
<< bmqu::PrintUtil::prettyBytes(availableSpace) << ".";