-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
DatabaseShardImp.cpp
2253 lines (1903 loc) · 66.3 KB
/
DatabaseShardImp.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
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2017 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/app/ledger/InboundLedgers.h>
#include <ripple/app/ledger/LedgerMaster.h>
#include <ripple/app/misc/NetworkOPs.h>
#include <ripple/app/rdb/backend/SQLiteDatabase.h>
#include <ripple/basics/ByteUtilities.h>
#include <ripple/basics/RangeSet.h>
#include <ripple/basics/chrono.h>
#include <ripple/basics/random.h>
#include <ripple/core/ConfigSections.h>
#include <ripple/nodestore/DummyScheduler.h>
#include <ripple/nodestore/impl/DatabaseShardImp.h>
#include <ripple/overlay/Overlay.h>
#include <ripple/overlay/predicates.h>
#include <ripple/protocol/HashPrefix.h>
#include <ripple/protocol/LedgerHeader.h>
#include <ripple/protocol/digest.h>
#include <boost/algorithm/string/predicate.hpp>
#if BOOST_OS_LINUX
#include <sys/statvfs.h>
#endif
namespace ripple {
namespace NodeStore {
DatabaseShardImp::DatabaseShardImp(
Application& app,
Scheduler& scheduler,
int readThreads,
beast::Journal j)
: DatabaseShard(
scheduler,
readThreads,
app.config().section(ConfigSection::shardDatabase()),
j)
, app_(app)
, avgShardFileSz_(ledgersPerShard_ * kilobytes(192ull))
, openFinalLimit_(
app.config().getValueFor(SizedItem::openFinalLimit, std::nullopt))
{
if (app.config().reporting())
{
Throw<std::runtime_error>(
"Attempted to create DatabaseShardImp in reporting mode. Reporting "
"does not support shards. Remove shards info from config");
}
}
bool
DatabaseShardImp::init()
{
{
std::lock_guard lock(mutex_);
if (init_)
{
JLOG(j_.error()) << "already initialized";
return false;
}
if (!initConfig(lock))
{
JLOG(j_.error()) << "invalid configuration file settings";
return false;
}
try
{
using namespace boost::filesystem;
// Consolidate the main storage path and all historical paths
std::vector<path> paths{dir_};
paths.insert(
paths.end(), historicalPaths_.begin(), historicalPaths_.end());
for (auto const& path : paths)
{
if (exists(path))
{
if (!is_directory(path))
{
JLOG(j_.error()) << path << " must be a directory";
return false;
}
}
else if (!create_directories(path))
{
JLOG(j_.error())
<< "failed to create path: " + path.string();
return false;
}
}
if (!app_.config().standalone() && !historicalPaths_.empty())
{
// Check historical paths for duplicated file systems
if (!checkHistoricalPaths(lock))
return false;
}
ctx_ = std::make_unique<nudb::context>();
ctx_->start();
// Find shards
std::uint32_t openFinals{0};
for (auto const& path : paths)
{
for (auto const& it : directory_iterator(path))
{
// Ignore files
if (!is_directory(it))
continue;
// Ignore nonnumerical directory names
auto const shardDir{it.path()};
auto dirName{shardDir.stem().string()};
if (!std::all_of(
dirName.begin(), dirName.end(), [](auto c) {
return ::isdigit(static_cast<unsigned char>(c));
}))
{
continue;
}
// Ignore values below the earliest shard index
auto const shardIndex{std::stoul(dirName)};
if (shardIndex < earliestShardIndex_)
{
JLOG(j_.debug())
<< "shard " << shardIndex
<< " ignored, comes before earliest shard index "
<< earliestShardIndex_;
continue;
}
// Check if a previous database import failed
if (is_regular_file(shardDir / databaseImportMarker_))
{
JLOG(j_.warn())
<< "shard " << shardIndex
<< " previously failed database import, removing";
remove_all(shardDir);
continue;
}
auto shard{std::make_shared<Shard>(
app_, *this, shardIndex, shardDir.parent_path(), j_)};
if (!shard->init(scheduler_, *ctx_))
{
// Remove corrupted or legacy shard
shard->removeOnDestroy();
JLOG(j_.warn())
<< "shard " << shardIndex << " removed, "
<< (shard->isLegacy() ? "legacy" : "corrupted")
<< " shard";
continue;
}
switch (shard->getState())
{
case ShardState::finalized:
if (++openFinals > openFinalLimit_)
shard->tryClose();
shards_.emplace(shardIndex, std::move(shard));
break;
case ShardState::complete:
finalizeShard(
shards_.emplace(shardIndex, std::move(shard))
.first->second,
true,
std::nullopt);
break;
case ShardState::acquire:
if (acquireIndex_ != 0)
{
JLOG(j_.error())
<< "more than one shard being acquired";
return false;
}
shards_.emplace(shardIndex, std::move(shard));
acquireIndex_ = shardIndex;
break;
default:
JLOG(j_.error())
<< "shard " << shardIndex << " invalid state";
return false;
}
}
}
}
catch (std::exception const& e)
{
JLOG(j_.fatal()) << "Exception caught in function " << __func__
<< ". Error: " << e.what();
return false;
}
init_ = true;
}
updateFileStats();
return true;
}
std::optional<std::uint32_t>
DatabaseShardImp::prepareLedger(std::uint32_t validLedgerSeq)
{
std::optional<std::uint32_t> shardIndex;
{
std::lock_guard lock(mutex_);
assert(init_);
if (acquireIndex_ != 0)
{
if (auto const it{shards_.find(acquireIndex_)}; it != shards_.end())
return it->second->prepare();
// Should never get here
assert(false);
return std::nullopt;
}
if (!canAdd_)
return std::nullopt;
shardIndex = findAcquireIndex(validLedgerSeq, lock);
}
if (!shardIndex)
{
JLOG(j_.debug()) << "no new shards to add";
{
std::lock_guard lock(mutex_);
canAdd_ = false;
}
return std::nullopt;
}
auto const pathDesignation = [this, shardIndex = *shardIndex]() {
std::lock_guard lock(mutex_);
return prepareForNewShard(shardIndex, numHistoricalShards(lock), lock);
}();
if (!pathDesignation)
return std::nullopt;
auto const needsHistoricalPath =
*pathDesignation == PathDesignation::historical;
auto shard = [this, shardIndex, needsHistoricalPath] {
std::lock_guard lock(mutex_);
return std::make_unique<Shard>(
app_,
*this,
*shardIndex,
(needsHistoricalPath ? chooseHistoricalPath(lock) : ""),
j_);
}();
if (!shard->init(scheduler_, *ctx_))
return std::nullopt;
auto const ledgerSeq{shard->prepare()};
{
std::lock_guard lock(mutex_);
shards_.emplace(*shardIndex, std::move(shard));
acquireIndex_ = *shardIndex;
updatePeers(lock);
}
return ledgerSeq;
}
bool
DatabaseShardImp::prepareShards(std::vector<std::uint32_t> const& shardIndexes)
{
auto fail = [j = j_, &shardIndexes](
std::string const& msg,
std::optional<std::uint32_t> shardIndex = std::nullopt) {
auto multipleIndexPrequel = [&shardIndexes] {
std::vector<std::string> indexesAsString(shardIndexes.size());
std::transform(
shardIndexes.begin(),
shardIndexes.end(),
indexesAsString.begin(),
[](uint32_t const index) { return std::to_string(index); });
return std::string("shard") +
(shardIndexes.size() > 1 ? "s " : " ") +
boost::algorithm::join(indexesAsString, ", ");
};
JLOG(j.error()) << (shardIndex ? "shard " + std::to_string(*shardIndex)
: multipleIndexPrequel())
<< " " << msg;
return false;
};
if (shardIndexes.empty())
return fail("invalid shard indexes");
std::lock_guard lock(mutex_);
assert(init_);
if (!canAdd_)
return fail("cannot be stored at this time");
auto historicalShardsToPrepare = 0;
for (auto const shardIndex : shardIndexes)
{
if (shardIndex < earliestShardIndex_)
{
return fail(
"comes before earliest shard index " +
std::to_string(earliestShardIndex_),
shardIndex);
}
// If we are synced to the network, check if the shard index is
// greater or equal to the current or validated shard index.
auto seqCheck = [&](std::uint32_t ledgerSeq) {
if (ledgerSeq >= earliestLedgerSeq_ &&
shardIndex >= seqToShardIndex(ledgerSeq))
{
return fail("invalid index", shardIndex);
}
return true;
};
if (!seqCheck(app_.getLedgerMaster().getValidLedgerIndex() + 1) ||
!seqCheck(app_.getLedgerMaster().getCurrentLedgerIndex()))
{
return fail("invalid index", shardIndex);
}
if (shards_.find(shardIndex) != shards_.end())
return fail("is already stored", shardIndex);
if (preparedIndexes_.find(shardIndex) != preparedIndexes_.end())
return fail(
"is already queued for import from the shard archive handler",
shardIndex);
if (databaseImportStatus_)
{
if (auto shard = databaseImportStatus_->currentShard.lock(); shard)
{
if (shard->index() == shardIndex)
return fail(
"is being imported from the nodestore", shardIndex);
}
}
// Any shard earlier than the two most recent shards
// is a historical shard
if (shardIndex < shardBoundaryIndex())
++historicalShardsToPrepare;
}
auto const numHistShards = numHistoricalShards(lock);
// Check shard count and available storage space
if (numHistShards + historicalShardsToPrepare > maxHistoricalShards_)
return fail("maximum number of historical shards reached");
if (historicalShardsToPrepare)
{
// Check available storage space for historical shards
if (!sufficientStorage(
historicalShardsToPrepare, PathDesignation::historical, lock))
return fail("insufficient storage space available");
}
if (auto const recentShardsToPrepare =
shardIndexes.size() - historicalShardsToPrepare;
recentShardsToPrepare)
{
// Check available storage space for recent shards
if (!sufficientStorage(
recentShardsToPrepare, PathDesignation::none, lock))
return fail("insufficient storage space available");
}
for (auto const shardIndex : shardIndexes)
preparedIndexes_.emplace(shardIndex);
updatePeers(lock);
return true;
}
void
DatabaseShardImp::removePreShard(std::uint32_t shardIndex)
{
std::lock_guard lock(mutex_);
assert(init_);
if (preparedIndexes_.erase(shardIndex))
updatePeers(lock);
}
std::string
DatabaseShardImp::getPreShards()
{
RangeSet<std::uint32_t> rs;
{
std::lock_guard lock(mutex_);
assert(init_);
for (auto const& shardIndex : preparedIndexes_)
rs.insert(shardIndex);
}
if (rs.empty())
return {};
return ripple::to_string(rs);
};
bool
DatabaseShardImp::importShard(
std::uint32_t shardIndex,
boost::filesystem::path const& srcDir)
{
auto fail = [&](std::string const& msg,
std::lock_guard<std::mutex> const& lock) {
JLOG(j_.error()) << "shard " << shardIndex << " " << msg;
// Remove the failed import shard index so it can be retried
preparedIndexes_.erase(shardIndex);
updatePeers(lock);
return false;
};
using namespace boost::filesystem;
try
{
if (!is_directory(srcDir) || is_empty(srcDir))
{
return fail(
"invalid source directory " + srcDir.string(),
std::lock_guard(mutex_));
}
}
catch (std::exception const& e)
{
return fail(
std::string(". Exception caught in function ") + __func__ +
". Error: " + e.what(),
std::lock_guard(mutex_));
}
auto const expectedHash{app_.getLedgerMaster().walkHashBySeq(
lastLedgerSeq(shardIndex), InboundLedger::Reason::GENERIC)};
if (!expectedHash)
return fail("expected hash not found", std::lock_guard(mutex_));
path dstDir;
{
std::lock_guard lock(mutex_);
if (shards_.find(shardIndex) != shards_.end())
return fail("already exists", lock);
// Check shard was prepared for import
if (preparedIndexes_.find(shardIndex) == preparedIndexes_.end())
return fail("was not prepared for import", lock);
auto const pathDesignation{
prepareForNewShard(shardIndex, numHistoricalShards(lock), lock)};
if (!pathDesignation)
return fail("failed to import", lock);
if (*pathDesignation == PathDesignation::historical)
dstDir = chooseHistoricalPath(lock);
else
dstDir = dir_;
}
dstDir /= std::to_string(shardIndex);
auto renameDir = [&, fname = __func__](path const& src, path const& dst) {
try
{
rename(src, dst);
}
catch (std::exception const& e)
{
return fail(
std::string(". Exception caught in function ") + fname +
". Error: " + e.what(),
std::lock_guard(mutex_));
}
return true;
};
// Rename source directory to the shard database directory
if (!renameDir(srcDir, dstDir))
return false;
// Create the new shard
auto shard{std::make_unique<Shard>(
app_, *this, shardIndex, dstDir.parent_path(), j_)};
if (!shard->init(scheduler_, *ctx_) ||
shard->getState() != ShardState::complete)
{
shard.reset();
renameDir(dstDir, srcDir);
return fail("failed to import", std::lock_guard(mutex_));
}
auto const [it, inserted] = [&]() {
std::lock_guard lock(mutex_);
preparedIndexes_.erase(shardIndex);
return shards_.emplace(shardIndex, std::move(shard));
}();
if (!inserted)
{
shard.reset();
renameDir(dstDir, srcDir);
return fail("failed to import", std::lock_guard(mutex_));
}
finalizeShard(it->second, true, expectedHash);
return true;
}
std::shared_ptr<Ledger>
DatabaseShardImp::fetchLedger(uint256 const& hash, std::uint32_t ledgerSeq)
{
auto const shardIndex{seqToShardIndex(ledgerSeq)};
{
std::shared_ptr<Shard> shard;
{
std::lock_guard lock(mutex_);
assert(init_);
auto const it{shards_.find(shardIndex)};
if (it == shards_.end())
return nullptr;
shard = it->second;
}
// Ledger must be stored in a final or acquiring shard
switch (shard->getState())
{
case ShardState::finalized:
break;
case ShardState::acquire:
if (shard->containsLedger(ledgerSeq))
break;
[[fallthrough]];
default:
return nullptr;
}
}
auto const nodeObject{Database::fetchNodeObject(hash, ledgerSeq)};
if (!nodeObject)
return nullptr;
auto fail = [&](std::string const& msg) -> std::shared_ptr<Ledger> {
JLOG(j_.error()) << "shard " << shardIndex << " " << msg;
return nullptr;
};
auto ledger{std::make_shared<Ledger>(
deserializePrefixedHeader(makeSlice(nodeObject->getData())),
app_.config(),
*app_.getShardFamily())};
if (ledger->info().seq != ledgerSeq)
{
return fail(
"encountered invalid ledger sequence " + std::to_string(ledgerSeq));
}
if (ledger->info().hash != hash)
{
return fail(
"encountered invalid ledger hash " + to_string(hash) +
" on sequence " + std::to_string(ledgerSeq));
}
ledger->setFull();
if (!ledger->stateMap().fetchRoot(
SHAMapHash{ledger->info().accountHash}, nullptr))
{
return fail(
"is missing root STATE node on hash " + to_string(hash) +
" on sequence " + std::to_string(ledgerSeq));
}
if (ledger->info().txHash.isNonZero())
{
if (!ledger->txMap().fetchRoot(
SHAMapHash{ledger->info().txHash}, nullptr))
{
return fail(
"is missing root TXN node on hash " + to_string(hash) +
" on sequence " + std::to_string(ledgerSeq));
}
}
return ledger;
}
void
DatabaseShardImp::setStored(std::shared_ptr<Ledger const> const& ledger)
{
auto const ledgerSeq{ledger->info().seq};
if (ledger->info().hash.isZero())
{
JLOG(j_.error()) << "zero ledger hash for ledger sequence "
<< ledgerSeq;
return;
}
if (ledger->info().accountHash.isZero())
{
JLOG(j_.error()) << "zero account hash for ledger sequence "
<< ledgerSeq;
return;
}
if (ledger->stateMap().getHash().isNonZero() &&
!ledger->stateMap().isValid())
{
JLOG(j_.error()) << "invalid state map for ledger sequence "
<< ledgerSeq;
return;
}
if (ledger->info().txHash.isNonZero() && !ledger->txMap().isValid())
{
JLOG(j_.error()) << "invalid transaction map for ledger sequence "
<< ledgerSeq;
return;
}
auto const shardIndex{seqToShardIndex(ledgerSeq)};
std::shared_ptr<Shard> shard;
{
std::lock_guard lock(mutex_);
assert(init_);
if (shardIndex != acquireIndex_)
{
JLOG(j_.trace())
<< "shard " << shardIndex << " is not being acquired";
return;
}
auto const it{shards_.find(shardIndex)};
if (it == shards_.end())
{
JLOG(j_.error())
<< "shard " << shardIndex << " is not being acquired";
return;
}
shard = it->second;
}
if (shard->containsLedger(ledgerSeq))
{
JLOG(j_.trace()) << "shard " << shardIndex << " ledger already stored";
return;
}
setStoredInShard(shard, ledger);
}
std::unique_ptr<ShardInfo>
DatabaseShardImp::getShardInfo() const
{
std::lock_guard lock(mutex_);
return getShardInfo(lock);
}
void
DatabaseShardImp::stop()
{
// Stop read threads in base before data members are destroyed
Database::stop();
std::vector<std::weak_ptr<Shard>> shards;
{
std::lock_guard lock(mutex_);
shards.reserve(shards_.size());
for (auto const& [_, shard] : shards_)
{
shards.push_back(shard);
shard->stop();
}
shards_.clear();
}
taskQueue_.stop();
// All shards should be expired at this point
for (auto const& wptr : shards)
{
if (auto const shard{wptr.lock()})
{
JLOG(j_.warn()) << " shard " << shard->index() << " unexpired";
}
}
std::unique_lock lock(mutex_);
// Notify the shard being imported
// from the node store to stop
if (databaseImportStatus_)
{
// A node store import is in progress
if (auto importShard = databaseImportStatus_->currentShard.lock();
importShard)
importShard->stop();
}
// Wait for the node store import thread
// if necessary
if (databaseImporter_.joinable())
{
// Tells the import function to halt
haltDatabaseImport_ = true;
// Wait for the function to exit
while (databaseImportStatus_)
{
// Unlock just in case the import
// function is waiting on the mutex
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
lock.lock();
}
// Calling join while holding the mutex_ without
// first making sure that doImportDatabase has
// exited could lead to deadlock via the mutex
// acquisition that occurs in that function
if (databaseImporter_.joinable())
databaseImporter_.join();
}
}
void
DatabaseShardImp::importDatabase(Database& source)
{
std::lock_guard lock(mutex_);
assert(init_);
// Only the application local node store can be imported
assert(&source == &app_.getNodeStore());
if (databaseImporter_.joinable())
{
assert(false);
JLOG(j_.error()) << "database import already in progress";
return;
}
startDatabaseImportThread(lock);
}
void
DatabaseShardImp::doImportDatabase()
{
auto shouldHalt = [this] {
bool expected = true;
return haltDatabaseImport_.compare_exchange_strong(expected, false) ||
isStopping();
};
if (shouldHalt())
return;
auto loadLedger =
[this](char const* const sortOrder) -> std::optional<std::uint32_t> {
std::shared_ptr<Ledger> ledger;
std::uint32_t ledgerSeq{0};
std::optional<LedgerInfo> info;
if (sortOrder == std::string("asc"))
{
info = dynamic_cast<SQLiteDatabase*>(&app_.getRelationalDatabase())
->getLimitedOldestLedgerInfo(earliestLedgerSeq());
}
else
{
info = dynamic_cast<SQLiteDatabase*>(&app_.getRelationalDatabase())
->getLimitedNewestLedgerInfo(earliestLedgerSeq());
}
if (info)
{
ledger = loadLedgerHelper(*info, app_, false);
ledgerSeq = info->seq;
}
if (!ledger || ledgerSeq == 0)
{
JLOG(j_.error()) << "no suitable ledgers were found in"
" the SQLite database to import";
return std::nullopt;
}
return ledgerSeq;
};
// Find earliest ledger sequence stored
auto const earliestLedgerSeq{loadLedger("asc")};
if (!earliestLedgerSeq)
return;
auto const earliestIndex = [&] {
auto earliestIndex = seqToShardIndex(*earliestLedgerSeq);
// Consider only complete shards
if (earliestLedgerSeq != firstLedgerSeq(earliestIndex))
++earliestIndex;
return earliestIndex;
}();
// Find last ledger sequence stored
auto const latestLedgerSeq = loadLedger("desc");
if (!latestLedgerSeq)
return;
auto const latestIndex = [&] {
auto latestIndex = seqToShardIndex(*latestLedgerSeq);
// Consider only complete shards
if (latestLedgerSeq != lastLedgerSeq(latestIndex))
--latestIndex;
return latestIndex;
}();
if (latestIndex < earliestIndex)
{
JLOG(j_.error()) << "no suitable ledgers were found in"
" the SQLite database to import";
return;
}
JLOG(j_.debug()) << "Importing ledgers for shards " << earliestIndex
<< " through " << latestIndex;
{
std::lock_guard lock(mutex_);
assert(!databaseImportStatus_);
databaseImportStatus_ = std::make_unique<DatabaseImportStatus>(
earliestIndex, latestIndex, 0);
}
// Import the shards
for (std::uint32_t shardIndex = earliestIndex; shardIndex <= latestIndex;
++shardIndex)
{
if (shouldHalt())
return;
auto const pathDesignation = [this, shardIndex] {
std::lock_guard lock(mutex_);
auto const numHistShards = numHistoricalShards(lock);
auto const pathDesignation =
prepareForNewShard(shardIndex, numHistShards, lock);
return pathDesignation;
}();
if (!pathDesignation)
break;
{
std::lock_guard lock(mutex_);
// Skip if being acquired
if (shardIndex == acquireIndex_)
{
JLOG(j_.debug())
<< "shard " << shardIndex << " already being acquired";
continue;
}
// Skip if being imported from the shard archive handler
if (preparedIndexes_.find(shardIndex) != preparedIndexes_.end())
{
JLOG(j_.debug())
<< "shard " << shardIndex << " already being imported";
continue;
}
// Skip if stored
if (shards_.find(shardIndex) != shards_.end())
{
JLOG(j_.debug()) << "shard " << shardIndex << " already stored";
continue;
}
}
std::uint32_t const firstSeq = firstLedgerSeq(shardIndex);
std::uint32_t const lastSeq =
std::max(firstSeq, lastLedgerSeq(shardIndex));
// Verify SQLite ledgers are in the node store
{
auto const ledgerHashes{
app_.getRelationalDatabase().getHashesByIndex(
firstSeq, lastSeq)};
if (ledgerHashes.size() != maxLedgers(shardIndex))
continue;
auto& source = app_.getNodeStore();
bool valid{true};
for (std::uint32_t n = firstSeq; n <= lastSeq; ++n)
{
if (!source.fetchNodeObject(ledgerHashes.at(n).ledgerHash, n))
{
JLOG(j_.warn()) << "SQLite ledger sequence " << n
<< " mismatches node store";
valid = false;
break;
}
}
if (!valid)
continue;
}
if (shouldHalt())
return;
bool const needsHistoricalPath =
*pathDesignation == PathDesignation::historical;
auto const path = needsHistoricalPath
? chooseHistoricalPath(std::lock_guard(mutex_))
: dir_;
// Create the new shard
auto shard{std::make_shared<Shard>(app_, *this, shardIndex, path, j_)};
if (!shard->init(scheduler_, *ctx_))
continue;
{
std::lock_guard lock(mutex_);
if (shouldHalt())
return;
databaseImportStatus_->currentIndex = shardIndex;
databaseImportStatus_->currentShard = shard;
databaseImportStatus_->firstSeq = firstSeq;
databaseImportStatus_->lastSeq = lastSeq;
}
// Create a marker file to signify a database import in progress
auto const shardDir{path / std::to_string(shardIndex)};
auto const markerFile{shardDir / databaseImportMarker_};
{
std::ofstream ofs{markerFile.string()};
if (!ofs.is_open())
{
JLOG(j_.error()) << "shard " << shardIndex
<< " failed to create temp marker file";
shard->removeOnDestroy();
continue;
}
}
// Copy the ledgers from node store
std::shared_ptr<Ledger> recentStored;
std::optional<uint256> lastLedgerHash;
while (auto const ledgerSeq = shard->prepare())
{
if (shouldHalt())
return;
// Not const so it may be moved later
auto ledger{loadByIndex(*ledgerSeq, app_, false)};