作者: 谢瑞阳 10225101483 徐翔宇 10225101535

366 lines
9.7 KiB

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