作者: 韩晨旭 10225101440 李畅 10225102463
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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