-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathdb_stress_test_base.cc
4411 lines (4095 loc) · 170 KB
/
db_stress_test_base.cc
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) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
#include <ios>
#include <thread>
#include "db_stress_tool/db_stress_listener.h"
#include "rocksdb/io_status.h"
#include "rocksdb/options.h"
#include "rocksdb/slice_transform.h"
#include "util/compression.h"
#ifdef GFLAGS
#include "db_stress_tool/db_stress_common.h"
#include "db_stress_tool/db_stress_compaction_filter.h"
#include "db_stress_tool/db_stress_compaction_service.h"
#include "db_stress_tool/db_stress_driver.h"
#include "db_stress_tool/db_stress_filters.h"
#include "db_stress_tool/db_stress_table_properties_collector.h"
#include "db_stress_tool/db_stress_wide_merge_operator.h"
#include "options/options_parser.h"
#include "rocksdb/convenience.h"
#include "rocksdb/filter_policy.h"
#include "rocksdb/secondary_cache.h"
#include "rocksdb/sst_file_manager.h"
#include "rocksdb/types.h"
#include "rocksdb/utilities/object_registry.h"
#include "rocksdb/utilities/write_batch_with_index.h"
#include "test_util/testutil.h"
#include "util/cast_util.h"
#include "utilities/backup/backup_engine_impl.h"
#include "utilities/fault_injection_fs.h"
#include "utilities/fault_injection_secondary_cache.h"
namespace ROCKSDB_NAMESPACE {
namespace {
std::shared_ptr<const FilterPolicy> CreateFilterPolicy() {
if (FLAGS_bloom_bits < 0) {
return BlockBasedTableOptions().filter_policy;
}
const FilterPolicy* new_policy;
if (FLAGS_bloom_before_level == INT_MAX) {
// Use Bloom API
new_policy = NewBloomFilterPolicy(FLAGS_bloom_bits, false);
} else {
new_policy =
NewRibbonFilterPolicy(FLAGS_bloom_bits, FLAGS_bloom_before_level);
}
return std::shared_ptr<const FilterPolicy>(new_policy);
}
} // namespace
StressTest::StressTest()
: cache_(NewCache(FLAGS_cache_size, FLAGS_cache_numshardbits)),
filter_policy_(CreateFilterPolicy()),
db_(nullptr),
txn_db_(nullptr),
optimistic_txn_db_(nullptr),
db_aptr_(nullptr),
clock_(db_stress_env->GetSystemClock().get()),
new_column_family_name_(1),
num_times_reopened_(0),
db_preload_finished_(false),
secondary_db_(nullptr),
is_db_stopped_(false) {
if (FLAGS_destroy_db_initially) {
std::vector<std::string> files;
db_stress_env->GetChildren(FLAGS_db, &files);
for (unsigned int i = 0; i < files.size(); i++) {
if (Slice(files[i]).starts_with("heap-")) {
db_stress_env->DeleteFile(FLAGS_db + "/" + files[i]);
}
}
Options options;
options.env = db_stress_env;
// Remove files without preserving manfiest files
const Status s = !FLAGS_use_blob_db
? DestroyDB(FLAGS_db, options)
: blob_db::DestroyBlobDB(FLAGS_db, options,
blob_db::BlobDBOptions());
if (!s.ok()) {
fprintf(stderr, "Cannot destroy original db: %s\n", s.ToString().c_str());
exit(1);
}
}
Status s = DbStressSqfcManager().MakeSharedFactory(
FLAGS_sqfc_name, FLAGS_sqfc_version, &sqfc_factory_);
if (!s.ok()) {
fprintf(stderr, "Error initializing SstQueryFilterConfig: %s\n",
s.ToString().c_str());
exit(1);
}
}
void StressTest::CleanUp() {
CleanUpColumnFamilies();
if (db_) {
db_->Close();
}
delete db_;
db_ = nullptr;
delete secondary_db_;
secondary_db_ = nullptr;
}
void StressTest::CleanUpColumnFamilies() {
for (auto cf : column_families_) {
delete cf;
}
column_families_.clear();
for (auto* cf : secondary_cfhs_) {
delete cf;
}
secondary_cfhs_.clear();
}
std::shared_ptr<Cache> StressTest::NewCache(size_t capacity,
int32_t num_shard_bits) {
ConfigOptions config_options;
if (capacity <= 0) {
return nullptr;
}
std::shared_ptr<SecondaryCache> secondary_cache;
if (!FLAGS_secondary_cache_uri.empty()) {
assert(!strstr(FLAGS_secondary_cache_uri.c_str(),
"compressed_secondary_cache") ||
(FLAGS_compressed_secondary_cache_size == 0 &&
FLAGS_compressed_secondary_cache_ratio == 0.0 &&
!StartsWith(FLAGS_cache_type, "tiered_")));
Status s = SecondaryCache::CreateFromString(
config_options, FLAGS_secondary_cache_uri, &secondary_cache);
if (secondary_cache == nullptr) {
fprintf(stderr,
"No secondary cache registered matching string: %s status=%s\n",
FLAGS_secondary_cache_uri.c_str(), s.ToString().c_str());
exit(1);
}
if (FLAGS_secondary_cache_fault_one_in > 0) {
secondary_cache = std::make_shared<FaultInjectionSecondaryCache>(
secondary_cache, static_cast<uint32_t>(FLAGS_seed),
FLAGS_secondary_cache_fault_one_in);
}
} else if (FLAGS_compressed_secondary_cache_size > 0) {
if (StartsWith(FLAGS_cache_type, "tiered_")) {
fprintf(stderr,
"Cannot specify both compressed_secondary_cache_size and %s\n",
FLAGS_cache_type.c_str());
exit(1);
}
CompressedSecondaryCacheOptions opts;
opts.capacity = FLAGS_compressed_secondary_cache_size;
opts.compress_format_version = FLAGS_compress_format_version;
if (FLAGS_enable_do_not_compress_roles) {
opts.do_not_compress_roles = {CacheEntryRoleSet::All()};
}
opts.enable_custom_split_merge = FLAGS_enable_custom_split_merge;
secondary_cache = NewCompressedSecondaryCache(opts);
if (secondary_cache == nullptr) {
fprintf(stderr, "Failed to allocate compressed secondary cache\n");
exit(1);
}
compressed_secondary_cache = secondary_cache;
}
std::string cache_type = FLAGS_cache_type;
size_t cache_size = FLAGS_cache_size;
bool tiered = false;
if (StartsWith(cache_type, "tiered_")) {
tiered = true;
cache_type.erase(0, strlen("tiered_"));
}
if (FLAGS_use_write_buffer_manager) {
cache_size += FLAGS_db_write_buffer_size;
}
if (cache_type == "clock_cache") {
fprintf(stderr, "Old clock cache implementation has been removed.\n");
exit(1);
} else if (EndsWith(cache_type, "hyper_clock_cache")) {
size_t estimated_entry_charge;
if (cache_type == "fixed_hyper_clock_cache" ||
cache_type == "hyper_clock_cache") {
estimated_entry_charge = FLAGS_block_size;
} else if (cache_type == "auto_hyper_clock_cache") {
estimated_entry_charge = 0;
} else {
fprintf(stderr, "Cache type not supported.");
exit(1);
}
HyperClockCacheOptions opts(cache_size, estimated_entry_charge,
num_shard_bits);
opts.hash_seed = BitwiseAnd(FLAGS_seed, INT32_MAX);
if (tiered) {
TieredCacheOptions tiered_opts;
tiered_opts.cache_opts = &opts;
tiered_opts.cache_type = PrimaryCacheType::kCacheTypeHCC;
tiered_opts.total_capacity = cache_size;
tiered_opts.compressed_secondary_ratio = 0.5;
tiered_opts.adm_policy =
static_cast<TieredAdmissionPolicy>(FLAGS_adm_policy);
if (tiered_opts.adm_policy ==
TieredAdmissionPolicy::kAdmPolicyThreeQueue) {
CompressedSecondaryCacheOptions nvm_sec_cache_opts;
nvm_sec_cache_opts.capacity = cache_size;
tiered_opts.nvm_sec_cache =
NewCompressedSecondaryCache(nvm_sec_cache_opts);
}
block_cache = NewTieredCache(tiered_opts);
} else {
opts.secondary_cache = std::move(secondary_cache);
block_cache = opts.MakeSharedCache();
}
} else if (EndsWith(cache_type, "lru_cache")) {
LRUCacheOptions opts;
opts.capacity = capacity;
opts.num_shard_bits = num_shard_bits;
opts.metadata_charge_policy =
static_cast<CacheMetadataChargePolicy>(FLAGS_metadata_charge_policy);
opts.use_adaptive_mutex = FLAGS_use_adaptive_mutex_lru;
opts.high_pri_pool_ratio = FLAGS_high_pri_pool_ratio;
opts.low_pri_pool_ratio = FLAGS_low_pri_pool_ratio;
if (tiered) {
TieredCacheOptions tiered_opts;
tiered_opts.cache_opts = &opts;
tiered_opts.cache_type = PrimaryCacheType::kCacheTypeLRU;
tiered_opts.total_capacity = cache_size;
tiered_opts.compressed_secondary_ratio = 0.5;
tiered_opts.adm_policy =
static_cast<TieredAdmissionPolicy>(FLAGS_adm_policy);
if (tiered_opts.adm_policy ==
TieredAdmissionPolicy::kAdmPolicyThreeQueue) {
CompressedSecondaryCacheOptions nvm_sec_cache_opts;
nvm_sec_cache_opts.capacity = cache_size;
tiered_opts.nvm_sec_cache =
NewCompressedSecondaryCache(nvm_sec_cache_opts);
}
block_cache = NewTieredCache(tiered_opts);
} else {
opts.secondary_cache = std::move(secondary_cache);
block_cache = NewLRUCache(opts);
}
} else {
fprintf(stderr, "Cache type not supported.");
exit(1);
}
return block_cache;
}
std::vector<std::string> StressTest::GetBlobCompressionTags() {
std::vector<std::string> compression_tags{"kNoCompression"};
if (Snappy_Supported()) {
compression_tags.emplace_back("kSnappyCompression");
}
if (LZ4_Supported()) {
compression_tags.emplace_back("kLZ4Compression");
}
if (ZSTD_Supported()) {
compression_tags.emplace_back("kZSTD");
}
return compression_tags;
}
bool StressTest::BuildOptionsTable() {
if (FLAGS_set_options_one_in <= 0) {
return true;
}
bool keepRibbonFilterPolicyOnly = FLAGS_bloom_before_level != INT_MAX;
std::unordered_map<std::string, std::vector<std::string>> options_tbl = {
{"write_buffer_size",
{std::to_string(options_.write_buffer_size),
std::to_string(options_.write_buffer_size * 2),
std::to_string(options_.write_buffer_size * 4)}},
{"max_write_buffer_number",
{std::to_string(options_.max_write_buffer_number),
std::to_string(options_.max_write_buffer_number * 2),
std::to_string(options_.max_write_buffer_number * 4)}},
{"arena_block_size",
{
std::to_string(options_.arena_block_size),
std::to_string(options_.write_buffer_size / 4),
std::to_string(options_.write_buffer_size / 8),
}},
{"memtable_huge_page_size", {"0", std::to_string(2 * 1024 * 1024)}},
{"strict_max_successive_merges", {"false", "true"}},
{"inplace_update_num_locks", {"100", "200", "300"}},
// TODO: re-enable once internal task T124324915 is fixed.
// {"experimental_mempurge_threshold", {"0.0", "1.0"}},
// TODO(ljin): enable test for this option
// {"disable_auto_compactions", {"100", "200", "300"}},
{"level0_slowdown_writes_trigger",
{
std::to_string(options_.level0_slowdown_writes_trigger),
std::to_string(options_.level0_slowdown_writes_trigger + 2),
std::to_string(options_.level0_slowdown_writes_trigger + 4),
}},
{"level0_stop_writes_trigger",
{
std::to_string(options_.level0_stop_writes_trigger),
std::to_string(options_.level0_stop_writes_trigger + 2),
std::to_string(options_.level0_stop_writes_trigger + 4),
}},
{"max_compaction_bytes",
{
std::to_string(options_.target_file_size_base * 5),
std::to_string(options_.target_file_size_base * 15),
std::to_string(options_.target_file_size_base * 100),
}},
{"target_file_size_base",
{
std::to_string(options_.target_file_size_base),
std::to_string(options_.target_file_size_base * 2),
std::to_string(options_.target_file_size_base * 4),
}},
{"target_file_size_multiplier",
{
std::to_string(options_.target_file_size_multiplier),
"1",
"2",
}},
{"max_bytes_for_level_base",
{
std::to_string(options_.max_bytes_for_level_base / 2),
std::to_string(options_.max_bytes_for_level_base),
std::to_string(options_.max_bytes_for_level_base * 2),
}},
{"max_bytes_for_level_multiplier",
{
std::to_string(options_.max_bytes_for_level_multiplier),
"1",
"2",
}},
{"max_sequential_skip_in_iterations", {"4", "8", "12"}},
{"block_based_table_factory",
{
keepRibbonFilterPolicyOnly ? "{filter_policy=ribbonfilter:2.35}"
: "{filter_policy=bloomfilter:2.34}",
"{filter_policy=ribbonfilter:5.67:-1}",
keepRibbonFilterPolicyOnly ? "{filter_policy=ribbonfilter:8.9:3}"
: "{filter_policy=nullptr}",
"{block_size=" + std::to_string(FLAGS_block_size) + "}",
"{block_size=" +
std::to_string(FLAGS_block_size + (FLAGS_seed & 0xFFFU)) + "}",
}},
};
if (FLAGS_compaction_style == kCompactionStyleUniversal &&
FLAGS_universal_max_read_amp > 0) {
// level0_file_num_compaction_trigger needs to be at most max_read_amp
options_tbl.emplace(
"level0_file_num_compaction_trigger",
std::vector<std::string>{
std::to_string(options_.level0_file_num_compaction_trigger),
std::to_string(
std::min(options_.level0_file_num_compaction_trigger + 2,
FLAGS_universal_max_read_amp)),
std::to_string(
std::min(options_.level0_file_num_compaction_trigger + 4,
FLAGS_universal_max_read_amp)),
});
} else {
options_tbl.emplace(
"level0_file_num_compaction_trigger",
std::vector<std::string>{
std::to_string(options_.level0_file_num_compaction_trigger),
std::to_string(options_.level0_file_num_compaction_trigger + 2),
std::to_string(options_.level0_file_num_compaction_trigger + 4),
});
}
if (FLAGS_unordered_write) {
options_tbl.emplace("max_successive_merges", std::vector<std::string>{"0"});
} else {
options_tbl.emplace("max_successive_merges",
std::vector<std::string>{"0", "2", "4"});
}
if (FLAGS_allow_setting_blob_options_dynamically) {
options_tbl.emplace("enable_blob_files",
std::vector<std::string>{"false", "true"});
options_tbl.emplace("min_blob_size",
std::vector<std::string>{"0", "8", "16"});
options_tbl.emplace("blob_file_size",
std::vector<std::string>{"1M", "16M", "256M", "1G"});
options_tbl.emplace("blob_compression_type", GetBlobCompressionTags());
options_tbl.emplace("enable_blob_garbage_collection",
std::vector<std::string>{"false", "true"});
options_tbl.emplace(
"blob_garbage_collection_age_cutoff",
std::vector<std::string>{"0.0", "0.25", "0.5", "0.75", "1.0"});
options_tbl.emplace("blob_garbage_collection_force_threshold",
std::vector<std::string>{"0.5", "0.75", "1.0"});
options_tbl.emplace("blob_compaction_readahead_size",
std::vector<std::string>{"0", "1M", "4M"});
options_tbl.emplace("blob_file_starting_level",
std::vector<std::string>{"0", "1", "2"});
options_tbl.emplace("prepopulate_blob_cache",
std::vector<std::string>{"kDisable", "kFlushOnly"});
}
if (keepRibbonFilterPolicyOnly) {
// Can modify RibbonFilterPolicy field
options_tbl.emplace("table_factory.filter_policy.bloom_before_level",
std::vector<std::string>{"-1", "0", "1", "2",
"2147483646", "2147483647"});
}
if (!FLAGS_file_temperature_age_thresholds.empty()) {
// Modify file_temperature_age_thresholds only if it is set initially
// (FIFO tiered storage setup)
options_tbl.emplace(
"file_temperature_age_thresholds",
std::vector<std::string>{
"{{temperature=kWarm;age=30}:{temperature=kCold;age=300}}",
"{{temperature=kCold;age=100}}", "{}"});
}
// NOTE: allow -1 to mean starting disabled but dynamically changing
// But 0 means tiering is disabled for the entire run.
if (FLAGS_preclude_last_level_data_seconds != 0) {
options_tbl.emplace("preclude_last_level_data_seconds",
std::vector<std::string>{"0", "5", "30", "5000"});
}
options_tbl.emplace("preserve_internal_time_seconds",
std::vector<std::string>{"0", "5", "30", "5000"});
options_table_ = std::move(options_tbl);
for (const auto& iter : options_table_) {
options_index_.push_back(iter.first);
}
return true;
}
void StressTest::InitDb(SharedState* shared) {
uint64_t now = clock_->NowMicros();
fprintf(stdout, "%s Initializing db_stress\n",
clock_->TimeToString(now / 1000000).c_str());
PrintEnv();
Open(shared);
BuildOptionsTable();
}
void StressTest::FinishInitDb(SharedState* shared) {
if (FLAGS_read_only) {
uint64_t now = clock_->NowMicros();
fprintf(stdout, "%s Preloading db with %" PRIu64 " KVs\n",
clock_->TimeToString(now / 1000000).c_str(), FLAGS_max_key);
PreloadDbAndReopenAsReadOnly(FLAGS_max_key, shared);
}
if (shared->HasHistory()) {
// The way it works right now is, if there's any history, that means the
// previous run mutating the DB had all its operations traced, in which case
// we should always be able to `Restore()` the expected values to match the
// `db_`'s current seqno.
Status s = shared->Restore(db_);
if (!s.ok()) {
fprintf(stderr, "Error restoring historical expected values: %s\n",
s.ToString().c_str());
exit(1);
}
}
if (FLAGS_use_txn && !FLAGS_use_optimistic_txn) {
// It's OK here without sync because unsynced data cannot be lost at this
// point
// - even with sync_fault_injection=1 as the
// file is still directly writable until after FinishInitDb()
ProcessRecoveredPreparedTxns(shared);
}
if (FLAGS_enable_compaction_filter) {
auto* compaction_filter_factory =
static_cast<DbStressCompactionFilterFactory*>(
options_.compaction_filter_factory.get());
assert(compaction_filter_factory);
// This must be called only after any potential `SharedState::Restore()` has
// completed in order for the `compaction_filter_factory` to operate on the
// correct latest values file.
compaction_filter_factory->SetSharedState(shared);
fprintf(stdout, "Compaction filter factory: %s\n",
compaction_filter_factory->Name());
}
}
void StressTest::TrackExpectedState(SharedState* shared) {
// When data loss is simulated, recovery from potential data loss is a prefix
// recovery that requires tracing
if (MightHaveUnsyncedDataLoss() && IsStateTracked()) {
Status s = shared->SaveAtAndAfter(db_);
if (!s.ok()) {
fprintf(stderr, "Error enabling history tracing: %s\n",
s.ToString().c_str());
exit(1);
}
}
}
Status StressTest::AssertSame(DB* db, ColumnFamilyHandle* cf,
ThreadState::SnapshotState& snap_state) {
Status s;
if (cf->GetName() != snap_state.cf_at_name) {
return s;
}
// This `ReadOptions` is for validation purposes. Ignore
// `FLAGS_rate_limit_user_ops` to avoid slowing any validation.
ReadOptions ropt;
ropt.snapshot = snap_state.snapshot;
ropt.auto_refresh_iterator_with_snapshot =
FLAGS_auto_refresh_iterator_with_snapshot;
Slice ts;
if (!snap_state.timestamp.empty()) {
ts = snap_state.timestamp;
ropt.timestamp = &ts;
}
PinnableSlice exp_v(&snap_state.value);
exp_v.PinSelf();
PinnableSlice v;
s = db->Get(ropt, cf, snap_state.key, &v);
if (!s.ok() && !s.IsNotFound()) {
// When `persist_user_defined_timestamps` is false, a repeated read with
// both a read timestamp and an explicitly taken snapshot cannot guarantee
// consistent result all the time. When it cannot return consistent result,
// it will return an `InvalidArgument` status.
if (s.IsInvalidArgument() && !FLAGS_persist_user_defined_timestamps) {
return Status::OK();
}
return s;
}
if (snap_state.status != s) {
return Status::Corruption(
"The snapshot gave inconsistent results for key " +
std::to_string(Hash(snap_state.key.c_str(), snap_state.key.size(), 0)) +
" in cf " + cf->GetName() + ": (" + snap_state.status.ToString() +
") vs. (" + s.ToString() + ")");
}
if (s.ok()) {
if (exp_v != v) {
return Status::Corruption("The snapshot gave inconsistent values: (" +
exp_v.ToString() + ") vs. (" + v.ToString() +
")");
}
}
if (snap_state.key_vec != nullptr) {
// When `prefix_extractor` is set, seeking to beginning and scanning
// across prefixes are only supported with `total_order_seek` set.
ropt.total_order_seek = true;
std::unique_ptr<Iterator> iterator(db->NewIterator(ropt));
std::unique_ptr<std::vector<bool>> tmp_bitvec(
new std::vector<bool>(FLAGS_max_key));
for (iterator->SeekToFirst(); iterator->Valid(); iterator->Next()) {
uint64_t key_val;
if (GetIntVal(iterator->key().ToString(), &key_val)) {
(*tmp_bitvec.get())[key_val] = true;
}
}
if (!std::equal(snap_state.key_vec->begin(), snap_state.key_vec->end(),
tmp_bitvec.get()->begin())) {
return Status::Corruption("Found inconsistent keys at this snapshot");
}
}
return Status::OK();
}
void StressTest::ProcessStatus(SharedState* shared, std::string opname,
const Status& s,
bool ignore_injected_error) const {
if (s.ok()) {
return;
}
if (!ignore_injected_error || !IsErrorInjectedAndRetryable(s)) {
std::ostringstream oss;
oss << opname << " failed: " << s.ToString();
VerificationAbort(shared, oss.str());
assert(false);
}
}
void StressTest::VerificationAbort(SharedState* shared, std::string msg) const {
fprintf(stderr, "Verification failed: %s\n", msg.c_str());
shared->SetVerificationFailure();
}
void StressTest::VerificationAbort(SharedState* shared, std::string msg, int cf,
int64_t key) const {
auto key_str = Key(key);
Slice key_slice = key_str;
fprintf(stderr,
"Verification failed for column family %d key %s (%" PRIi64 "): %s\n",
cf, key_slice.ToString(true).c_str(), key, msg.c_str());
shared->SetVerificationFailure();
}
void StressTest::VerificationAbort(SharedState* shared, std::string msg, int cf,
int64_t key, Slice value_from_db,
Slice value_from_expected) const {
auto key_str = Key(key);
fprintf(stderr,
"Verification failed for column family %d key %s (%" PRIi64
"): value_from_db: %s, value_from_expected: %s, msg: %s\n",
cf, Slice(key_str).ToString(true).c_str(), key,
value_from_db.ToString(true).c_str(),
value_from_expected.ToString(true).c_str(), msg.c_str());
shared->SetVerificationFailure();
}
void StressTest::VerificationAbort(SharedState* shared, int cf, int64_t key,
const Slice& value,
const WideColumns& columns) const {
assert(shared);
auto key_str = Key(key);
fprintf(stderr,
"Verification failed for column family %d key %s (%" PRIi64
"): Value and columns inconsistent: value: %s, columns: %s\n",
cf, Slice(key_str).ToString(/* hex */ true).c_str(), key,
value.ToString(/* hex */ true).c_str(),
WideColumnsToHex(columns).c_str());
shared->SetVerificationFailure();
}
std::string StressTest::DebugString(const Slice& value,
const WideColumns& columns) {
std::ostringstream oss;
oss << "value: " << value.ToString(/* hex */ true)
<< ", columns: " << WideColumnsToHex(columns);
return oss.str();
}
void StressTest::PrintStatistics() {
if (dbstats) {
fprintf(stdout, "STATISTICS:\n%s\n", dbstats->ToString().c_str());
}
if (dbstats_secondaries) {
fprintf(stdout, "Secondary instances STATISTICS:\n%s\n",
dbstats_secondaries->ToString().c_str());
}
}
// Currently PreloadDb has to be single-threaded.
void StressTest::PreloadDbAndReopenAsReadOnly(int64_t number_of_keys,
SharedState* shared) {
WriteOptions write_opts;
write_opts.disableWAL = FLAGS_disable_wal;
if (FLAGS_sync) {
write_opts.sync = true;
}
if (FLAGS_rate_limit_auto_wal_flush) {
write_opts.rate_limiter_priority = Env::IO_USER;
}
char value[100];
int cf_idx = 0;
Status s;
for (auto cfh : column_families_) {
for (int64_t k = 0; k != number_of_keys; ++k) {
const std::string key = Key(k);
PendingExpectedValue pending_expected_value =
shared->PreparePut(cf_idx, k);
const uint32_t value_base = pending_expected_value.GetFinalValueBase();
const size_t sz = GenerateValue(value_base, value, sizeof(value));
const Slice v(value, sz);
std::string ts;
if (FLAGS_user_timestamp_size > 0) {
ts = GetNowNanos();
}
if (FLAGS_use_put_entity_one_in > 0 &&
(value_base % FLAGS_use_put_entity_one_in) == 0) {
if (!FLAGS_use_txn) {
if (FLAGS_use_attribute_group) {
s = db_->PutEntity(write_opts, key,
GenerateAttributeGroups({cfh}, value_base, v));
} else {
s = db_->PutEntity(write_opts, cfh, key,
GenerateWideColumns(value_base, v));
}
} else {
s = ExecuteTransaction(
write_opts, /*thread=*/nullptr, [&](Transaction& txn) {
return txn.PutEntity(cfh, key,
GenerateWideColumns(value_base, v));
});
}
} else if (FLAGS_use_merge) {
if (!FLAGS_use_txn) {
if (FLAGS_user_timestamp_size > 0) {
s = db_->Merge(write_opts, cfh, key, ts, v);
} else {
s = db_->Merge(write_opts, cfh, key, v);
}
} else {
s = ExecuteTransaction(
write_opts, /*thread=*/nullptr,
[&](Transaction& txn) { return txn.Merge(cfh, key, v); });
}
} else {
if (!FLAGS_use_txn) {
if (FLAGS_user_timestamp_size > 0) {
s = db_->Put(write_opts, cfh, key, ts, v);
} else {
s = db_->Put(write_opts, cfh, key, v);
}
} else {
s = ExecuteTransaction(
write_opts, /*thread=*/nullptr,
[&](Transaction& txn) { return txn.Put(cfh, key, v); });
}
}
if (!s.ok()) {
pending_expected_value.Rollback();
break;
}
pending_expected_value.Commit();
}
if (!s.ok()) {
break;
}
++cf_idx;
}
if (s.ok()) {
s = db_->Flush(FlushOptions(), column_families_);
}
if (s.ok()) {
CleanUpColumnFamilies();
delete db_;
db_ = nullptr;
txn_db_ = nullptr;
optimistic_txn_db_ = nullptr;
delete secondary_db_;
secondary_db_ = nullptr;
db_preload_finished_.store(true);
auto now = clock_->NowMicros();
fprintf(stdout, "%s Reopening database in read-only\n",
clock_->TimeToString(now / 1000000).c_str());
// Reopen as read-only, can ignore all options related to updates
Open(shared);
} else {
fprintf(stderr, "Failed to preload db");
exit(1);
}
}
Status StressTest::SetOptions(ThreadState* thread) {
assert(FLAGS_set_options_one_in > 0);
std::unordered_map<std::string, std::string> opts;
std::string name =
options_index_[thread->rand.Next() % options_index_.size()];
int value_idx = thread->rand.Next() % options_table_[name].size();
if (name == "level0_file_num_compaction_trigger" ||
name == "level0_slowdown_writes_trigger" ||
name == "level0_stop_writes_trigger") {
opts["level0_file_num_compaction_trigger"] =
options_table_["level0_file_num_compaction_trigger"][value_idx];
opts["level0_slowdown_writes_trigger"] =
options_table_["level0_slowdown_writes_trigger"][value_idx];
opts["level0_stop_writes_trigger"] =
options_table_["level0_stop_writes_trigger"][value_idx];
} else {
opts[name] = options_table_[name][value_idx];
}
int rand_cf_idx = thread->rand.Next() % FLAGS_column_families;
auto cfh = column_families_[rand_cf_idx];
return db_->SetOptions(cfh, opts);
}
void StressTest::ProcessRecoveredPreparedTxns(SharedState* shared) {
assert(txn_db_);
std::vector<Transaction*> recovered_prepared_trans;
txn_db_->GetAllPreparedTransactions(&recovered_prepared_trans);
for (Transaction* txn : recovered_prepared_trans) {
ProcessRecoveredPreparedTxnsHelper(txn, shared);
delete txn;
}
recovered_prepared_trans.clear();
txn_db_->GetAllPreparedTransactions(&recovered_prepared_trans);
assert(recovered_prepared_trans.size() == 0);
}
void StressTest::ProcessRecoveredPreparedTxnsHelper(Transaction* txn,
SharedState* shared) {
thread_local Random rand(static_cast<uint32_t>(FLAGS_seed));
for (size_t i = 0; i < column_families_.size(); ++i) {
std::unique_ptr<WBWIIterator> wbwi_iter(
txn->GetWriteBatch()->NewIterator(column_families_[i]));
for (wbwi_iter->SeekToFirst(); wbwi_iter->Valid(); wbwi_iter->Next()) {
uint64_t key_val;
if (GetIntVal(wbwi_iter->Entry().key.ToString(), &key_val)) {
shared->SyncPendingPut(static_cast<int>(i) /* cf_idx */, key_val);
}
}
}
if (rand.OneIn(2)) {
Status s = txn->Commit();
assert(s.ok());
} else {
Status s = txn->Rollback();
assert(s.ok());
}
}
Status StressTest::NewTxn(WriteOptions& write_opts, ThreadState* thread,
std::unique_ptr<Transaction>* out_txn,
bool* commit_bypass_memtable) {
if (!FLAGS_use_txn) {
return Status::InvalidArgument("NewTxn when FLAGS_use_txn is not set");
}
write_opts.disableWAL = FLAGS_disable_wal;
static std::atomic<uint64_t> txn_id = {0};
if (FLAGS_use_optimistic_txn) {
out_txn->reset(optimistic_txn_db_->BeginTransaction(write_opts));
return Status::OK();
} else {
TransactionOptions txn_options;
txn_options.use_only_the_last_commit_time_batch_for_recovery =
FLAGS_use_only_the_last_commit_time_batch_for_recovery;
txn_options.lock_timeout = 600000; // 10 min
txn_options.deadlock_detect = true;
if (FLAGS_commit_bypass_memtable_one_in > 0) {
assert(FLAGS_txn_write_policy == 0);
assert(FLAGS_user_timestamp_size == 0);
txn_options.commit_bypass_memtable =
thread->rand.OneIn(FLAGS_commit_bypass_memtable_one_in);
if (commit_bypass_memtable) {
*commit_bypass_memtable = txn_options.commit_bypass_memtable;
}
}
out_txn->reset(txn_db_->BeginTransaction(write_opts, txn_options));
auto istr = std::to_string(txn_id.fetch_add(1));
Status s = (*out_txn)->SetName("xid" + istr);
return s;
}
}
Status StressTest::CommitTxn(Transaction& txn, ThreadState* thread) {
if (!FLAGS_use_txn) {
return Status::InvalidArgument("CommitTxn when FLAGS_use_txn is not set");
}
Status s = Status::OK();
if (FLAGS_use_optimistic_txn) {
assert(optimistic_txn_db_);
s = txn.Commit();
} else {
assert(txn_db_);
s = txn.Prepare();
std::shared_ptr<const Snapshot> timestamped_snapshot;
if (s.ok()) {
if (thread && FLAGS_create_timestamped_snapshot_one_in &&
thread->rand.OneIn(FLAGS_create_timestamped_snapshot_one_in)) {
uint64_t ts = db_stress_env->NowNanos();
s = txn.CommitAndTryCreateSnapshot(/*notifier=*/nullptr, ts,
×tamped_snapshot);
std::pair<Status, std::shared_ptr<const Snapshot>> res;
if (thread->tid == 0) {
uint64_t now = db_stress_env->NowNanos();
res = txn_db_->CreateTimestampedSnapshot(now);
if (res.first.ok()) {
assert(res.second);
assert(res.second->GetTimestamp() == now);
if (timestamped_snapshot) {
assert(res.second->GetTimestamp() >
timestamped_snapshot->GetTimestamp());
}
} else {
assert(!res.second);
}
}
} else {
s = txn.Commit();
}
}
if (thread && FLAGS_create_timestamped_snapshot_one_in > 0 &&
thread->rand.OneInOpt(50000)) {
uint64_t now = db_stress_env->NowNanos();
constexpr uint64_t time_diff = static_cast<uint64_t>(1000) * 1000 * 1000;
txn_db_->ReleaseTimestampedSnapshotsOlderThan(now - time_diff);
}
}
return s;
}
Status StressTest::ExecuteTransaction(WriteOptions& write_opts,
ThreadState* thread,
std::function<Status(Transaction&)>&& ops,
bool* commit_bypass_memtable) {
std::unique_ptr<Transaction> txn;
Status s = NewTxn(write_opts, thread, &txn, commit_bypass_memtable);
std::string try_again_messages;
if (s.ok()) {
for (int tries = 1;; ++tries) {
s = ops(*txn);
if (s.ok()) {
s = CommitTxn(*txn, thread);
if (s.ok()) {
break;
}
}
// Optimistic txn might return TryAgain, in which case rollback
// and try again.
if (!s.IsTryAgain() || !FLAGS_use_optimistic_txn) {
break;
}
// Record and report historical TryAgain messages for debugging
try_again_messages +=
std::to_string(SystemClock::Default()->NowMicros() / 1000);
try_again_messages += "ms ";
try_again_messages += s.getState();
try_again_messages += "\n";
// In theory, each Rollback after TryAgain should have an independent
// chance of success, so too many retries could indicate something is
// not working properly.
if (tries >= 10) {
s = Status::TryAgain(try_again_messages);
break;
}
s = txn->Rollback();
if (!s.ok()) {
break;
}
}
}
return s;
}
void StressTest::OperateDb(ThreadState* thread) {
ReadOptions read_opts(FLAGS_verify_checksum, true);
read_opts.rate_limiter_priority =
FLAGS_rate_limit_user_ops ? Env::IO_USER : Env::IO_TOTAL;
read_opts.async_io = FLAGS_async_io;
read_opts.adaptive_readahead = FLAGS_adaptive_readahead;
read_opts.readahead_size = FLAGS_readahead_size;
read_opts.auto_readahead_size = FLAGS_auto_readahead_size;
read_opts.fill_cache = FLAGS_fill_cache;
read_opts.optimize_multiget_for_io = FLAGS_optimize_multiget_for_io;
read_opts.allow_unprepared_value = FLAGS_allow_unprepared_value;
read_opts.auto_refresh_iterator_with_snapshot =
FLAGS_auto_refresh_iterator_with_snapshot;
WriteOptions write_opts;
if (FLAGS_rate_limit_auto_wal_flush) {
write_opts.rate_limiter_priority = Env::IO_USER;
}
write_opts.memtable_insert_hint_per_batch =
FLAGS_memtable_insert_hint_per_batch;
auto shared = thread->shared;
char value[100];
std::string from_db;
if (FLAGS_sync) {
write_opts.sync = true;
}
write_opts.disableWAL = FLAGS_disable_wal;
write_opts.protection_bytes_per_key = FLAGS_batch_protection_bytes_per_key;
const int prefix_bound = static_cast<int>(FLAGS_readpercent) +
static_cast<int>(FLAGS_prefixpercent);
const int write_bound = prefix_bound + static_cast<int>(FLAGS_writepercent);
const int del_bound = write_bound + static_cast<int>(FLAGS_delpercent);
const int delrange_bound =
del_bound + static_cast<int>(FLAGS_delrangepercent);
const int iterate_bound =
delrange_bound + static_cast<int>(FLAGS_iterpercent);
const uint64_t ops_per_open = FLAGS_ops_per_thread / (FLAGS_reopen + 1);
thread->stats.Start();
for (int open_cnt = 0; open_cnt <= FLAGS_reopen; ++open_cnt) {
if (thread->shared->HasVerificationFailedYet() ||
thread->shared->ShouldStopTest()) {
break;
}
if (open_cnt != 0) {
thread->stats.FinishedSingleOp();
MutexLock l(thread->shared->GetMutex());
while (!thread->snapshot_queue.empty()) {
db_->ReleaseSnapshot(thread->snapshot_queue.front().second.snapshot);
delete thread->snapshot_queue.front().second.key_vec;
thread->snapshot_queue.pop();
}