Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

354 rader
9.4 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. FileType type;
  110. std::vector<std::string> candidates;
  111. for (int i = 0; i < filenames.size(); i++) {
  112. if (ParseFileName(filenames[i], &number, &type) &&
  113. type == filetype) {
  114. candidates.push_back(dbname_ + "/" + filenames[i]);
  115. }
  116. }
  117. ASSERT_TRUE(!candidates.empty()) << filetype;
  118. std::string fname = candidates[rnd_.Uniform(candidates.size())];
  119. struct stat sbuf;
  120. if (stat(fname.c_str(), &sbuf) != 0) {
  121. const char* msg = strerror(errno);
  122. ASSERT_TRUE(false) << fname << ": " << msg;
  123. }
  124. if (offset < 0) {
  125. // Relative to end of file; make it absolute
  126. if (-offset > sbuf.st_size) {
  127. offset = 0;
  128. } else {
  129. offset = sbuf.st_size + offset;
  130. }
  131. }
  132. if (offset > sbuf.st_size) {
  133. offset = sbuf.st_size;
  134. }
  135. if (offset + bytes_to_corrupt > sbuf.st_size) {
  136. bytes_to_corrupt = sbuf.st_size - offset;
  137. }
  138. // Do it
  139. std::string contents;
  140. Status s = ReadFileToString(Env::Default(), fname, &contents);
  141. ASSERT_TRUE(s.ok()) << s.ToString();
  142. for (int i = 0; i < bytes_to_corrupt; i++) {
  143. contents[i + offset] ^= 0x80;
  144. }
  145. s = WriteStringToFile(Env::Default(), contents, fname);
  146. ASSERT_TRUE(s.ok()) << s.ToString();
  147. }
  148. int Property(const std::string& name) {
  149. std::string property;
  150. int result;
  151. if (db_->GetProperty(name, &property) &&
  152. sscanf(property.c_str(), "%d", &result) == 1) {
  153. return result;
  154. } else {
  155. return -1;
  156. }
  157. }
  158. // Return the ith key
  159. Slice Key(int i, std::string* storage) {
  160. char buf[100];
  161. snprintf(buf, sizeof(buf), "%016d", i);
  162. storage->assign(buf, strlen(buf));
  163. return Slice(*storage);
  164. }
  165. // Return the value to associate with the specified key
  166. Slice Value(int k, std::string* storage) {
  167. Random r(k);
  168. return test::RandomString(&r, kValueSize, storage);
  169. }
  170. };
  171. TEST(CorruptionTest, Recovery) {
  172. Build(100);
  173. Check(100, 100);
  174. Corrupt(kLogFile, 19, 1); // WriteBatch tag for first record
  175. Corrupt(kLogFile, log::kBlockSize + 1000, 1); // Somewhere in second block
  176. Reopen();
  177. // The 64 records in the first two log blocks are completely lost.
  178. Check(36, 36);
  179. }
  180. TEST(CorruptionTest, RecoverWriteError) {
  181. env_.writable_file_error_ = true;
  182. Status s = TryReopen();
  183. ASSERT_TRUE(!s.ok());
  184. }
  185. TEST(CorruptionTest, NewFileErrorDuringWrite) {
  186. // Do enough writing to force minor compaction
  187. env_.writable_file_error_ = true;
  188. const int num = 3 + (Options().write_buffer_size / kValueSize);
  189. std::string value_storage;
  190. Status s;
  191. for (int i = 0; s.ok() && i < num; i++) {
  192. WriteBatch batch;
  193. batch.Put("a", Value(100, &value_storage));
  194. s = db_->Write(WriteOptions(), &batch);
  195. }
  196. ASSERT_TRUE(!s.ok());
  197. ASSERT_GE(env_.num_writable_file_errors_, 1);
  198. env_.writable_file_error_ = false;
  199. Reopen();
  200. }
  201. TEST(CorruptionTest, TableFile) {
  202. Build(100);
  203. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  204. dbi->TEST_CompactMemTable();
  205. dbi->TEST_CompactRange(0, "", "~");
  206. dbi->TEST_CompactRange(1, "", "~");
  207. Corrupt(kTableFile, 100, 1);
  208. Check(99, 99);
  209. }
  210. TEST(CorruptionTest, TableFileIndexData) {
  211. Build(10000); // Enough to build multiple Tables
  212. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  213. dbi->TEST_CompactMemTable();
  214. dbi->TEST_CompactRange(0, "", "~");
  215. dbi->TEST_CompactRange(1, "", "~");
  216. Corrupt(kTableFile, -2000, 500);
  217. Reopen();
  218. Check(5000, 9999);
  219. }
  220. TEST(CorruptionTest, MissingDescriptor) {
  221. Build(1000);
  222. RepairDB();
  223. Reopen();
  224. Check(1000, 1000);
  225. }
  226. TEST(CorruptionTest, SequenceNumberRecovery) {
  227. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  228. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  229. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3"));
  230. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v4"));
  231. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v5"));
  232. RepairDB();
  233. Reopen();
  234. std::string v;
  235. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  236. ASSERT_EQ("v5", v);
  237. // Write something. If sequence number was not recovered properly,
  238. // it will be hidden by an earlier write.
  239. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v6"));
  240. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  241. ASSERT_EQ("v6", v);
  242. Reopen();
  243. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  244. ASSERT_EQ("v6", v);
  245. }
  246. TEST(CorruptionTest, CorruptedDescriptor) {
  247. ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello"));
  248. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  249. dbi->TEST_CompactMemTable();
  250. dbi->TEST_CompactRange(0, "", "~");
  251. Corrupt(kDescriptorFile, 0, 1000);
  252. Status s = TryReopen();
  253. ASSERT_TRUE(!s.ok());
  254. RepairDB();
  255. Reopen();
  256. std::string v;
  257. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  258. ASSERT_EQ("hello", v);
  259. }
  260. TEST(CorruptionTest, CompactionInputError) {
  261. Build(10);
  262. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  263. dbi->TEST_CompactMemTable();
  264. ASSERT_EQ(1, Property("leveldb.num-files-at-level0"));
  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. dbi->TEST_CompactRange(0, "", "~");
  271. ASSERT_EQ(0, Property("leveldb.num-files-at-level0"));
  272. }
  273. TEST(CorruptionTest, CompactionInputErrorParanoid) {
  274. Options options;
  275. options.paranoid_checks = true;
  276. options.write_buffer_size = 1048576;
  277. Reopen(&options);
  278. Build(10);
  279. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  280. dbi->TEST_CompactMemTable();
  281. ASSERT_EQ(1, Property("leveldb.num-files-at-level0"));
  282. Corrupt(kTableFile, 100, 1);
  283. Check(9, 9);
  284. // Write must eventually fail because of corrupted table
  285. Status s;
  286. std::string tmp1, tmp2;
  287. for (int i = 0; i < 10000 && s.ok(); i++) {
  288. s = db_->Put(WriteOptions(), Key(i, &tmp1), Value(i, &tmp2));
  289. }
  290. ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db";
  291. }
  292. TEST(CorruptionTest, UnrelatedKeys) {
  293. Build(10);
  294. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  295. dbi->TEST_CompactMemTable();
  296. Corrupt(kTableFile, 100, 1);
  297. std::string tmp1, tmp2;
  298. ASSERT_OK(db_->Put(WriteOptions(), Key(1000, &tmp1), Value(1000, &tmp2)));
  299. std::string v;
  300. ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  301. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  302. dbi->TEST_CompactMemTable();
  303. ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  304. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  305. }
  306. }
  307. int main(int argc, char** argv) {
  308. return leveldb::test::RunAllTests();
  309. }