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.

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