write_stress.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. //
  7. // The goal of this tool is to be a simple stress test with focus on catching:
  8. // * bugs in compaction/flush processes, especially the ones that cause
  9. // assertion errors
  10. // * bugs in the code that deletes obsolete files
  11. //
  12. // There are two parts of the test:
  13. // * write_stress, a binary that writes to the database
  14. // * write_stress_runner.py, a script that invokes and kills write_stress
  15. //
  16. // Here are some interesting parts of write_stress:
  17. // * Runs with very high concurrency of compactions and flushes (32 threads
  18. // total) and tries to create a huge amount of small files
  19. // * The keys written to the database are not uniformly distributed -- there is
  20. // a 3-character prefix that mutates occasionally (in prefix mutator thread), in
  21. // such a way that the first character mutates slower than second, which mutates
  22. // slower than third character. That way, the compaction stress tests some
  23. // interesting compaction features like trivial moves and bottommost level
  24. // calculation
  25. // * There is a thread that creates an iterator, holds it for couple of seconds
  26. // and then iterates over all keys. This is supposed to test RocksDB's abilities
  27. // to keep the files alive when there are references to them.
  28. // * Some writes trigger WAL sync. This is stress testing our WAL sync code.
  29. // * At the end of the run, we make sure that we didn't leak any of the sst
  30. // files
  31. //
  32. // write_stress_runner.py changes the mode in which we run write_stress and also
  33. // kills and restarts it. There are some interesting characteristics:
  34. // * At the beginning we divide the full test runtime into smaller parts --
  35. // shorter runtimes (couple of seconds) and longer runtimes (100, 1000) seconds
  36. // * The first time we run write_stress, we destroy the old DB. Every next time
  37. // during the test, we use the same DB.
  38. // * We can run in kill mode or clean-restart mode. Kill mode kills the
  39. // write_stress violently.
  40. // * We can run in mode where delete_obsolete_files_with_fullscan is true or
  41. // false
  42. // * We can run with low_open_files mode turned on or off. When it's turned on,
  43. // we configure table cache to only hold a couple of files -- that way we need
  44. // to reopen files every time we access them.
  45. //
  46. // Another goal was to create a stress test without a lot of parameters. So
  47. // tools/write_stress_runner.py should only take one parameter -- runtime_sec
  48. // and it should figure out everything else on its own.
  49. #include <cstdio>
  50. #ifndef GFLAGS
  51. int main() {
  52. fprintf(stderr, "Please install gflags to run rocksdb tools\n");
  53. return 1;
  54. }
  55. #else
  56. #include <atomic>
  57. #include <cinttypes>
  58. #include <random>
  59. #include <set>
  60. #include <string>
  61. #include <thread>
  62. #include "file/filename.h"
  63. #include "port/port.h"
  64. #include "rocksdb/db.h"
  65. #include "rocksdb/env.h"
  66. #include "rocksdb/options.h"
  67. #include "rocksdb/slice.h"
  68. #include "rocksdb/system_clock.h"
  69. #include "util/gflags_compat.h"
  70. using GFLAGS_NAMESPACE::ParseCommandLineFlags;
  71. using GFLAGS_NAMESPACE::RegisterFlagValidator;
  72. using GFLAGS_NAMESPACE::SetUsageMessage;
  73. DEFINE_int32(key_size, 10, "Key size");
  74. DEFINE_int32(value_size, 100, "Value size");
  75. DEFINE_string(db, "", "Use the db with the following name.");
  76. DEFINE_bool(destroy_db, true,
  77. "Destroy the existing DB before running the test");
  78. DEFINE_int32(runtime_sec, 10 * 60, "How long are we running for, in seconds");
  79. DEFINE_int32(seed, 139, "Random seed");
  80. DEFINE_double(prefix_mutate_period_sec, 1.0,
  81. "How often are we going to mutate the prefix");
  82. DEFINE_double(first_char_mutate_probability, 0.1,
  83. "How likely are we to mutate the first char every period");
  84. DEFINE_double(second_char_mutate_probability, 0.2,
  85. "How likely are we to mutate the second char every period");
  86. DEFINE_double(third_char_mutate_probability, 0.5,
  87. "How likely are we to mutate the third char every period");
  88. DEFINE_int32(iterator_hold_sec, 5,
  89. "How long will the iterator hold files before it gets destroyed");
  90. DEFINE_double(sync_probability, 0.01, "How often are we syncing writes");
  91. DEFINE_bool(delete_obsolete_files_with_fullscan, false,
  92. "If true, we delete obsolete files after each compaction/flush "
  93. "using GetChildren() API");
  94. DEFINE_bool(low_open_files_mode, false,
  95. "If true, we set max_open_files to 20, so that every file access "
  96. "needs to reopen it");
  97. namespace ROCKSDB_NAMESPACE {
  98. static const int kPrefixSize = 3;
  99. class WriteStress {
  100. public:
  101. WriteStress() : stop_(false) {
  102. // initialize key_prefix
  103. for (int i = 0; i < kPrefixSize; ++i) {
  104. key_prefix_[i].store('a');
  105. }
  106. // Choose a location for the test database if none given with --db=<path>
  107. if (FLAGS_db.empty()) {
  108. std::string default_db_path;
  109. Env::Default()->GetTestDirectory(&default_db_path);
  110. default_db_path += "/write_stress";
  111. FLAGS_db = default_db_path;
  112. }
  113. Options options;
  114. if (FLAGS_destroy_db) {
  115. DestroyDB(FLAGS_db, options); // ignore
  116. }
  117. // make the LSM tree deep, so that we have many concurrent flushes and
  118. // compactions
  119. options.create_if_missing = true;
  120. options.write_buffer_size = 256 * 1024; // 256k
  121. options.max_bytes_for_level_base = 1 * 1024 * 1024; // 1MB
  122. options.target_file_size_base = 100 * 1024; // 100k
  123. options.max_write_buffer_number = 16;
  124. options.max_background_compactions = 16;
  125. options.max_background_flushes = 16;
  126. options.max_open_files = FLAGS_low_open_files_mode ? 20 : -1;
  127. if (FLAGS_delete_obsolete_files_with_fullscan) {
  128. options.delete_obsolete_files_period_micros = 0;
  129. }
  130. // open DB
  131. DB* db;
  132. Status s = DB::Open(options, FLAGS_db, &db);
  133. if (!s.ok()) {
  134. fprintf(stderr, "Can't open database: %s\n", s.ToString().c_str());
  135. std::abort();
  136. }
  137. db_.reset(db);
  138. }
  139. void WriteThread() {
  140. std::mt19937 rng(static_cast<unsigned int>(FLAGS_seed));
  141. std::uniform_real_distribution<double> dist(0, 1);
  142. auto random_string = [](std::mt19937& r, int len) {
  143. std::uniform_int_distribution<int> char_dist('a', 'z');
  144. std::string ret;
  145. for (int i = 0; i < len; ++i) {
  146. ret += static_cast<char>(char_dist(r));
  147. }
  148. return ret;
  149. };
  150. while (!stop_.load(std::memory_order_relaxed)) {
  151. std::string prefix;
  152. prefix.resize(kPrefixSize);
  153. for (int i = 0; i < kPrefixSize; ++i) {
  154. prefix[i] = key_prefix_[i].load(std::memory_order_relaxed);
  155. }
  156. auto key = prefix + random_string(rng, FLAGS_key_size - kPrefixSize);
  157. auto value = random_string(rng, FLAGS_value_size);
  158. WriteOptions woptions;
  159. woptions.sync = dist(rng) < FLAGS_sync_probability;
  160. auto s = db_->Put(woptions, key, value);
  161. if (!s.ok()) {
  162. fprintf(stderr, "Write to DB failed: %s\n", s.ToString().c_str());
  163. std::abort();
  164. }
  165. }
  166. }
  167. void IteratorHoldThread() {
  168. while (!stop_.load(std::memory_order_relaxed)) {
  169. std::unique_ptr<Iterator> iterator(db_->NewIterator(ReadOptions()));
  170. SystemClock::Default()->SleepForMicroseconds(FLAGS_iterator_hold_sec *
  171. 1000 * 1000LL);
  172. for (iterator->SeekToFirst(); iterator->Valid(); iterator->Next()) {
  173. }
  174. if (!iterator->status().ok()) {
  175. fprintf(stderr, "Iterator statuts not OK: %s\n",
  176. iterator->status().ToString().c_str());
  177. std::abort();
  178. }
  179. }
  180. }
  181. void PrefixMutatorThread() {
  182. std::mt19937 rng(static_cast<unsigned int>(FLAGS_seed));
  183. std::uniform_real_distribution<double> dist(0, 1);
  184. std::uniform_int_distribution<int> char_dist('a', 'z');
  185. while (!stop_.load(std::memory_order_relaxed)) {
  186. SystemClock::Default()->SleepForMicroseconds(
  187. static_cast<int>(FLAGS_prefix_mutate_period_sec * 1000 * 1000LL));
  188. if (dist(rng) < FLAGS_first_char_mutate_probability) {
  189. key_prefix_[0].store(static_cast<char>(char_dist(rng)),
  190. std::memory_order_relaxed);
  191. }
  192. if (dist(rng) < FLAGS_second_char_mutate_probability) {
  193. key_prefix_[1].store(static_cast<char>(char_dist(rng)),
  194. std::memory_order_relaxed);
  195. }
  196. if (dist(rng) < FLAGS_third_char_mutate_probability) {
  197. key_prefix_[2].store(static_cast<char>(char_dist(rng)),
  198. std::memory_order_relaxed);
  199. }
  200. }
  201. }
  202. int Run() {
  203. threads_.emplace_back([&]() { WriteThread(); });
  204. threads_.emplace_back([&]() { PrefixMutatorThread(); });
  205. threads_.emplace_back([&]() { IteratorHoldThread(); });
  206. if (FLAGS_runtime_sec == -1) {
  207. // infinite runtime, until we get killed
  208. while (true) {
  209. SystemClock::Default()->SleepForMicroseconds(1000 * 1000);
  210. }
  211. }
  212. SystemClock::Default()->SleepForMicroseconds(FLAGS_runtime_sec * 1000 *
  213. 1000);
  214. stop_.store(true, std::memory_order_relaxed);
  215. for (auto& t : threads_) {
  216. t.join();
  217. }
  218. threads_.clear();
  219. // let's see if we leaked some files
  220. db_->PauseBackgroundWork();
  221. std::vector<LiveFileMetaData> metadata;
  222. db_->GetLiveFilesMetaData(&metadata);
  223. std::set<uint64_t> sst_file_numbers;
  224. for (const auto& file : metadata) {
  225. uint64_t number;
  226. FileType type;
  227. if (!ParseFileName(file.name, &number, "LOG", &type)) {
  228. continue;
  229. }
  230. if (type == kTableFile) {
  231. sst_file_numbers.insert(number);
  232. }
  233. }
  234. std::vector<std::string> children;
  235. Env::Default()->GetChildren(FLAGS_db, &children);
  236. for (const auto& child : children) {
  237. uint64_t number;
  238. FileType type;
  239. if (!ParseFileName(child, &number, "LOG", &type)) {
  240. continue;
  241. }
  242. if (type == kTableFile) {
  243. if (sst_file_numbers.find(number) == sst_file_numbers.end()) {
  244. fprintf(stderr,
  245. "Found a table file in DB path that should have been "
  246. "deleted: %s\n",
  247. child.c_str());
  248. std::abort();
  249. }
  250. }
  251. }
  252. db_->ContinueBackgroundWork();
  253. return 0;
  254. }
  255. private:
  256. // each key is prepended with this prefix. we occasionally change it. third
  257. // letter is changed more frequently than second, which is changed more
  258. // frequently than the first one.
  259. std::atomic<char> key_prefix_[kPrefixSize];
  260. std::atomic<bool> stop_;
  261. std::vector<port::Thread> threads_;
  262. std::unique_ptr<DB> db_;
  263. };
  264. } // namespace ROCKSDB_NAMESPACE
  265. int main(int argc, char** argv) {
  266. SetUsageMessage(std::string("\nUSAGE:\n") + std::string(argv[0]) +
  267. " [OPTIONS]...");
  268. ParseCommandLineFlags(&argc, &argv, true);
  269. ROCKSDB_NAMESPACE::WriteStress write_stress;
  270. return write_stress.Run();
  271. }
  272. #endif // GFLAGS