1 //  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 //
6 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
7 // Use of this source code is governed by a BSD-style license that can be
8 // found in the LICENSE file. See the AUTHORS file for names of contributors.
9 //
10 // The test uses an array to compare against values written to the database.
11 // Keys written to the array are in 1:1 correspondence to the actual values in
12 // the database according to the formula in the function GenerateValue.
13 
14 // Space is reserved in the array from 0 to FLAGS_max_key and values are
15 // randomly written/deleted/read from those positions. During verification we
16 // compare all the positions in the array. To shorten/elongate the running
17 // time, you could change the settings: FLAGS_max_key, FLAGS_ops_per_thread,
18 // (sometimes also FLAGS_threads).
19 //
20 // NOTE that if FLAGS_test_batches_snapshots is set, the test will have
21 // different behavior. See comment of the flag for details.
22 
23 #ifdef GFLAGS
24 #include "db_stress_tool/db_stress_common.h"
25 #include "db_stress_tool/db_stress_driver.h"
26 #include "rocksdb/convenience.h"
27 #ifndef NDEBUG
28 #include "utilities/fault_injection_fs.h"
29 #endif
30 
31 namespace ROCKSDB_NAMESPACE {
32 namespace {
33 static std::shared_ptr<ROCKSDB_NAMESPACE::Env> env_guard;
34 static std::shared_ptr<ROCKSDB_NAMESPACE::DbStressEnvWrapper> env_wrapper_guard;
35 static std::shared_ptr<CompositeEnvWrapper> fault_env_guard;
36 }  // namespace
37 
38 KeyGenContext key_gen_ctx;
39 
db_stress_tool(int argc,char ** argv)40 int db_stress_tool(int argc, char** argv) {
41   SetUsageMessage(std::string("\nUSAGE:\n") + std::string(argv[0]) +
42                   " [OPTIONS]...");
43   ParseCommandLineFlags(&argc, &argv, true);
44 
45   SanitizeDoubleParam(&FLAGS_bloom_bits);
46   SanitizeDoubleParam(&FLAGS_memtable_prefix_bloom_size_ratio);
47   SanitizeDoubleParam(&FLAGS_max_bytes_for_level_multiplier);
48 
49 #ifndef NDEBUG
50   if (FLAGS_mock_direct_io) {
51     SetupSyncPointsToMockDirectIO();
52   }
53 #endif
54   if (FLAGS_statistics) {
55     dbstats = ROCKSDB_NAMESPACE::CreateDBStatistics();
56     if (FLAGS_test_secondary) {
57       dbstats_secondaries = ROCKSDB_NAMESPACE::CreateDBStatistics();
58     }
59   }
60   compression_type_e = StringToCompressionType(FLAGS_compression_type.c_str());
61   bottommost_compression_type_e =
62       StringToCompressionType(FLAGS_bottommost_compression_type.c_str());
63   checksum_type_e = StringToChecksumType(FLAGS_checksum_type.c_str());
64 
65   Env* raw_env;
66 
67   int env_opts =
68       !FLAGS_hdfs.empty() + !FLAGS_env_uri.empty() + !FLAGS_fs_uri.empty();
69   if (env_opts > 1) {
70     fprintf(stderr,
71             "Error: --hdfs, --env_uri and --fs_uri are mutually exclusive\n");
72     exit(1);
73   }
74 
75   if (!FLAGS_hdfs.empty()) {
76     raw_env = new ROCKSDB_NAMESPACE::HdfsEnv(FLAGS_hdfs);
77   } else {
78     Status s = Env::CreateFromUri(ConfigOptions(), FLAGS_env_uri, FLAGS_fs_uri,
79                                   &raw_env, &env_guard);
80     if (!s.ok()) {
81       fprintf(stderr, "Error Creating Env URI: %s: %s\n", FLAGS_env_uri.c_str(),
82               s.ToString().c_str());
83       exit(1);
84     }
85   }
86 
87 #ifndef NDEBUG
88   if (FLAGS_read_fault_one_in || FLAGS_sync_fault_injection ||
89       FLAGS_write_fault_one_in || FLAGS_open_metadata_write_fault_one_in ||
90       FLAGS_open_write_fault_one_in || FLAGS_open_read_fault_one_in) {
91     FaultInjectionTestFS* fs =
92         new FaultInjectionTestFS(raw_env->GetFileSystem());
93     fault_fs_guard.reset(fs);
94     if (FLAGS_write_fault_one_in) {
95       fault_fs_guard->SetFilesystemDirectWritable(false);
96     } else {
97       fault_fs_guard->SetFilesystemDirectWritable(true);
98     }
99     fault_env_guard =
100         std::make_shared<CompositeEnvWrapper>(raw_env, fault_fs_guard);
101     raw_env = fault_env_guard.get();
102   }
103   if (FLAGS_write_fault_one_in) {
104     SyncPoint::GetInstance()->SetCallBack(
105         "BuildTable:BeforeFinishBuildTable",
106         [&](void*) { fault_fs_guard->EnableWriteErrorInjection(); });
107     SyncPoint::GetInstance()->EnableProcessing();
108   }
109 #endif
110 
111   env_wrapper_guard = std::make_shared<DbStressEnvWrapper>(raw_env);
112   db_stress_env = env_wrapper_guard.get();
113 
114 #ifndef NDEBUG
115   if (FLAGS_write_fault_one_in) {
116     // In the write injection case, we need to use the FS interface and returns
117     // the IOStatus with different error and flags. Therefore,
118     // DbStressEnvWrapper cannot be used which will swallow the FS
119     // implementations. We should directly use the raw_env which is the
120     // CompositeEnvWrapper of env and fault_fs.
121     db_stress_env = raw_env;
122   }
123 #endif
124 
125   FLAGS_rep_factory = StringToRepFactory(FLAGS_memtablerep.c_str());
126 
127   // The number of background threads should be at least as much the
128   // max number of concurrent compactions.
129   db_stress_env->SetBackgroundThreads(FLAGS_max_background_compactions,
130                                       ROCKSDB_NAMESPACE::Env::Priority::LOW);
131   db_stress_env->SetBackgroundThreads(FLAGS_num_bottom_pri_threads,
132                                       ROCKSDB_NAMESPACE::Env::Priority::BOTTOM);
133   if (FLAGS_prefixpercent > 0 && FLAGS_prefix_size < 0) {
134     fprintf(stderr,
135             "Error: prefixpercent is non-zero while prefix_size is "
136             "not positive!\n");
137     exit(1);
138   }
139   if (FLAGS_test_batches_snapshots && FLAGS_prefix_size <= 0) {
140     fprintf(stderr,
141             "Error: please specify prefix_size for "
142             "test_batches_snapshots test!\n");
143     exit(1);
144   }
145   if (FLAGS_memtable_prefix_bloom_size_ratio > 0.0 && FLAGS_prefix_size < 0 &&
146       !FLAGS_memtable_whole_key_filtering) {
147     fprintf(stderr,
148             "Error: please specify positive prefix_size or enable whole key "
149             "filtering in order to use memtable_prefix_bloom_size_ratio\n");
150     exit(1);
151   }
152   if ((FLAGS_readpercent + FLAGS_prefixpercent + FLAGS_writepercent +
153        FLAGS_delpercent + FLAGS_delrangepercent + FLAGS_iterpercent) != 100) {
154     fprintf(stderr,
155             "Error: "
156             "Read(%d)+Prefix(%d)+Write(%d)+Delete(%d)+DeleteRange(%d)"
157             "+Iterate(%d) percents != "
158             "100!\n",
159             FLAGS_readpercent, FLAGS_prefixpercent, FLAGS_writepercent,
160             FLAGS_delpercent, FLAGS_delrangepercent, FLAGS_iterpercent);
161     exit(1);
162   }
163   if (FLAGS_disable_wal == 1 && FLAGS_reopen > 0) {
164     fprintf(stderr, "Error: Db cannot reopen safely with disable_wal set!\n");
165     exit(1);
166   }
167   if ((unsigned)FLAGS_reopen >= FLAGS_ops_per_thread) {
168     fprintf(stderr,
169             "Error: #DB-reopens should be < ops_per_thread\n"
170             "Provided reopens = %d and ops_per_thread = %lu\n",
171             FLAGS_reopen, (unsigned long)FLAGS_ops_per_thread);
172     exit(1);
173   }
174   if (FLAGS_test_batches_snapshots && FLAGS_delrangepercent > 0) {
175     fprintf(stderr,
176             "Error: nonzero delrangepercent unsupported in "
177             "test_batches_snapshots mode\n");
178     exit(1);
179   }
180   if (FLAGS_active_width > FLAGS_max_key) {
181     fprintf(stderr, "Error: active_width can be at most max_key\n");
182     exit(1);
183   } else if (FLAGS_active_width == 0) {
184     FLAGS_active_width = FLAGS_max_key;
185   }
186   if (FLAGS_value_size_mult * kRandomValueMaxFactor > kValueMaxLen) {
187     fprintf(stderr, "Error: value_size_mult can be at most %d\n",
188             kValueMaxLen / kRandomValueMaxFactor);
189     exit(1);
190   }
191   if (FLAGS_use_merge && FLAGS_nooverwritepercent == 100) {
192     fprintf(
193         stderr,
194         "Error: nooverwritepercent must not be 100 when using merge operands");
195     exit(1);
196   }
197   if (FLAGS_ingest_external_file_one_in > 0 && FLAGS_nooverwritepercent > 0) {
198     fprintf(stderr,
199             "Error: nooverwritepercent must be 0 when using file ingestion\n");
200     exit(1);
201   }
202   if (FLAGS_clear_column_family_one_in > 0 && FLAGS_backup_one_in > 0) {
203     fprintf(stderr,
204             "Error: clear_column_family_one_in must be 0 when using backup\n");
205     exit(1);
206   }
207   if (FLAGS_test_cf_consistency && FLAGS_disable_wal) {
208     FLAGS_atomic_flush = true;
209   }
210 
211   if (FLAGS_read_only) {
212     if (FLAGS_writepercent != 0 || FLAGS_delpercent != 0 ||
213         FLAGS_delrangepercent != 0) {
214       fprintf(stderr, "Error: updates are not supported in read only mode\n");
215       exit(1);
216     } else if (FLAGS_checkpoint_one_in > 0 &&
217                FLAGS_clear_column_family_one_in > 0) {
218       fprintf(stdout,
219               "Warn: checkpoint won't be validated since column families may "
220               "be dropped.\n");
221     }
222   }
223 
224   // Choose a location for the test database if none given with --db=<path>
225   if (FLAGS_db.empty()) {
226     std::string default_db_path;
227     db_stress_env->GetTestDirectory(&default_db_path);
228     default_db_path += "/dbstress";
229     FLAGS_db = default_db_path;
230   }
231 
232   if ((FLAGS_test_secondary || FLAGS_continuous_verification_interval > 0) &&
233       FLAGS_secondaries_base.empty()) {
234     std::string default_secondaries_path;
235     db_stress_env->GetTestDirectory(&default_secondaries_path);
236     default_secondaries_path += "/dbstress_secondaries";
237     ROCKSDB_NAMESPACE::Status s =
238         db_stress_env->CreateDirIfMissing(default_secondaries_path);
239     if (!s.ok()) {
240       fprintf(stderr, "Failed to create directory %s: %s\n",
241               default_secondaries_path.c_str(), s.ToString().c_str());
242       exit(1);
243     }
244     FLAGS_secondaries_base = default_secondaries_path;
245   }
246 
247   if (!FLAGS_test_secondary && FLAGS_secondary_catch_up_one_in > 0) {
248     fprintf(
249         stderr,
250         "Must set -test_secondary=true if secondary_catch_up_one_in > 0.\n");
251     exit(1);
252   }
253   if (FLAGS_best_efforts_recovery && !FLAGS_skip_verifydb &&
254       !FLAGS_disable_wal) {
255     fprintf(stderr,
256             "With best-efforts recovery, either skip_verifydb or disable_wal "
257             "should be set to true.\n");
258     exit(1);
259   }
260   if (FLAGS_skip_verifydb) {
261     if (FLAGS_verify_db_one_in > 0) {
262       fprintf(stderr,
263               "Must set -verify_db_one_in=0 if skip_verifydb is true.\n");
264       exit(1);
265     }
266     if (FLAGS_continuous_verification_interval > 0) {
267       fprintf(stderr,
268               "Must set -continuous_verification_interval=0 if skip_verifydb "
269               "is true.\n");
270       exit(1);
271     }
272   }
273   if (FLAGS_enable_compaction_filter &&
274       (FLAGS_acquire_snapshot_one_in > 0 || FLAGS_compact_range_one_in > 0 ||
275        FLAGS_iterpercent > 0 || FLAGS_test_batches_snapshots ||
276        FLAGS_test_cf_consistency)) {
277     fprintf(
278         stderr,
279         "Error: acquire_snapshot_one_in, compact_range_one_in, iterpercent, "
280         "test_batches_snapshots  must all be 0 when using compaction filter\n");
281     exit(1);
282   }
283   if (FLAGS_batch_protection_bytes_per_key > 0 &&
284       !FLAGS_test_batches_snapshots) {
285     fprintf(stderr,
286             "Error: test_batches_snapshots must be enabled when "
287             "batch_protection_bytes_per_key > 0\n");
288     exit(1);
289   }
290 
291 #ifndef NDEBUG
292   KillPoint* kp = KillPoint::GetInstance();
293   kp->rocksdb_kill_odds = FLAGS_kill_random_test;
294   kp->rocksdb_kill_exclude_prefixes = SplitString(FLAGS_kill_exclude_prefixes);
295 #endif
296 
297   unsigned int levels = FLAGS_max_key_len;
298   std::vector<std::string> weights;
299   uint64_t scale_factor = FLAGS_key_window_scale_factor;
300   key_gen_ctx.window = scale_factor * 100;
301   if (!FLAGS_key_len_percent_dist.empty()) {
302     weights = SplitString(FLAGS_key_len_percent_dist);
303     if (weights.size() != levels) {
304       fprintf(stderr,
305               "Number of weights in key_len_dist should be equal to"
306               " max_key_len");
307       exit(1);
308     }
309 
310     uint64_t total_weight = 0;
311     for (std::string& weight : weights) {
312       uint64_t val = std::stoull(weight);
313       key_gen_ctx.weights.emplace_back(val * scale_factor);
314       total_weight += val;
315     }
316     if (total_weight != 100) {
317       fprintf(stderr, "Sum of all weights in key_len_dist should be 100");
318       exit(1);
319     }
320   } else {
321     uint64_t keys_per_level = key_gen_ctx.window / levels;
322     for (unsigned int level = 0; level + 1 < levels; ++level) {
323       key_gen_ctx.weights.emplace_back(keys_per_level);
324     }
325     key_gen_ctx.weights.emplace_back(key_gen_ctx.window -
326                                      keys_per_level * (levels - 1));
327   }
328 
329   std::unique_ptr<ROCKSDB_NAMESPACE::StressTest> stress;
330   if (FLAGS_test_cf_consistency) {
331     stress.reset(CreateCfConsistencyStressTest());
332   } else if (FLAGS_test_batches_snapshots) {
333     stress.reset(CreateBatchedOpsStressTest());
334   } else {
335     stress.reset(CreateNonBatchedOpsStressTest());
336   }
337   // Initialize the Zipfian pre-calculated array
338   InitializeHotKeyGenerator(FLAGS_hot_key_alpha);
339   if (RunStressTest(stress.get())) {
340     return 0;
341   } else {
342     return 1;
343   }
344 }
345 
346 }  // namespace ROCKSDB_NAMESPACE
347 #endif  // GFLAGS
348