corruption_test.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include <sys/types.h>
  5. #include "gtest/gtest.h"
  6. #include "db/db_impl.h"
  7. #include "db/filename.h"
  8. #include "db/log_format.h"
  9. #include "db/version_set.h"
  10. #include "leveldb/cache.h"
  11. #include "leveldb/db.h"
  12. #include "leveldb/table.h"
  13. #include "leveldb/write_batch.h"
  14. #include "util/logging.h"
  15. #include "util/testutil.h"
  16. namespace leveldb {
  17. static const int kValueSize = 1000;
  18. class CorruptionTest : public testing::Test {
  19. public:
  20. CorruptionTest()
  21. : db_(nullptr),
  22. dbname_("/memenv/corruption_test"),
  23. tiny_cache_(NewLRUCache(100)) {
  24. options_.env = &env_;
  25. options_.block_cache = tiny_cache_;
  26. DestroyDB(dbname_, options_);
  27. options_.create_if_missing = true;
  28. Reopen();
  29. options_.create_if_missing = false;
  30. }
  31. ~CorruptionTest() {
  32. delete db_;
  33. delete tiny_cache_;
  34. }
  35. Status TryReopen() {
  36. delete db_;
  37. db_ = nullptr;
  38. return DB::Open(options_, dbname_, &db_);
  39. }
  40. void Reopen() { ASSERT_LEVELDB_OK(TryReopen()); }
  41. void RepairDB() {
  42. delete db_;
  43. db_ = nullptr;
  44. ASSERT_LEVELDB_OK(::leveldb::RepairDB(dbname_, options_));
  45. }
  46. void Build(int n) {
  47. std::string key_space, value_space;
  48. WriteBatch batch;
  49. for (int i = 0; i < n; i++) {
  50. // if ((i % 100) == 0) std::fprintf(stderr, "@ %d of %d\n", i, n);
  51. Slice key = Key(i, &key_space);
  52. batch.Clear();
  53. batch.Put(key, Value(i, &value_space));
  54. WriteOptions options;
  55. // Corrupt() doesn't work without this sync on windows; stat reports 0 for
  56. // the file size.
  57. if (i == n - 1) {
  58. options.sync = true;
  59. }
  60. ASSERT_LEVELDB_OK(db_->Write(options, &batch));
  61. }
  62. }
  63. void Check(int min_expected, int max_expected) {
  64. int next_expected = 0;
  65. int missed = 0;
  66. int bad_keys = 0;
  67. int bad_values = 0;
  68. int correct = 0;
  69. std::string value_space;
  70. Iterator* iter = db_->NewIterator(ReadOptions());
  71. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  72. uint64_t key;
  73. Slice in(iter->key());
  74. if (in == "" || in == "~") {
  75. // Ignore boundary keys.
  76. continue;
  77. }
  78. if (!ConsumeDecimalNumber(&in, &key) || !in.empty() ||
  79. key < next_expected) {
  80. bad_keys++;
  81. continue;
  82. }
  83. missed += (key - next_expected);
  84. next_expected = key + 1;
  85. if (iter->value() != Value(key, &value_space)) {
  86. bad_values++;
  87. } else {
  88. correct++;
  89. }
  90. }
  91. delete iter;
  92. std::fprintf(
  93. stderr,
  94. "expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n",
  95. min_expected, max_expected, correct, bad_keys, bad_values, missed);
  96. ASSERT_LE(min_expected, correct);
  97. ASSERT_GE(max_expected, correct);
  98. }
  99. void Corrupt(FileType filetype, int offset, int bytes_to_corrupt) {
  100. // Pick file to corrupt
  101. std::vector<std::string> filenames;
  102. ASSERT_LEVELDB_OK(env_.target()->GetChildren(dbname_, &filenames));
  103. uint64_t number;
  104. FileType type;
  105. std::string fname;
  106. int picked_number = -1;
  107. for (size_t i = 0; i < filenames.size(); i++) {
  108. if (ParseFileName(filenames[i], &number, &type) && type == filetype &&
  109. int(number) > picked_number) { // Pick latest file
  110. fname = dbname_ + "/" + filenames[i];
  111. picked_number = number;
  112. }
  113. }
  114. ASSERT_TRUE(!fname.empty()) << filetype;
  115. uint64_t file_size;
  116. ASSERT_LEVELDB_OK(env_.target()->GetFileSize(fname, &file_size));
  117. if (offset < 0) {
  118. // Relative to end of file; make it absolute
  119. if (-offset > file_size) {
  120. offset = 0;
  121. } else {
  122. offset = file_size + offset;
  123. }
  124. }
  125. if (offset > file_size) {
  126. offset = file_size;
  127. }
  128. if (offset + bytes_to_corrupt > file_size) {
  129. bytes_to_corrupt = file_size - offset;
  130. }
  131. // Do it
  132. std::string contents;
  133. Status s = ReadFileToString(env_.target(), fname, &contents);
  134. ASSERT_TRUE(s.ok()) << s.ToString();
  135. for (int i = 0; i < bytes_to_corrupt; i++) {
  136. contents[i + offset] ^= 0x80;
  137. }
  138. s = WriteStringToFile(env_.target(), contents, fname);
  139. ASSERT_TRUE(s.ok()) << s.ToString();
  140. }
  141. int Property(const std::string& name) {
  142. std::string property;
  143. int result;
  144. if (db_->GetProperty(name, &property) &&
  145. sscanf(property.c_str(), "%d", &result) == 1) {
  146. return result;
  147. } else {
  148. return -1;
  149. }
  150. }
  151. // Return the ith key
  152. Slice Key(int i, std::string* storage) {
  153. char buf[100];
  154. std::snprintf(buf, sizeof(buf), "%016d", i);
  155. storage->assign(buf, strlen(buf));
  156. return Slice(*storage);
  157. }
  158. // Return the value to associate with the specified key
  159. Slice Value(int k, std::string* storage) {
  160. Random r(k);
  161. return test::RandomString(&r, kValueSize, storage);
  162. }
  163. test::ErrorEnv env_;
  164. Options options_;
  165. DB* db_;
  166. private:
  167. std::string dbname_;
  168. Cache* tiny_cache_;
  169. };
  170. TEST_F(CorruptionTest, Recovery) {
  171. Build(100);
  172. Check(100, 100);
  173. Corrupt(kLogFile, 19, 1); // WriteBatch tag for first record
  174. Corrupt(kLogFile, log::kBlockSize + 1000, 1); // Somewhere in second block
  175. Reopen();
  176. // The 64 records in the first two log blocks are completely lost.
  177. Check(36, 36);
  178. }
  179. TEST_F(CorruptionTest, RecoverWriteError) {
  180. env_.writable_file_error_ = true;
  181. Status s = TryReopen();
  182. ASSERT_TRUE(!s.ok());
  183. }
  184. TEST_F(CorruptionTest, NewFileErrorDuringWrite) {
  185. // Do enough writing to force minor compaction
  186. env_.writable_file_error_ = true;
  187. const int num = 3 + (Options().write_buffer_size / kValueSize);
  188. std::string value_storage;
  189. Status s;
  190. for (int i = 0; s.ok() && i < num; i++) {
  191. WriteBatch batch;
  192. batch.Put("a", Value(100, &value_storage));
  193. s = db_->Write(WriteOptions(), &batch);
  194. }
  195. ASSERT_TRUE(!s.ok());
  196. ASSERT_GE(env_.num_writable_file_errors_, 1);
  197. env_.writable_file_error_ = false;
  198. Reopen();
  199. }
  200. TEST_F(CorruptionTest, TableFile) {
  201. Build(100);
  202. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  203. dbi->TEST_CompactMemTable();
  204. dbi->TEST_CompactRange(0, nullptr, nullptr);
  205. dbi->TEST_CompactRange(1, nullptr, nullptr);
  206. Corrupt(kTableFile, 100, 1);
  207. Check(90, 99);
  208. }
  209. TEST_F(CorruptionTest, TableFileRepair) {
  210. options_.block_size = 2 * kValueSize; // Limit scope of corruption
  211. options_.paranoid_checks = true;
  212. Reopen();
  213. Build(100);
  214. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  215. dbi->TEST_CompactMemTable();
  216. dbi->TEST_CompactRange(0, nullptr, nullptr);
  217. dbi->TEST_CompactRange(1, nullptr, nullptr);
  218. Corrupt(kTableFile, 100, 1);
  219. RepairDB();
  220. Reopen();
  221. Check(95, 99);
  222. }
  223. TEST_F(CorruptionTest, TableFileIndexData) {
  224. Build(10000); // Enough to build multiple Tables
  225. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  226. dbi->TEST_CompactMemTable();
  227. Corrupt(kTableFile, -2000, 500);
  228. Reopen();
  229. Check(5000, 9999);
  230. }
  231. TEST_F(CorruptionTest, MissingDescriptor) {
  232. Build(1000);
  233. RepairDB();
  234. Reopen();
  235. Check(1000, 1000);
  236. }
  237. TEST_F(CorruptionTest, SequenceNumberRecovery) {
  238. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "v1"));
  239. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "v2"));
  240. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "v3"));
  241. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "v4"));
  242. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "v5"));
  243. RepairDB();
  244. Reopen();
  245. std::string v;
  246. ASSERT_LEVELDB_OK(db_->Get(ReadOptions(), "foo", &v));
  247. ASSERT_EQ("v5", v);
  248. // Write something. If sequence number was not recovered properly,
  249. // it will be hidden by an earlier write.
  250. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "v6"));
  251. ASSERT_LEVELDB_OK(db_->Get(ReadOptions(), "foo", &v));
  252. ASSERT_EQ("v6", v);
  253. Reopen();
  254. ASSERT_LEVELDB_OK(db_->Get(ReadOptions(), "foo", &v));
  255. ASSERT_EQ("v6", v);
  256. }
  257. TEST_F(CorruptionTest, CorruptedDescriptor) {
  258. ASSERT_LEVELDB_OK(db_->Put(WriteOptions(), "foo", "hello"));
  259. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  260. dbi->TEST_CompactMemTable();
  261. dbi->TEST_CompactRange(0, nullptr, nullptr);
  262. Corrupt(kDescriptorFile, 0, 1000);
  263. Status s = TryReopen();
  264. ASSERT_TRUE(!s.ok());
  265. RepairDB();
  266. Reopen();
  267. std::string v;
  268. ASSERT_LEVELDB_OK(db_->Get(ReadOptions(), "foo", &v));
  269. ASSERT_EQ("hello", v);
  270. }
  271. TEST_F(CorruptionTest, CompactionInputError) {
  272. Build(10);
  273. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  274. dbi->TEST_CompactMemTable();
  275. const int last = config::kMaxMemCompactLevel;
  276. ASSERT_EQ(1, Property("leveldb.num-files-at-level" + NumberToString(last)));
  277. Corrupt(kTableFile, 100, 1);
  278. Check(5, 9);
  279. // Force compactions by writing lots of values
  280. Build(10000);
  281. Check(10000, 10000);
  282. }
  283. TEST_F(CorruptionTest, CompactionInputErrorParanoid) {
  284. options_.paranoid_checks = true;
  285. options_.write_buffer_size = 512 << 10;
  286. Reopen();
  287. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  288. // Make multiple inputs so we need to compact.
  289. for (int i = 0; i < 2; i++) {
  290. Build(10);
  291. dbi->TEST_CompactMemTable();
  292. Corrupt(kTableFile, 100, 1);
  293. env_.SleepForMicroseconds(100000);
  294. }
  295. dbi->CompactRange(nullptr, nullptr);
  296. // Write must fail because of corrupted table
  297. std::string tmp1, tmp2;
  298. Status s = db_->Put(WriteOptions(), Key(5, &tmp1), Value(5, &tmp2));
  299. ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db";
  300. }
  301. TEST_F(CorruptionTest, UnrelatedKeys) {
  302. Build(10);
  303. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  304. dbi->TEST_CompactMemTable();
  305. Corrupt(kTableFile, 100, 1);
  306. std::string tmp1, tmp2;
  307. ASSERT_LEVELDB_OK(
  308. db_->Put(WriteOptions(), Key(1000, &tmp1), Value(1000, &tmp2)));
  309. std::string v;
  310. ASSERT_LEVELDB_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  311. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  312. dbi->TEST_CompactMemTable();
  313. ASSERT_LEVELDB_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  314. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  315. }
  316. } // namespace leveldb