作者: 韩晨旭 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.

378 lines
10 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. Random rnd_;
  26. std::string dbname_;
  27. Cache* tiny_cache_;
  28. Options options_;
  29. DB* db_;
  30. CorruptionTest() : rnd_(test::RandomSeed()) {
  31. tiny_cache_ = NewLRUCache(100);
  32. options_.env = &env_;
  33. dbname_ = test::TmpDir() + "/db_test";
  34. DestroyDB(dbname_, options_);
  35. db_ = NULL;
  36. options_.create_if_missing = true;
  37. Reopen();
  38. options_.create_if_missing = false;
  39. }
  40. ~CorruptionTest() {
  41. delete db_;
  42. DestroyDB(dbname_, Options());
  43. delete tiny_cache_;
  44. }
  45. Status TryReopen(Options* options = NULL) {
  46. delete db_;
  47. db_ = NULL;
  48. Options opt = (options ? *options : options_);
  49. opt.env = &env_;
  50. opt.block_cache = tiny_cache_;
  51. return DB::Open(opt, dbname_, &db_);
  52. }
  53. void Reopen(Options* options = NULL) {
  54. ASSERT_OK(TryReopen(options));
  55. }
  56. void RepairDB() {
  57. delete db_;
  58. db_ = NULL;
  59. ASSERT_OK(::leveldb::RepairDB(dbname_, options_));
  60. }
  61. void Build(int n) {
  62. std::string key_space, value_space;
  63. WriteBatch batch;
  64. for (int i = 0; i < n; i++) {
  65. //if ((i % 100) == 0) fprintf(stderr, "@ %d of %d\n", i, n);
  66. Slice key = Key(i, &key_space);
  67. batch.Clear();
  68. batch.Put(key, Value(i, &value_space));
  69. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  70. }
  71. }
  72. void Check(int min_expected, int max_expected) {
  73. int next_expected = 0;
  74. int missed = 0;
  75. int bad_keys = 0;
  76. int bad_values = 0;
  77. int correct = 0;
  78. std::string value_space;
  79. Iterator* iter = db_->NewIterator(ReadOptions());
  80. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  81. uint64_t key;
  82. Slice in(iter->key());
  83. if (!ConsumeDecimalNumber(&in, &key) ||
  84. !in.empty() ||
  85. key < next_expected) {
  86. bad_keys++;
  87. continue;
  88. }
  89. missed += (key - next_expected);
  90. next_expected = key + 1;
  91. if (iter->value() != Value(key, &value_space)) {
  92. bad_values++;
  93. } else {
  94. correct++;
  95. }
  96. }
  97. delete iter;
  98. fprintf(stderr,
  99. "expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n",
  100. min_expected, max_expected, correct, bad_keys, bad_values, missed);
  101. ASSERT_LE(min_expected, correct);
  102. ASSERT_GE(max_expected, correct);
  103. }
  104. void Corrupt(FileType filetype, int offset, int bytes_to_corrupt) {
  105. // Pick file to corrupt
  106. std::vector<std::string> filenames;
  107. ASSERT_OK(env_.GetChildren(dbname_, &filenames));
  108. uint64_t number;
  109. LargeValueRef large_ref;
  110. FileType type;
  111. std::vector<std::string> candidates;
  112. for (int i = 0; i < filenames.size(); i++) {
  113. if (ParseFileName(filenames[i], &number, &large_ref, &type) &&
  114. type == filetype) {
  115. candidates.push_back(dbname_ + "/" + filenames[i]);
  116. }
  117. }
  118. ASSERT_TRUE(!candidates.empty()) << filetype;
  119. std::string fname = candidates[rnd_.Uniform(candidates.size())];
  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, "", "~");
  207. dbi->TEST_CompactRange(1, "", "~");
  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. dbi->TEST_CompactRange(0, "", "~");
  216. dbi->TEST_CompactRange(1, "", "~");
  217. Corrupt(kTableFile, -2000, 500);
  218. Reopen();
  219. Check(5000, 9999);
  220. }
  221. TEST(CorruptionTest, MissingDescriptor) {
  222. Build(1000);
  223. RepairDB();
  224. Reopen();
  225. Check(1000, 1000);
  226. }
  227. TEST(CorruptionTest, SequenceNumberRecovery) {
  228. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  229. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  230. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3"));
  231. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v4"));
  232. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v5"));
  233. RepairDB();
  234. Reopen();
  235. std::string v;
  236. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  237. ASSERT_EQ("v5", v);
  238. // Write something. If sequence number was not recovered properly,
  239. // it will be hidden by an earlier write.
  240. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v6"));
  241. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  242. ASSERT_EQ("v6", v);
  243. Reopen();
  244. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  245. ASSERT_EQ("v6", v);
  246. }
  247. TEST(CorruptionTest, LargeValueRecovery) {
  248. Options options;
  249. options.large_value_threshold = 10000;
  250. Reopen(&options);
  251. Random rnd(301);
  252. std::string big;
  253. ASSERT_OK(db_->Put(WriteOptions(),
  254. "foo", test::RandomString(&rnd, 100000, &big)));
  255. std::string v;
  256. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  257. ASSERT_EQ(big, v);
  258. RepairDB();
  259. Reopen();
  260. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  261. ASSERT_EQ(big, v);
  262. Reopen();
  263. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  264. ASSERT_EQ(big, v);
  265. }
  266. TEST(CorruptionTest, CorruptedDescriptor) {
  267. ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello"));
  268. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  269. dbi->TEST_CompactMemTable();
  270. dbi->TEST_CompactRange(0, "", "~");
  271. Corrupt(kDescriptorFile, 0, 1000);
  272. Status s = TryReopen();
  273. ASSERT_TRUE(!s.ok());
  274. RepairDB();
  275. Reopen();
  276. std::string v;
  277. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  278. ASSERT_EQ("hello", v);
  279. }
  280. TEST(CorruptionTest, CompactionInputError) {
  281. Build(10);
  282. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  283. dbi->TEST_CompactMemTable();
  284. ASSERT_EQ(1, Property("leveldb.num-files-at-level0"));
  285. Corrupt(kTableFile, 100, 1);
  286. Check(9, 9);
  287. // Force compactions by writing lots of values
  288. Build(10000);
  289. Check(10000, 10000);
  290. dbi->TEST_CompactRange(0, "", "~");
  291. ASSERT_EQ(0, Property("leveldb.num-files-at-level0"));
  292. }
  293. TEST(CorruptionTest, CompactionInputErrorParanoid) {
  294. Options options;
  295. options.paranoid_checks = true;
  296. options.write_buffer_size = 1048576;
  297. Reopen(&options);
  298. Build(10);
  299. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  300. dbi->TEST_CompactMemTable();
  301. ASSERT_EQ(1, Property("leveldb.num-files-at-level0"));
  302. Corrupt(kTableFile, 100, 1);
  303. Check(9, 9);
  304. // Write must eventually fail because of corrupted table
  305. Status s;
  306. std::string tmp1, tmp2;
  307. for (int i = 0; i < 10000 && s.ok(); i++) {
  308. s = db_->Put(WriteOptions(), Key(i, &tmp1), Value(i, &tmp2));
  309. }
  310. ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db";
  311. }
  312. TEST(CorruptionTest, UnrelatedKeys) {
  313. Build(10);
  314. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  315. dbi->TEST_CompactMemTable();
  316. Corrupt(kTableFile, 100, 1);
  317. std::string tmp1, tmp2;
  318. ASSERT_OK(db_->Put(WriteOptions(), Key(1000, &tmp1), Value(1000, &tmp2)));
  319. std::string v;
  320. ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  321. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  322. dbi->TEST_CompactMemTable();
  323. ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  324. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  325. }
  326. }
  327. int main(int argc, char** argv) {
  328. return leveldb::test::RunAllTests();
  329. }