/
wiredtiger_kv_engine.cpp
2111 lines (1771 loc) · 78.2 KB
/
wiredtiger_kv_engine.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 (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage
#define LOG_FOR_RECOVERY(level) \
MONGO_LOG_COMPONENT(level, ::mongo::logger::LogComponent::kStorageRecovery)
#define LOG_FOR_ROLLBACK(level) \
MONGO_LOG_COMPONENT(level, ::mongo::logger::LogComponent::kReplicationRollback)
#include "mongo/platform/basic.h"
#ifdef _WIN32
#define NVALGRIND
#endif
#include <fmt/format.h>
#include <memory>
#include "mongo/db/storage/wiredtiger/wiredtiger_kv_engine.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/system/error_code.hpp>
#include <fmt/format.h>
#include <valgrind/valgrind.h>
#include "mongo/base/error_codes.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/bson/dotted_path_support.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/client.h"
#include "mongo/db/commands/server_status_metric.h"
#include "mongo/db/concurrency/locker.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/global_settings.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/repl/repl_settings.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/server_options.h"
#include "mongo/db/server_recovery.h"
#include "mongo/db/service_context.h"
#include "mongo/db/snapshot_window_options.h"
#include "mongo/db/storage/journal_listener.h"
#include "mongo/db/storage/storage_file_util.h"
#include "mongo/db/storage/storage_options.h"
#include "mongo/db/storage/storage_parameters_gen.h"
#include "mongo/db/storage/storage_repair_observer.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_cursor.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_customization_hooks.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_extensions.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_global_options.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_index.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_parameters_gen.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_record_store.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_recovery_unit.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_session_cache.h"
#include "mongo/db/storage/wiredtiger/wiredtiger_size_storer.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/util/background.h"
#include "mongo/util/concurrency/idle_thread_block.h"
#include "mongo/util/concurrency/ticketholder.h"
#include "mongo/util/debug_util.h"
#include "mongo/util/exit.h"
#include "mongo/util/log.h"
#include "mongo/util/processinfo.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/time_support.h"
#if !defined(__has_feature)
#define __has_feature(x) 0
#endif
using namespace fmt::literals;
namespace mongo {
namespace {
MONGO_FAIL_POINT_DEFINE(WTPreserveSnapshotHistoryIndefinitely);
MONGO_FAIL_POINT_DEFINE(WTSetOldestTSToStableTS);
MONGO_FAIL_POINT_DEFINE(pauseCheckpointThread);
} // namespace
bool WiredTigerFileVersion::shouldDowngrade(bool readOnly,
bool repairMode,
bool hasRecoveryTimestamp) {
if (readOnly) {
// A read-only state must not have upgraded. Nor could it downgrade.
return false;
}
const auto replCoord = repl::ReplicationCoordinator::get(getGlobalServiceContext());
const auto memberState = replCoord->getMemberState();
if (memberState.arbiter()) {
// SERVER-35361: Arbiters will no longer downgrade their data files. To downgrade
// binaries, the user must delete the dbpath. It's not particularly expensive for a
// replica set to re-initialize an arbiter that comes online.
return false;
}
if (!serverGlobalParams.featureCompatibility.isVersionInitialized()) {
// If the FCV document hasn't been read, trust the WT compatibility. MongoD will
// downgrade to the same compatibility it discovered on startup.
return _startupVersion == StartupVersion::IS_42 ||
_startupVersion == StartupVersion::IS_40 || _startupVersion == StartupVersion::IS_36 ||
_startupVersion == StartupVersion::IS_34;
}
if (serverGlobalParams.featureCompatibility.getVersion() !=
ServerGlobalParams::FeatureCompatibility::Version::kFullyDowngradedTo42) {
// Only consider downgrading when FCV is set to 4.2
return false;
}
if (getGlobalReplSettings().usingReplSets()) {
// If this process is run with `--replSet`, it must have run any startup replication
// recovery and downgrading at this point is safe.
return true;
}
if (hasRecoveryTimestamp) {
// If we're not running with `--replSet`, don't allow downgrades if the node needed to run
// replication recovery. Having a recovery timestamp implies recovery must be run, but it
// was not.
return false;
}
// If there is no `recoveryTimestamp`, then the data should be consistent with the top of
// oplog and downgrading can proceed. This is expected for standalone datasets that use FCV.
return true;
}
std::string WiredTigerFileVersion::getDowngradeString() {
if (!serverGlobalParams.featureCompatibility.isVersionInitialized()) {
invariant(_startupVersion != StartupVersion::IS_44);
switch (_startupVersion) {
case StartupVersion::IS_34:
return "compatibility=(release=2.9)";
case StartupVersion::IS_36:
return "compatibility=(release=3.0)";
case StartupVersion::IS_40:
return "compatibility=(release=3.1)";
case StartupVersion::IS_42:
return "compatibility=(release=3.2)";
default:
MONGO_UNREACHABLE;
}
}
return "compatibility=(release=3.2)";
}
using std::set;
using std::string;
namespace dps = ::mongo::dotted_path_support;
class WiredTigerKVEngine::WiredTigerSessionSweeper : public BackgroundJob {
public:
explicit WiredTigerSessionSweeper(WiredTigerSessionCache* sessionCache)
: BackgroundJob(false /* deleteSelf */), _sessionCache(sessionCache) {}
virtual string name() const {
return "WTIdleSessionSweeper";
}
virtual void run() {
ThreadClient tc(name(), getGlobalServiceContext());
LOG(1) << "starting " << name() << " thread";
while (!_shuttingDown.load()) {
{
stdx::unique_lock<Latch> lock(_mutex);
MONGO_IDLE_THREAD_BLOCK;
// Check every 10 seconds or sooner in the debug builds
_condvar.wait_for(lock, stdx::chrono::seconds(kDebugBuild ? 1 : 10));
}
_sessionCache->closeExpiredIdleSessions(gWiredTigerSessionCloseIdleTimeSecs.load() *
1000);
}
LOG(1) << "stopping " << name() << " thread";
}
void shutdown() {
_shuttingDown.store(true);
{
stdx::unique_lock<Latch> lock(_mutex);
// Wake up the session sweeper thread early, we do not want the shutdown
// to wait for us too long.
_condvar.notify_one();
}
wait();
}
private:
WiredTigerSessionCache* _sessionCache;
AtomicWord<bool> _shuttingDown{false};
Mutex _mutex = MONGO_MAKE_LATCH("WiredTigerSessionSweeper::_mutex"); // protects _condvar
// The session sweeper thread idles on this condition variable for a particular time duration
// between cleaning up expired sessions. It can be triggered early to expediate shutdown.
stdx::condition_variable _condvar;
};
class WiredTigerKVEngine::WiredTigerJournalFlusher : public BackgroundJob {
public:
explicit WiredTigerJournalFlusher(WiredTigerSessionCache* sessionCache)
: BackgroundJob(false /* deleteSelf */), _sessionCache(sessionCache) {}
virtual string name() const {
return "WTJournalFlusher";
}
virtual void run() {
ThreadClient tc(name(), getGlobalServiceContext());
LOG(1) << "starting " << name() << " thread";
while (true) {
auto opCtx = tc->makeOperationContext();
try {
_sessionCache->waitUntilDurable(
opCtx.get(), /*forceCheckpoint*/ false, /*stableCheckpoint*/ false);
} catch (const AssertionException& e) {
invariant(e.code() == ErrorCodes::ShutdownInProgress);
}
// Wait until either journalCommitIntervalMs passes or an immediate journal flush is
// requested (or shutdown).
auto deadline =
Date_t::now() + Milliseconds(storageGlobalParams.journalCommitIntervalMs.load());
stdx::unique_lock<Latch> lk(_stateMutex);
MONGO_IDLE_THREAD_BLOCK;
_flushJournalNowCV.wait_until(lk, deadline.toSystemTimePoint(), [&] {
return _flushJournalNow || _shuttingDown;
});
_flushJournalNow = false;
if (_shuttingDown) {
LOG(1) << "stopping " << name() << " thread";
return;
}
}
}
/**
* Signals the thread to quit and then waits until it does.
*/
void shutdown() {
{
stdx::lock_guard<Latch> lk(_stateMutex);
_shuttingDown = true;
_flushJournalNowCV.notify_one();
}
wait();
}
/**
* Signals an immediate journal flush.
*/
void triggerJournalFlush() {
stdx::lock_guard<Latch> lk(_stateMutex);
if (!_flushJournalNow) {
_flushJournalNow = true;
_flushJournalNowCV.notify_one();
}
}
private:
WiredTigerSessionCache* _sessionCache;
// Protects the state below.
mutable Mutex _stateMutex = MONGO_MAKE_LATCH("WiredTigerJournalFlusherStateMutex");
// Signaled to wake up the thread, if the thread is waiting. The thread will check whether
// _flushJournalNow or _shuttingDown is set.
mutable stdx::condition_variable _flushJournalNowCV;
bool _flushJournalNow = false;
bool _shuttingDown = false;
};
namespace {
/**
* RAII class that holds an exclusive lock on the checkpoint resource mutex.
*
* Instances are created via getCheckpointLock(), which passes in the checkpoint resource mutex.
*/
class CheckpointLockImpl : public StorageEngine::CheckpointLock {
CheckpointLockImpl(const CheckpointLockImpl&) = delete;
CheckpointLockImpl& operator=(const CheckpointLockImpl&) = delete;
CheckpointLockImpl(CheckpointLockImpl&& other) = delete;
public:
CheckpointLockImpl() = delete;
CheckpointLockImpl(OperationContext* opCtx, Lock::ResourceMutex mutex)
: _lk(opCtx->lockState(), mutex) {
invariant(_lk.isLocked());
}
~CheckpointLockImpl() = default;
private:
Lock::ExclusiveLock _lk;
};
} // namespace
std::string toString(const StorageEngine::OldestActiveTransactionTimestampResult& r) {
if (r.isOK()) {
if (r.getValue()) {
// Timestamp.
return r.getValue().value().toString();
} else {
// boost::none.
return "null";
}
} else {
return r.getStatus().toString();
}
}
class WiredTigerKVEngine::WiredTigerCheckpointThread : public BackgroundJob {
public:
explicit WiredTigerCheckpointThread(WiredTigerKVEngine* wiredTigerKVEngine,
WiredTigerSessionCache* sessionCache)
: BackgroundJob(false /* deleteSelf */),
_wiredTigerKVEngine(wiredTigerKVEngine),
_sessionCache(sessionCache) {}
virtual string name() const {
return "WTCheckpointThread";
}
virtual void run() {
ThreadClient tc(name(), getGlobalServiceContext());
LOG(1) << "starting " << name() << " thread";
while (!_shuttingDown.load()) {
auto opCtx = tc->makeOperationContext();
{
stdx::unique_lock<Latch> lock(_mutex);
MONGO_IDLE_THREAD_BLOCK;
_condvar.wait_for(lock,
stdx::chrono::seconds(static_cast<std::int64_t>(
wiredTigerGlobalOptions.checkpointDelaySecs)));
}
pauseCheckpointThread.pauseWhileSet();
// Might have been awakened by another thread shutting us down.
if (_shuttingDown.load()) {
break;
}
const Date_t startTime = Date_t::now();
const Timestamp stableTimestamp = _wiredTigerKVEngine->getStableTimestamp();
const Timestamp initialDataTimestamp = _wiredTigerKVEngine->getInitialDataTimestamp();
// The amount of oplog to keep is primarily dictated by a user setting. However, in
// unexpected cases, durable, recover to a timestamp storage engines may need to play
// forward from an oplog entry that would otherwise be truncated by the user
// setting. Furthermore, the entries in prepared or large transactions can refer to
// previous entries in the same transaction.
//
// Live (replication) rollback will replay oplogs from exactly the stable timestamp.
// With prepared or large transactions, it may require some additional entries prior to
// the stable timestamp. These requirements are summarized in getOplogNeededForRollback.
// Truncating the oplog at this point is sufficient for in-memory configurations, but
// could cause an unrecoverable scenario if the node crashed and has to play from the
// last stable checkpoint.
//
// By recording the oplog needed for rollback "now", then taking a stable checkpoint,
// we can safely assume that the oplog needed for crash recovery has caught up to the
// recorded value. After the checkpoint, this value will be published such that actors
// which truncate the oplog can read an updated value.
try {
// Three cases:
//
// First, initialDataTimestamp is Timestamp(0, 1) -> Take full checkpoint. This is
// when there is no consistent view of the data (i.e: during initial sync).
//
// Second, stableTimestamp < initialDataTimestamp: Skip checkpoints. The data on
// disk is prone to being rolled back. Hold off on checkpoints. Hope that the
// stable timestamp surpasses the data on disk, allowing storage to persist newer
// copies to disk.
//
// Third, stableTimestamp >= initialDataTimestamp: Take stable checkpoint. Steady
// state case.
if (initialDataTimestamp.asULL() <= 1) {
UniqueWiredTigerSession session = _sessionCache->getSession();
WT_SESSION* s = session->getSession();
auto checkpointLock = _wiredTigerKVEngine->getCheckpointLock(opCtx.get());
_wiredTigerKVEngine->clearIndividuallyCheckpointedIndexesList();
invariantWTOK(s->checkpoint(s, "use_timestamp=false"));
} else if (stableTimestamp < initialDataTimestamp) {
LOG_FOR_RECOVERY(2)
<< "Stable timestamp is behind the initial data timestamp, skipping "
"a checkpoint. StableTimestamp: "
<< stableTimestamp.toString()
<< " InitialDataTimestamp: " << initialDataTimestamp.toString();
} else {
auto oplogNeededForRollback = _wiredTigerKVEngine->getOplogNeededForRollback();
LOG_FOR_RECOVERY(2)
<< "Performing stable checkpoint. StableTimestamp: " << stableTimestamp
<< ", OplogNeededForRollback: " << toString(oplogNeededForRollback);
UniqueWiredTigerSession session = _sessionCache->getSession();
WT_SESSION* s = session->getSession();
{
auto checkpointLock = _wiredTigerKVEngine->getCheckpointLock(opCtx.get());
_wiredTigerKVEngine->clearIndividuallyCheckpointedIndexesList();
invariantWTOK(s->checkpoint(s, "use_timestamp=true"));
}
if (oplogNeededForRollback.isOK()) {
// Now that the checkpoint is durable, publish the oplog needed to recover
// from it.
stdx::lock_guard<Latch> lk(_oplogNeededForCrashRecoveryMutex);
_oplogNeededForCrashRecovery.store(
oplogNeededForRollback.getValue().asULL());
}
}
const auto secondsElapsed = durationCount<Seconds>(Date_t::now() - startTime);
if (secondsElapsed >= 30) {
LOG(1) << "Checkpoint took " << secondsElapsed << " seconds to complete.";
}
} catch (const WriteConflictException&) {
// Temporary: remove this after WT-3483
warning() << "Checkpoint encountered a write conflict exception.";
} catch (const AssertionException& exc) {
invariant(ErrorCodes::isShutdownError(exc.code()), exc.what());
}
}
LOG(1) << "stopping " << name() << " thread";
}
/**
* Returns true if we have already triggered taking the first checkpoint.
*/
bool hasTriggeredFirstStableCheckpoint() {
return _hasTriggeredFirstStableCheckpoint;
}
/**
* Triggers taking the first stable checkpoint, which is when the stable timestamp advances past
* the initial data timestamp.
*
* The checkpoint thread runs automatically every wiredTigerGlobalOptions.checkpointDelaySecs
* seconds. This function avoids potentially waiting that full duration for a stable checkpoint,
* initiating one immediately.
*
* Do not call this function if hasTriggeredFirstStableCheckpoint() returns true.
*/
void triggerFirstStableCheckpoint(Timestamp prevStable,
Timestamp initialData,
Timestamp currStable) {
invariant(!_hasTriggeredFirstStableCheckpoint);
if (prevStable < initialData && currStable >= initialData) {
_hasTriggeredFirstStableCheckpoint = true;
log() << "Triggering the first stable checkpoint. Initial Data: " << initialData
<< " PrevStable: " << prevStable << " CurrStable: " << currStable;
stdx::unique_lock<Latch> lock(_mutex);
_condvar.notify_one();
}
}
std::uint64_t getOplogNeededForCrashRecovery() const {
return _oplogNeededForCrashRecovery.load();
}
/*
* Atomically assign _oplogNeededForCrashRecovery to a variable.
* _oplogNeededForCrashRecovery will not change during assignment.
*/
void assignOplogNeededForCrashRecoveryTo(boost::optional<Timestamp>* timestamp) {
stdx::lock_guard<Latch> lk(_oplogNeededForCrashRecoveryMutex);
*timestamp = Timestamp(_oplogNeededForCrashRecovery.load());
}
void shutdown() {
_shuttingDown.store(true);
{
stdx::unique_lock<Latch> lock(_mutex);
// Wake up the checkpoint thread early, to take a final checkpoint before shutting
// down, if one has not coincidentally just been taken.
_condvar.notify_one();
}
wait();
}
private:
WiredTigerKVEngine* _wiredTigerKVEngine;
WiredTigerSessionCache* _sessionCache;
Mutex _mutex = MONGO_MAKE_LATCH("WiredTigerCheckpointThread::_mutex");
; // protects _condvar
// The checkpoint thread idles on this condition variable for a particular time duration between
// taking checkpoints. It can be triggered early to expediate immediate checkpointing.
stdx::condition_variable _condvar;
AtomicWord<bool> _shuttingDown{false};
bool _hasTriggeredFirstStableCheckpoint = false;
Mutex _oplogNeededForCrashRecoveryMutex =
MONGO_MAKE_LATCH("WiredTigerCheckpointThread::_oplogNeededForCrashRecoveryMutex");
AtomicWord<std::uint64_t> _oplogNeededForCrashRecovery;
};
namespace {
TicketHolder openWriteTransaction(128);
TicketHolder openReadTransaction(128);
} // namespace
OpenWriteTransactionParam::OpenWriteTransactionParam(StringData name, ServerParameterType spt)
: ServerParameter(name, spt), _data(&openWriteTransaction) {}
void OpenWriteTransactionParam::append(OperationContext* opCtx,
BSONObjBuilder& b,
const std::string& name) {
b.append(name, _data->outof());
}
Status OpenWriteTransactionParam::setFromString(const std::string& str) {
int num = 0;
Status status = NumberParser{}(str, &num);
if (!status.isOK()) {
return status;
}
if (num <= 0) {
return {ErrorCodes::BadValue, str::stream() << name() << " has to be > 0"};
}
return _data->resize(num);
}
OpenReadTransactionParam::OpenReadTransactionParam(StringData name, ServerParameterType spt)
: ServerParameter(name, spt), _data(&openReadTransaction) {}
void OpenReadTransactionParam::append(OperationContext* opCtx,
BSONObjBuilder& b,
const std::string& name) {
b.append(name, _data->outof());
}
Status OpenReadTransactionParam::setFromString(const std::string& str) {
int num = 0;
Status status = NumberParser{}(str, &num);
if (!status.isOK()) {
return status;
}
if (num <= 0) {
return {ErrorCodes::BadValue, str::stream() << name() << " has to be > 0"};
}
return _data->resize(num);
}
namespace {
StatusWith<std::vector<StorageEngine::BackupBlock>> getDataBlocksFromBackupCursor(
WT_CURSOR* cursor, std::string dbPath, const char* statusPrefix) {
int wtRet;
std::vector<StorageEngine::BackupBlock> blocks;
const char* filename;
const auto directoryPath = boost::filesystem::path(dbPath);
const auto wiredTigerLogFilePrefix = "WiredTigerLog";
while ((wtRet = cursor->next(cursor)) == 0) {
invariantWTOK(cursor->get_key(cursor, &filename));
std::string name(filename);
auto filePath = directoryPath;
if (name.find(wiredTigerLogFilePrefix) == 0) {
// TODO SERVER-13455:replace `journal/` with the configurable journal path.
filePath /= boost::filesystem::path("journal");
}
filePath /= name;
boost::system::error_code errorCode;
const std::uint64_t filesize = boost::filesystem::file_size(filePath, errorCode);
uassert(31317,
"Failed to get a file's size. Filename: {} Error: {}"_format(filePath.string(),
errorCode.message()),
!errorCode);
blocks.push_back({filePath.string(), 0, filesize});
}
if (wtRet != WT_NOTFOUND) {
return wtRCToStatus(wtRet, statusPrefix);
}
return blocks;
}
} // namespace
StringData WiredTigerKVEngine::kTableUriPrefix = "table:"_sd;
WiredTigerKVEngine::WiredTigerKVEngine(const std::string& canonicalName,
const std::string& path,
ClockSource* cs,
const std::string& extraOpenOptions,
size_t cacheSizeMB,
size_t maxCacheOverflowFileSizeMB,
bool durable,
bool ephemeral,
bool repair,
bool readOnly)
: _clockSource(cs),
_oplogManager(std::make_unique<WiredTigerOplogManager>()),
_canonicalName(canonicalName),
_path(path),
_sizeStorerSyncTracker(cs, 100000, Seconds(60)),
_durable(durable),
_ephemeral(ephemeral),
_inRepairMode(repair),
_readOnly(readOnly),
_keepDataHistory(serverGlobalParams.enableMajorityReadConcern) {
boost::filesystem::path journalPath = path;
journalPath /= "journal";
if (_durable) {
if (!boost::filesystem::exists(journalPath)) {
try {
boost::filesystem::create_directory(journalPath);
} catch (std::exception& e) {
log() << "error creating journal dir " << journalPath.string() << ' ' << e.what();
throw;
}
}
}
_previousCheckedDropsQueued = _clockSource->now();
std::stringstream ss;
ss << "create,";
ss << "cache_size=" << cacheSizeMB << "M,";
ss << "cache_overflow=(file_max=" << maxCacheOverflowFileSizeMB << "M),";
ss << "session_max=33000,";
ss << "eviction=(threads_min=4,threads_max=4),";
ss << "config_base=false,";
ss << "statistics=(fast),";
if (!WiredTigerSessionCache::isEngineCachingCursors()) {
ss << "cache_cursors=false,";
}
// The setting may have a later setting override it if not using the journal. We make it
// unconditional here because even nojournal may need this setting if it is a transition
// from using the journal.
if (!_readOnly) {
// If we're readOnly skip all WAL-related settings.
ss << "log=(enabled=true,archive=true,path=journal,compressor=";
ss << wiredTigerGlobalOptions.journalCompressor << "),";
ss << "file_manager=(close_idle_time=" << gWiredTigerFileHandleCloseIdleTime
<< ",close_scan_interval=" << gWiredTigerFileHandleCloseScanInterval
<< ",close_handle_minimum=" << gWiredTigerFileHandleCloseMinimum << "),";
ss << "statistics_log=(wait=" << wiredTigerGlobalOptions.statisticsLogDelaySecs << "),";
if (shouldLog(::mongo::logger::LogComponent::kStorageRecovery,
logger::LogSeverity::Debug(3))) {
ss << "verbose=[recovery_progress,checkpoint_progress,compact_progress,recovery],";
} else {
ss << "verbose=[recovery_progress,checkpoint_progress,compact_progress],";
}
if (kDebugBuild) {
// Enable debug write-ahead logging for all tables under debug build.
ss << "debug_mode=(table_logging=true,";
// For select debug builds, support enabling WiredTiger eviction debug mode. This uses
// more aggressive eviction tactics, but may have a negative performance impact.
if (gWiredTigerEvictionDebugMode) {
ss << "eviction=true,";
}
ss << "),";
}
}
ss << WiredTigerCustomizationHooks::get(getGlobalServiceContext())
->getTableCreateConfig("system");
ss << WiredTigerExtensions::get(getGlobalServiceContext())->getOpenExtensionsConfig();
ss << extraOpenOptions;
if (_readOnly) {
invariant(!_durable);
ss << ",readonly=true,";
}
if (!_durable && !_readOnly) {
// If we started without the journal, but previously used the journal then open with the
// WT log enabled to perform any unclean shutdown recovery and then close and reopen in
// the normal path without the journal.
if (boost::filesystem::exists(journalPath)) {
string config = ss.str();
log() << "Detected WT journal files. Running recovery from last checkpoint.";
log() << "journal to nojournal transition config: " << config;
int ret = wiredtiger_open(
path.c_str(), _eventHandler.getWtEventHandler(), config.c_str(), &_conn);
if (ret == EINVAL) {
fassertFailedNoTrace(28717);
} else if (ret != 0) {
Status s(wtRCToStatus(ret));
msgasserted(28718, s.reason());
}
invariantWTOK(_conn->close(_conn, nullptr));
// After successful recovery, remove the journal directory.
try {
boost::filesystem::remove_all(journalPath);
} catch (std::exception& e) {
error() << "error removing journal dir " << journalPath.string() << ' ' << e.what();
throw;
}
}
// This setting overrides the earlier setting because it is later in the config string.
ss << ",log=(enabled=false),";
}
string config = ss.str();
log() << "wiredtiger_open config: " << config;
_openWiredTiger(path, config);
_eventHandler.setStartupSuccessful();
_wtOpenConfig = config;
{
char buf[(2 * 8 /*bytes in hex*/) + 1 /*nul terminator*/];
invariantWTOK(_conn->query_timestamp(_conn, buf, "get=recovery"));
std::uint64_t tmp;
fassert(50758, NumberParser().base(16)(buf, &tmp));
_recoveryTimestamp = Timestamp(tmp);
LOG_FOR_RECOVERY(0) << "WiredTiger recoveryTimestamp. Ts: " << _recoveryTimestamp;
}
_sessionCache.reset(new WiredTigerSessionCache(this));
_sessionSweeper = std::make_unique<WiredTigerSessionSweeper>(_sessionCache.get());
_sessionSweeper->go();
// Until the Replication layer installs a real callback, prevent truncating the oplog.
setOldestActiveTransactionTimestampCallback(
[](Timestamp) { return StatusWith(boost::make_optional(Timestamp::min())); });
if (!_readOnly && !_ephemeral) {
if (!_recoveryTimestamp.isNull()) {
setInitialDataTimestamp(_recoveryTimestamp);
setOldestTimestamp(_recoveryTimestamp, false);
setStableTimestamp(_recoveryTimestamp, false);
}
}
if (_ephemeral && !getTestCommandsEnabled()) {
// We do not maintain any snapshot history for the ephemeral storage engine in production
// because replication and sharded transactions do not currently run on the inMemory engine.
// It is live in testing, however.
snapshotWindowParams.targetSnapshotHistoryWindowInSeconds.store(0);
}
_sizeStorerUri = _uri("sizeStorer");
WiredTigerSession session(_conn);
if (!_readOnly && repair && _hasUri(session.getSession(), _sizeStorerUri)) {
log() << "Repairing size cache";
auto status = _salvageIfNeeded(_sizeStorerUri.c_str());
if (status.code() != ErrorCodes::DataModifiedByRepair)
fassertNoTrace(28577, status);
}
_sizeStorer = std::make_unique<WiredTigerSizeStorer>(_conn, _sizeStorerUri, _readOnly);
Locker::setGlobalThrottling(&openReadTransaction, &openWriteTransaction);
}
WiredTigerKVEngine::~WiredTigerKVEngine() {
if (_conn) {
cleanShutdown();
}
_sessionCache.reset(nullptr);
}
void WiredTigerKVEngine::startAsyncThreads() {
if (!_ephemeral) {
if (_durable) {
_journalFlusher = std::make_unique<WiredTigerJournalFlusher>(_sessionCache.get());
_journalFlusher->go();
}
if (!_readOnly) {
_checkpointThread =
std::make_unique<WiredTigerCheckpointThread>(this, _sessionCache.get());
_checkpointThread->go();
}
}
}
void WiredTigerKVEngine::appendGlobalStats(BSONObjBuilder& b) {
BSONObjBuilder bb(b.subobjStart("concurrentTransactions"));
{
BSONObjBuilder bbb(bb.subobjStart("write"));
bbb.append("out", openWriteTransaction.used());
bbb.append("available", openWriteTransaction.available());
bbb.append("totalTickets", openWriteTransaction.outof());
bbb.done();
}
{
BSONObjBuilder bbb(bb.subobjStart("read"));
bbb.append("out", openReadTransaction.used());
bbb.append("available", openReadTransaction.available());
bbb.append("totalTickets", openReadTransaction.outof());
bbb.done();
}
bb.done();
}
void WiredTigerKVEngine::_openWiredTiger(const std::string& path, const std::string& wtOpenConfig) {
std::string configStr = wtOpenConfig + ",compatibility=(require_min=\"3.1.0\")";
auto wtEventHandler = _eventHandler.getWtEventHandler();
int ret = wiredtiger_open(path.c_str(), wtEventHandler, configStr.c_str(), &_conn);
if (!ret) {
_fileVersion = {WiredTigerFileVersion::StartupVersion::IS_42};
return;
}
// Arbiters do not replicate the FCV document. Due to arbiter FCV semantics on 4.0, shutting
// down a 4.0 arbiter may either downgrade the data files to WT compatibility 2.9 or 3.0. Thus,
// 4.2 binaries must allow starting up on 2.9 and 3.0 files.
configStr = wtOpenConfig + ",compatibility=(require_min=\"3.0.0\")";
ret = wiredtiger_open(path.c_str(), wtEventHandler, configStr.c_str(), &_conn);
if (!ret) {
_fileVersion = {WiredTigerFileVersion::StartupVersion::IS_36};
return;
}
configStr = wtOpenConfig + ",compatibility=(require_min=\"2.9.0\")";
ret = wiredtiger_open(path.c_str(), wtEventHandler, configStr.c_str(), &_conn);
if (!ret) {
_fileVersion = {WiredTigerFileVersion::StartupVersion::IS_34};
return;
}
warning() << "Failed to start up WiredTiger under any compatibility version.";
if (ret == EINVAL) {
fassertFailedNoTrace(28561);
}
if (ret == WT_TRY_SALVAGE) {
warning() << "WiredTiger metadata corruption detected";
if (!_inRepairMode) {
severe() << kWTRepairMsg;
fassertFailedNoTrace(50944);
}
}
severe() << "Reason: " << wtRCToStatus(ret).reason();
if (!_inRepairMode) {
fassertFailedNoTrace(28595);
}
// Always attempt to salvage metadata regardless of error code when in repair mode.
warning() << "Attempting to salvage WiredTiger metadata";
configStr = wtOpenConfig + ",salvage=true";
ret = wiredtiger_open(path.c_str(), wtEventHandler, configStr.c_str(), &_conn);
if (!ret) {
StorageRepairObserver::get(getGlobalServiceContext())
->invalidatingModification("WiredTiger metadata salvaged");
return;
}
severe() << "Failed to salvage WiredTiger metadata: " + wtRCToStatus(ret).reason();
fassertFailedNoTrace(50947);
}
void WiredTigerKVEngine::cleanShutdown() {
log() << "WiredTigerKVEngine shutting down";
if (!_readOnly)
syncSizeInfo(true);
if (!_conn) {
return;
}
// these must be the last things we do before _conn->close();
if (_sessionSweeper) {
log() << "Shutting down session sweeper thread";
_sessionSweeper->shutdown();
log() << "Finished shutting down session sweeper thread";
}
if (_journalFlusher) {
log() << "Shutting down journal flusher thread";
_journalFlusher->shutdown();
log() << "Finished shutting down journal flusher thread";
}
if (_checkpointThread) {
log() << "Shutting down checkpoint thread";
_checkpointThread->shutdown();
log() << "Finished shutting down checkpoint thread";
}
LOG_FOR_RECOVERY(2) << "Shutdown timestamps. StableTimestamp: " << _stableTimestamp.load()
<< " Initial data timestamp: " << _initialDataTimestamp.load();
_sizeStorer.reset();
_sessionCache->shuttingDown();
// We want WiredTiger to leak memory for faster shutdown except when we are running tools to look
// for memory leaks.
#if !__has_feature(address_sanitizer)
bool leak_memory = true;
#else
bool leak_memory = false;
#endif
std::string closeConfig = "";
if (RUNNING_ON_VALGRIND) {
leak_memory = false;
}
if (leak_memory) {
closeConfig = "leak_memory=true,";
}
if (_fileVersion.shouldDowngrade(_readOnly, _inRepairMode, !_recoveryTimestamp.isNull())) {
log() << "Downgrading WiredTiger datafiles.";
invariantWTOK(_conn->close(_conn, closeConfig.c_str()));
invariantWTOK(wiredtiger_open(
_path.c_str(), _eventHandler.getWtEventHandler(), _wtOpenConfig.c_str(), &_conn));
LOG(1) << "Downgrade compatibility configuration: " << _fileVersion.getDowngradeString();
invariantWTOK(_conn->reconfigure(_conn, _fileVersion.getDowngradeString().c_str()));
}
if (gTakeUnstableCheckpointOnShutdown) {
closeConfig += "use_timestamp=false,";
}
invariantWTOK(_conn->close(_conn, closeConfig.c_str()));
_conn = nullptr;
}
Status WiredTigerKVEngine::okToRename(OperationContext* opCtx,
StringData fromNS,
StringData toNS,
StringData ident,
const RecordStore* originalRecordStore) const {
syncSizeInfo(false);
return Status::OK();
}
int64_t WiredTigerKVEngine::getIdentSize(OperationContext* opCtx, StringData ident) {
WiredTigerSession* session = WiredTigerRecoveryUnit::get(opCtx)->getSession();
return WiredTigerUtil::getIdentSize(session->getSession(), _uri(ident));
}
Status WiredTigerKVEngine::repairIdent(OperationContext* opCtx, StringData ident) {
WiredTigerSession* session = WiredTigerRecoveryUnit::get(opCtx)->getSession();
string uri = _uri(ident);
session->closeAllCursors(uri);
_sessionCache->closeAllCursors(uri);
if (isEphemeral()) {
return Status::OK();
}
_ensureIdentPath(ident);
return _salvageIfNeeded(uri.c_str());
}
Status WiredTigerKVEngine::_salvageIfNeeded(const char* uri) {