作者: 谢瑞阳 10225101483 徐翔宇 10225101535
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.

359 line
9.5 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 <errno.h>
  6. #include <fcntl.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include "leveldb/cache.h"
  10. #include "leveldb/env.h"
  11. #include "leveldb/table.h"
  12. #include "leveldb/write_batch.h"
  13. #include "db/db_impl.h"
  14. #include "db/filename.h"
  15. #include "db/log_format.h"
  16. #include "db/version_set.h"
  17. #include "util/logging.h"
  18. #include "util/testharness.h"
  19. #include "util/testutil.h"
  20. namespace leveldb {
  21. static const int kValueSize = 1000;
  22. class CorruptionTest {
  23. public:
  24. test::ErrorEnv env_;
  25. std::string dbname_;
  26. Cache* tiny_cache_;
  27. Options options_;
  28. DB* db_;
  29. CorruptionTest() {
  30. tiny_cache_ = NewLRUCache(100);
  31. options_.env = &env_;
  32. dbname_ = test::TmpDir() + "/db_test";
  33. DestroyDB(dbname_, options_);
  34. db_ = NULL;
  35. options_.create_if_missing = true;
  36. Reopen();
  37. options_.create_if_missing = false;
  38. }
  39. ~CorruptionTest() {
  40. delete db_;
  41. DestroyDB(dbname_, Options());
  42. delete tiny_cache_;
  43. }
  44. Status TryReopen(Options* options = NULL) {
  45. delete db_;
  46. db_ = NULL;
  47. Options opt = (options ? *options : options_);
  48. opt.env = &env_;
  49. opt.block_cache = tiny_cache_;
  50. return DB::Open(opt, dbname_, &db_);
  51. }
  52. void Reopen(Options* options = NULL) {
  53. ASSERT_OK(TryReopen(options));
  54. }
  55. void RepairDB() {
  56. delete db_;
  57. db_ = NULL;
  58. ASSERT_OK(::leveldb::RepairDB(dbname_, options_));
  59. }
  60. void Build(int n) {
  61. std::string key_space, value_space;
  62. WriteBatch batch;
  63. for (int i = 0; i < n; i++) {
  64. //if ((i % 100) == 0) fprintf(stderr, "@ %d of %d\n", i, n);
  65. Slice key = Key(i, &key_space);
  66. batch.Clear();
  67. batch.Put(key, Value(i, &value_space));
  68. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  69. }
  70. }
  71. void Check(int min_expected, int max_expected) {
  72. int next_expected = 0;
  73. int missed = 0;
  74. int bad_keys = 0;
  75. int bad_values = 0;
  76. int correct = 0;
  77. std::string value_space;
  78. Iterator* iter = db_->NewIterator(ReadOptions());
  79. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  80. uint64_t key;
  81. Slice in(iter->key());
  82. if (!ConsumeDecimalNumber(&in, &key) ||
  83. !in.empty() ||
  84. key < next_expected) {
  85. bad_keys++;
  86. continue;
  87. }
  88. missed += (key - next_expected);
  89. next_expected = key + 1;
  90. if (iter->value() != Value(key, &value_space)) {
  91. bad_values++;
  92. } else {
  93. correct++;
  94. }
  95. }
  96. delete iter;
  97. fprintf(stderr,
  98. "expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n",
  99. min_expected, max_expected, correct, bad_keys, bad_values, missed);
  100. ASSERT_LE(min_expected, correct);
  101. ASSERT_GE(max_expected, correct);
  102. }
  103. void Corrupt(FileType filetype, int offset, int bytes_to_corrupt) {
  104. // Pick file to corrupt
  105. std::vector<std::string> filenames;
  106. ASSERT_OK(env_.GetChildren(dbname_, &filenames));
  107. uint64_t number;
  108. FileType type;
  109. std::string fname;
  110. int picked_number = -1;
  111. for (int i = 0; i < filenames.size(); i++) {
  112. if (ParseFileName(filenames[i], &number, &type) &&
  113. type == filetype &&
  114. int(number) > picked_number) { // Pick latest file
  115. fname = dbname_ + "/" + filenames[i];
  116. picked_number = number;
  117. }
  118. }
  119. ASSERT_TRUE(!fname.empty()) << filetype;
  120. struct stat sbuf;
  121. if (stat(fname.c_str(), &sbuf) != 0) {
  122. const char* msg = strerror(errno);
  123. ASSERT_TRUE(false) << fname << ": " << msg;
  124. }
  125. if (offset < 0) {
  126. // Relative to end of file; make it absolute
  127. if (-offset > sbuf.st_size) {
  128. offset = 0;
  129. } else {
  130. offset = sbuf.st_size + offset;
  131. }
  132. }
  133. if (offset > sbuf.st_size) {
  134. offset = sbuf.st_size;
  135. }
  136. if (offset + bytes_to_corrupt > sbuf.st_size) {
  137. bytes_to_corrupt = sbuf.st_size - offset;
  138. }
  139. // Do it
  140. std::string contents;
  141. Status s = ReadFileToString(Env::Default(), 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::Default(), 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, NULL, NULL);
  207. dbi->TEST_CompactRange(1, NULL, NULL);
  208. Corrupt(kTableFile, 100, 1);
  209. Check(99, 99);
  210. }
  211. TEST(CorruptionTest, TableFileIndexData) {
  212. Build(10000); // Enough to build multiple Tables
  213. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  214. dbi->TEST_CompactMemTable();
  215. Corrupt(kTableFile, -2000, 500);
  216. Reopen();
  217. Check(5000, 9999);
  218. }
  219. TEST(CorruptionTest, MissingDescriptor) {
  220. Build(1000);
  221. RepairDB();
  222. Reopen();
  223. Check(1000, 1000);
  224. }
  225. TEST(CorruptionTest, SequenceNumberRecovery) {
  226. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  227. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  228. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3"));
  229. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v4"));
  230. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v5"));
  231. RepairDB();
  232. Reopen();
  233. std::string v;
  234. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  235. ASSERT_EQ("v5", v);
  236. // Write something. If sequence number was not recovered properly,
  237. // it will be hidden by an earlier write.
  238. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v6"));
  239. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  240. ASSERT_EQ("v6", v);
  241. Reopen();
  242. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  243. ASSERT_EQ("v6", v);
  244. }
  245. TEST(CorruptionTest, CorruptedDescriptor) {
  246. ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello"));
  247. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  248. dbi->TEST_CompactMemTable();
  249. dbi->TEST_CompactRange(0, NULL, NULL);
  250. Corrupt(kDescriptorFile, 0, 1000);
  251. Status s = TryReopen();
  252. ASSERT_TRUE(!s.ok());
  253. RepairDB();
  254. Reopen();
  255. std::string v;
  256. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  257. ASSERT_EQ("hello", v);
  258. }
  259. TEST(CorruptionTest, CompactionInputError) {
  260. Build(10);
  261. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  262. dbi->TEST_CompactMemTable();
  263. const int last = config::kMaxMemCompactLevel;
  264. ASSERT_EQ(1, Property("leveldb.num-files-at-level" + NumberToString(last)));
  265. Corrupt(kTableFile, 100, 1);
  266. Check(9, 9);
  267. // Force compactions by writing lots of values
  268. Build(10000);
  269. Check(10000, 10000);
  270. }
  271. TEST(CorruptionTest, CompactionInputErrorParanoid) {
  272. Options options;
  273. options.paranoid_checks = true;
  274. options.write_buffer_size = 1048576;
  275. Reopen(&options);
  276. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  277. // Fill levels >= 1 so memtable compaction outputs to level 1
  278. for (int level = 1; level < config::kNumLevels; level++) {
  279. dbi->Put(WriteOptions(), "", "begin");
  280. dbi->Put(WriteOptions(), "~", "end");
  281. dbi->TEST_CompactMemTable();
  282. }
  283. Build(10);
  284. dbi->TEST_CompactMemTable();
  285. ASSERT_EQ(1, Property("leveldb.num-files-at-level0"));
  286. Corrupt(kTableFile, 100, 1);
  287. Check(9, 9);
  288. // Write must eventually fail because of corrupted table
  289. Status s;
  290. std::string tmp1, tmp2;
  291. for (int i = 0; i < 10000 && s.ok(); i++) {
  292. s = db_->Put(WriteOptions(), Key(i, &tmp1), Value(i, &tmp2));
  293. }
  294. ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db";
  295. }
  296. TEST(CorruptionTest, UnrelatedKeys) {
  297. Build(10);
  298. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  299. dbi->TEST_CompactMemTable();
  300. Corrupt(kTableFile, 100, 1);
  301. std::string tmp1, tmp2;
  302. ASSERT_OK(db_->Put(WriteOptions(), Key(1000, &tmp1), Value(1000, &tmp2)));
  303. std::string v;
  304. ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  305. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  306. dbi->TEST_CompactMemTable();
  307. ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  308. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  309. }
  310. } // namespace leveldb
  311. int main(int argc, char** argv) {
  312. return leveldb::test::RunAllTests();
  313. }