小组成员:谢瑞阳、徐翔宇
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.

400 lines
11 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. #if defined(LEVELDB_PLATFORM_WINDOWS)
  21. #include "util/env_windows_test_helper.h"
  22. #endif // defined(LEVELDB_PLATFORM_WINDOWS)
  23. namespace leveldb {
  24. static const int kValueSize = 1000;
  25. class CorruptionTest {
  26. public:
  27. test::ErrorEnv env_;
  28. std::string dbname_;
  29. Cache* tiny_cache_;
  30. Options options_;
  31. DB* db_;
  32. #if defined(LEVELDB_PLATFORM_WINDOWS)
  33. static void SetFileLimits(int mmap_limit) {
  34. EnvWindowsTestHelper::SetReadOnlyMMapLimit(mmap_limit);
  35. }
  36. // TODO(cmumford): Modify corruption_test to use MemEnv and remove.
  37. static void RelaxFilePermissions() {
  38. EnvWindowsTestHelper::RelaxFilePermissions();
  39. }
  40. #endif // defined(LEVELDB_PLATFORM_WINDOWS)
  41. CorruptionTest() {
  42. tiny_cache_ = NewLRUCache(100);
  43. options_.env = &env_;
  44. options_.block_cache = tiny_cache_;
  45. dbname_ = test::TmpDir() + "/corruption_test";
  46. DestroyDB(dbname_, options_);
  47. db_ = nullptr;
  48. options_.create_if_missing = true;
  49. Reopen();
  50. options_.create_if_missing = false;
  51. }
  52. ~CorruptionTest() {
  53. delete db_;
  54. DestroyDB(dbname_, Options());
  55. delete tiny_cache_;
  56. }
  57. Status TryReopen() {
  58. delete db_;
  59. db_ = nullptr;
  60. return DB::Open(options_, dbname_, &db_);
  61. }
  62. void Reopen() {
  63. ASSERT_OK(TryReopen());
  64. }
  65. void RepairDB() {
  66. delete db_;
  67. db_ = nullptr;
  68. ASSERT_OK(::leveldb::RepairDB(dbname_, options_));
  69. }
  70. void Build(int n) {
  71. std::string key_space, value_space;
  72. WriteBatch batch;
  73. for (int i = 0; i < n; i++) {
  74. //if ((i % 100) == 0) fprintf(stderr, "@ %d of %d\n", i, n);
  75. Slice key = Key(i, &key_space);
  76. batch.Clear();
  77. batch.Put(key, Value(i, &value_space));
  78. WriteOptions options;
  79. // Corrupt() doesn't work without this sync on windows; stat reports 0 for
  80. // the file size.
  81. if (i == n - 1) {
  82. options.sync = true;
  83. }
  84. ASSERT_OK(db_->Write(options, &batch));
  85. }
  86. }
  87. void Check(int min_expected, int max_expected) {
  88. int next_expected = 0;
  89. int missed = 0;
  90. int bad_keys = 0;
  91. int bad_values = 0;
  92. int correct = 0;
  93. std::string value_space;
  94. Iterator* iter = db_->NewIterator(ReadOptions());
  95. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  96. uint64_t key;
  97. Slice in(iter->key());
  98. if (in == "" || in == "~") {
  99. // Ignore boundary keys.
  100. continue;
  101. }
  102. if (!ConsumeDecimalNumber(&in, &key) ||
  103. !in.empty() ||
  104. key < next_expected) {
  105. bad_keys++;
  106. continue;
  107. }
  108. missed += (key - next_expected);
  109. next_expected = key + 1;
  110. if (iter->value() != Value(key, &value_space)) {
  111. bad_values++;
  112. } else {
  113. correct++;
  114. }
  115. }
  116. delete iter;
  117. fprintf(stderr,
  118. "expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n",
  119. min_expected, max_expected, correct, bad_keys, bad_values, missed);
  120. ASSERT_LE(min_expected, correct);
  121. ASSERT_GE(max_expected, correct);
  122. }
  123. void Corrupt(FileType filetype, int offset, int bytes_to_corrupt) {
  124. // Pick file to corrupt
  125. std::vector<std::string> filenames;
  126. ASSERT_OK(env_.GetChildren(dbname_, &filenames));
  127. uint64_t number;
  128. FileType type;
  129. std::string fname;
  130. int picked_number = -1;
  131. for (size_t i = 0; i < filenames.size(); i++) {
  132. if (ParseFileName(filenames[i], &number, &type) &&
  133. type == filetype &&
  134. int(number) > picked_number) { // Pick latest file
  135. fname = dbname_ + "/" + filenames[i];
  136. picked_number = number;
  137. }
  138. }
  139. ASSERT_TRUE(!fname.empty()) << filetype;
  140. struct stat sbuf;
  141. if (stat(fname.c_str(), &sbuf) != 0) {
  142. const char* msg = strerror(errno);
  143. ASSERT_TRUE(false) << fname << ": " << msg;
  144. }
  145. if (offset < 0) {
  146. // Relative to end of file; make it absolute
  147. if (-offset > sbuf.st_size) {
  148. offset = 0;
  149. } else {
  150. offset = sbuf.st_size + offset;
  151. }
  152. }
  153. if (offset > sbuf.st_size) {
  154. offset = sbuf.st_size;
  155. }
  156. if (offset + bytes_to_corrupt > sbuf.st_size) {
  157. bytes_to_corrupt = sbuf.st_size - offset;
  158. }
  159. // Do it
  160. std::string contents;
  161. Status s = ReadFileToString(Env::Default(), fname, &contents);
  162. ASSERT_TRUE(s.ok()) << s.ToString();
  163. for (int i = 0; i < bytes_to_corrupt; i++) {
  164. contents[i + offset] ^= 0x80;
  165. }
  166. s = WriteStringToFile(Env::Default(), contents, fname);
  167. ASSERT_TRUE(s.ok()) << s.ToString();
  168. }
  169. int Property(const std::string& name) {
  170. std::string property;
  171. int result;
  172. if (db_->GetProperty(name, &property) &&
  173. sscanf(property.c_str(), "%d", &result) == 1) {
  174. return result;
  175. } else {
  176. return -1;
  177. }
  178. }
  179. // Return the ith key
  180. Slice Key(int i, std::string* storage) {
  181. char buf[100];
  182. snprintf(buf, sizeof(buf), "%016d", i);
  183. storage->assign(buf, strlen(buf));
  184. return Slice(*storage);
  185. }
  186. // Return the value to associate with the specified key
  187. Slice Value(int k, std::string* storage) {
  188. Random r(k);
  189. return test::RandomString(&r, kValueSize, storage);
  190. }
  191. };
  192. TEST(CorruptionTest, Recovery) {
  193. Build(100);
  194. Check(100, 100);
  195. Corrupt(kLogFile, 19, 1); // WriteBatch tag for first record
  196. Corrupt(kLogFile, log::kBlockSize + 1000, 1); // Somewhere in second block
  197. Reopen();
  198. // The 64 records in the first two log blocks are completely lost.
  199. Check(36, 36);
  200. }
  201. TEST(CorruptionTest, RecoverWriteError) {
  202. env_.writable_file_error_ = true;
  203. Status s = TryReopen();
  204. ASSERT_TRUE(!s.ok());
  205. }
  206. TEST(CorruptionTest, NewFileErrorDuringWrite) {
  207. // Do enough writing to force minor compaction
  208. env_.writable_file_error_ = true;
  209. const int num = 3 + (Options().write_buffer_size / kValueSize);
  210. std::string value_storage;
  211. Status s;
  212. for (int i = 0; s.ok() && i < num; i++) {
  213. WriteBatch batch;
  214. batch.Put("a", Value(100, &value_storage));
  215. s = db_->Write(WriteOptions(), &batch);
  216. }
  217. ASSERT_TRUE(!s.ok());
  218. ASSERT_GE(env_.num_writable_file_errors_, 1);
  219. env_.writable_file_error_ = false;
  220. Reopen();
  221. }
  222. TEST(CorruptionTest, TableFile) {
  223. Build(100);
  224. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  225. dbi->TEST_CompactMemTable();
  226. dbi->TEST_CompactRange(0, nullptr, nullptr);
  227. dbi->TEST_CompactRange(1, nullptr, nullptr);
  228. Corrupt(kTableFile, 100, 1);
  229. Check(90, 99);
  230. }
  231. TEST(CorruptionTest, TableFileRepair) {
  232. options_.block_size = 2 * kValueSize; // Limit scope of corruption
  233. options_.paranoid_checks = true;
  234. Reopen();
  235. Build(100);
  236. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  237. dbi->TEST_CompactMemTable();
  238. dbi->TEST_CompactRange(0, nullptr, nullptr);
  239. dbi->TEST_CompactRange(1, nullptr, nullptr);
  240. Corrupt(kTableFile, 100, 1);
  241. RepairDB();
  242. Reopen();
  243. Check(95, 99);
  244. }
  245. TEST(CorruptionTest, TableFileIndexData) {
  246. Build(10000); // Enough to build multiple Tables
  247. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  248. dbi->TEST_CompactMemTable();
  249. Corrupt(kTableFile, -2000, 500);
  250. Reopen();
  251. Check(5000, 9999);
  252. }
  253. TEST(CorruptionTest, MissingDescriptor) {
  254. Build(1000);
  255. RepairDB();
  256. Reopen();
  257. Check(1000, 1000);
  258. }
  259. TEST(CorruptionTest, SequenceNumberRecovery) {
  260. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1"));
  261. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2"));
  262. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3"));
  263. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v4"));
  264. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v5"));
  265. RepairDB();
  266. Reopen();
  267. std::string v;
  268. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  269. ASSERT_EQ("v5", v);
  270. // Write something. If sequence number was not recovered properly,
  271. // it will be hidden by an earlier write.
  272. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v6"));
  273. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  274. ASSERT_EQ("v6", v);
  275. Reopen();
  276. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  277. ASSERT_EQ("v6", v);
  278. }
  279. TEST(CorruptionTest, CorruptedDescriptor) {
  280. ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello"));
  281. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  282. dbi->TEST_CompactMemTable();
  283. dbi->TEST_CompactRange(0, nullptr, nullptr);
  284. Corrupt(kDescriptorFile, 0, 1000);
  285. Status s = TryReopen();
  286. ASSERT_TRUE(!s.ok());
  287. RepairDB();
  288. Reopen();
  289. std::string v;
  290. ASSERT_OK(db_->Get(ReadOptions(), "foo", &v));
  291. ASSERT_EQ("hello", v);
  292. }
  293. TEST(CorruptionTest, CompactionInputError) {
  294. Build(10);
  295. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  296. dbi->TEST_CompactMemTable();
  297. const int last = config::kMaxMemCompactLevel;
  298. ASSERT_EQ(1, Property("leveldb.num-files-at-level" + NumberToString(last)));
  299. Corrupt(kTableFile, 100, 1);
  300. Check(5, 9);
  301. // Force compactions by writing lots of values
  302. Build(10000);
  303. Check(10000, 10000);
  304. }
  305. TEST(CorruptionTest, CompactionInputErrorParanoid) {
  306. options_.paranoid_checks = true;
  307. options_.write_buffer_size = 512 << 10;
  308. Reopen();
  309. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  310. // Make multiple inputs so we need to compact.
  311. for (int i = 0; i < 2; i++) {
  312. Build(10);
  313. dbi->TEST_CompactMemTable();
  314. Corrupt(kTableFile, 100, 1);
  315. env_.SleepForMicroseconds(100000);
  316. }
  317. dbi->CompactRange(nullptr, nullptr);
  318. // Write must fail because of corrupted table
  319. std::string tmp1, tmp2;
  320. Status s = db_->Put(WriteOptions(), Key(5, &tmp1), Value(5, &tmp2));
  321. ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db";
  322. }
  323. TEST(CorruptionTest, UnrelatedKeys) {
  324. Build(10);
  325. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  326. dbi->TEST_CompactMemTable();
  327. Corrupt(kTableFile, 100, 1);
  328. std::string tmp1, tmp2;
  329. ASSERT_OK(db_->Put(WriteOptions(), Key(1000, &tmp1), Value(1000, &tmp2)));
  330. std::string v;
  331. ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  332. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  333. dbi->TEST_CompactMemTable();
  334. ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v));
  335. ASSERT_EQ(Value(1000, &tmp2).ToString(), v);
  336. }
  337. } // namespace leveldb
  338. int main(int argc, char** argv) {
  339. #if defined(LEVELDB_PLATFORM_WINDOWS)
  340. // When Windows maps the contents of a file into memory, even if read/write,
  341. // subsequent attempts to open that file for write access will fail. Forcing
  342. // all RandomAccessFile instances to use base file I/O (e.g. ReadFile)
  343. // allows these tests to open files in order to corrupt their contents.
  344. leveldb::CorruptionTest::SetFileLimits(0);
  345. // Allow this test to write to (and corrupt) files which are normally
  346. // open for exclusive read access.
  347. leveldb::CorruptionTest::RelaxFilePermissions();
  348. #endif // defined(LEVELDB_PLATFORM_WINDOWS)
  349. return leveldb::test::RunAllTests();
  350. }