提供基本的ttl测试用例
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.

560 line
16 KiB

  1. // Copyright 2014 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. // This test uses a custom Env to keep track of the state of a filesystem as of
  5. // the last "sync". It then checks for data loss errors by purposely dropping
  6. // file data (or entire files) not protected by a "sync".
  7. #include <map>
  8. #include <set>
  9. #include "gtest/gtest.h"
  10. #include "db/db_impl.h"
  11. #include "db/filename.h"
  12. #include "db/log_format.h"
  13. #include "db/version_set.h"
  14. #include "leveldb/cache.h"
  15. #include "leveldb/db.h"
  16. #include "leveldb/env.h"
  17. #include "leveldb/table.h"
  18. #include "leveldb/write_batch.h"
  19. #include "port/port.h"
  20. #include "port/thread_annotations.h"
  21. #include "util/logging.h"
  22. #include "util/mutexlock.h"
  23. #include "util/testutil.h"
  24. #if defined(_WIN32) && defined(DeleteFile)
  25. // See rationale in env.h
  26. #undef DeleteFile
  27. #endif
  28. namespace leveldb {
  29. static const int kValueSize = 1000;
  30. static const int kMaxNumValues = 2000;
  31. static const size_t kNumIterations = 3;
  32. class FaultInjectionTestEnv;
  33. namespace {
  34. // Assume a filename, and not a directory name like "/foo/bar/"
  35. static std::string GetDirName(const std::string& filename) {
  36. size_t found = filename.find_last_of("/\\");
  37. if (found == std::string::npos) {
  38. return "";
  39. } else {
  40. return filename.substr(0, found);
  41. }
  42. }
  43. Status SyncDir(const std::string& dir) {
  44. // As this is a test it isn't required to *actually* sync this directory.
  45. return Status::OK();
  46. }
  47. // A basic file truncation function suitable for this test.
  48. Status Truncate(const std::string& filename, uint64_t length) {
  49. leveldb::Env* env = leveldb::Env::Default();
  50. SequentialFile* orig_file;
  51. Status s = env->NewSequentialFile(filename, &orig_file);
  52. if (!s.ok()) return s;
  53. char* scratch = new char[length];
  54. leveldb::Slice result;
  55. s = orig_file->Read(length, &result, scratch);
  56. delete orig_file;
  57. if (s.ok()) {
  58. std::string tmp_name = GetDirName(filename) + "/truncate.tmp";
  59. WritableFile* tmp_file;
  60. s = env->NewWritableFile(tmp_name, &tmp_file);
  61. if (s.ok()) {
  62. s = tmp_file->Append(result);
  63. delete tmp_file;
  64. if (s.ok()) {
  65. s = env->RenameFile(tmp_name, filename);
  66. } else {
  67. env->DeleteFile(tmp_name);
  68. }
  69. }
  70. }
  71. delete[] scratch;
  72. return s;
  73. }
  74. struct FileState {
  75. std::string filename_;
  76. int64_t pos_;
  77. int64_t pos_at_last_sync_;
  78. int64_t pos_at_last_flush_;
  79. FileState(const std::string& filename)
  80. : filename_(filename),
  81. pos_(-1),
  82. pos_at_last_sync_(-1),
  83. pos_at_last_flush_(-1) {}
  84. FileState() : pos_(-1), pos_at_last_sync_(-1), pos_at_last_flush_(-1) {}
  85. bool IsFullySynced() const { return pos_ <= 0 || pos_ == pos_at_last_sync_; }
  86. Status DropUnsyncedData() const;
  87. };
  88. } // anonymous namespace
  89. // A wrapper around WritableFile which informs another Env whenever this file
  90. // is written to or sync'ed.
  91. class TestWritableFile : public WritableFile {
  92. public:
  93. TestWritableFile(const FileState& state, WritableFile* f,
  94. FaultInjectionTestEnv* env);
  95. ~TestWritableFile() override;
  96. Status Append(const Slice& data) override;
  97. Status Close() override;
  98. Status Flush() override;
  99. Status Sync() override;
  100. private:
  101. FileState state_;
  102. WritableFile* target_;
  103. bool writable_file_opened_;
  104. FaultInjectionTestEnv* env_;
  105. Status SyncParent();
  106. };
  107. class FaultInjectionTestEnv : public EnvWrapper {
  108. public:
  109. FaultInjectionTestEnv()
  110. : EnvWrapper(Env::Default()), filesystem_active_(true) {}
  111. ~FaultInjectionTestEnv() override = default;
  112. Status NewWritableFile(const std::string& fname,
  113. WritableFile** result) override;
  114. Status NewAppendableFile(const std::string& fname,
  115. WritableFile** result) override;
  116. Status DeleteFile(const std::string& f) override;
  117. Status RenameFile(const std::string& s, const std::string& t) override;
  118. void WritableFileClosed(const FileState& state);
  119. Status DropUnsyncedFileData();
  120. Status DeleteFilesCreatedAfterLastDirSync();
  121. void DirWasSynced();
  122. bool IsFileCreatedSinceLastDirSync(const std::string& filename);
  123. void ResetState();
  124. void UntrackFile(const std::string& f);
  125. // Setting the filesystem to inactive is the test equivalent to simulating a
  126. // system reset. Setting to inactive will freeze our saved filesystem state so
  127. // that it will stop being recorded. It can then be reset back to the state at
  128. // the time of the reset.
  129. bool IsFilesystemActive() LOCKS_EXCLUDED(mutex_) {
  130. MutexLock l(&mutex_);
  131. return filesystem_active_;
  132. }
  133. void SetFilesystemActive(bool active) LOCKS_EXCLUDED(mutex_) {
  134. MutexLock l(&mutex_);
  135. filesystem_active_ = active;
  136. }
  137. private:
  138. port::Mutex mutex_;
  139. std::map<std::string, FileState> db_file_state_ GUARDED_BY(mutex_);
  140. std::set<std::string> new_files_since_last_dir_sync_ GUARDED_BY(mutex_);
  141. bool filesystem_active_ GUARDED_BY(mutex_); // Record flushes, syncs, writes
  142. };
  143. TestWritableFile::TestWritableFile(const FileState& state, WritableFile* f,
  144. FaultInjectionTestEnv* env)
  145. : state_(state), target_(f), writable_file_opened_(true), env_(env) {
  146. assert(f != nullptr);
  147. }
  148. TestWritableFile::~TestWritableFile() {
  149. if (writable_file_opened_) {
  150. Close();
  151. }
  152. delete target_;
  153. }
  154. Status TestWritableFile::Append(const Slice& data) {
  155. Status s = target_->Append(data);
  156. if (s.ok() && env_->IsFilesystemActive()) {
  157. state_.pos_ += data.size();
  158. }
  159. return s;
  160. }
  161. Status TestWritableFile::Close() {
  162. writable_file_opened_ = false;
  163. Status s = target_->Close();
  164. if (s.ok()) {
  165. env_->WritableFileClosed(state_);
  166. }
  167. return s;
  168. }
  169. Status TestWritableFile::Flush() {
  170. Status s = target_->Flush();
  171. if (s.ok() && env_->IsFilesystemActive()) {
  172. state_.pos_at_last_flush_ = state_.pos_;
  173. }
  174. return s;
  175. }
  176. Status TestWritableFile::SyncParent() {
  177. Status s = SyncDir(GetDirName(state_.filename_));
  178. if (s.ok()) {
  179. env_->DirWasSynced();
  180. }
  181. return s;
  182. }
  183. Status TestWritableFile::Sync() {
  184. if (!env_->IsFilesystemActive()) {
  185. return Status::OK();
  186. }
  187. // Ensure new files referred to by the manifest are in the filesystem.
  188. Status s = target_->Sync();
  189. if (s.ok()) {
  190. state_.pos_at_last_sync_ = state_.pos_;
  191. }
  192. if (env_->IsFileCreatedSinceLastDirSync(state_.filename_)) {
  193. Status ps = SyncParent();
  194. if (s.ok() && !ps.ok()) {
  195. s = ps;
  196. }
  197. }
  198. return s;
  199. }
  200. Status FaultInjectionTestEnv::NewWritableFile(const std::string& fname,
  201. WritableFile** result) {
  202. WritableFile* actual_writable_file;
  203. Status s = target()->NewWritableFile(fname, &actual_writable_file);
  204. if (s.ok()) {
  205. FileState state(fname);
  206. state.pos_ = 0;
  207. *result = new TestWritableFile(state, actual_writable_file, this);
  208. // NewWritableFile doesn't append to files, so if the same file is
  209. // opened again then it will be truncated - so forget our saved
  210. // state.
  211. UntrackFile(fname);
  212. MutexLock l(&mutex_);
  213. new_files_since_last_dir_sync_.insert(fname);
  214. }
  215. return s;
  216. }
  217. Status FaultInjectionTestEnv::NewAppendableFile(const std::string& fname,
  218. WritableFile** result) {
  219. WritableFile* actual_writable_file;
  220. Status s = target()->NewAppendableFile(fname, &actual_writable_file);
  221. if (s.ok()) {
  222. FileState state(fname);
  223. state.pos_ = 0;
  224. {
  225. MutexLock l(&mutex_);
  226. if (db_file_state_.count(fname) == 0) {
  227. new_files_since_last_dir_sync_.insert(fname);
  228. } else {
  229. state = db_file_state_[fname];
  230. }
  231. }
  232. *result = new TestWritableFile(state, actual_writable_file, this);
  233. }
  234. return s;
  235. }
  236. Status FaultInjectionTestEnv::DropUnsyncedFileData() {
  237. Status s;
  238. MutexLock l(&mutex_);
  239. for (const auto& kvp : db_file_state_) {
  240. if (!s.ok()) {
  241. break;
  242. }
  243. const FileState& state = kvp.second;
  244. if (!state.IsFullySynced()) {
  245. s = state.DropUnsyncedData();
  246. }
  247. }
  248. return s;
  249. }
  250. void FaultInjectionTestEnv::DirWasSynced() {
  251. MutexLock l(&mutex_);
  252. new_files_since_last_dir_sync_.clear();
  253. }
  254. bool FaultInjectionTestEnv::IsFileCreatedSinceLastDirSync(
  255. const std::string& filename) {
  256. MutexLock l(&mutex_);
  257. return new_files_since_last_dir_sync_.find(filename) !=
  258. new_files_since_last_dir_sync_.end();
  259. }
  260. void FaultInjectionTestEnv::UntrackFile(const std::string& f) {
  261. MutexLock l(&mutex_);
  262. db_file_state_.erase(f);
  263. new_files_since_last_dir_sync_.erase(f);
  264. }
  265. Status FaultInjectionTestEnv::DeleteFile(const std::string& f) {
  266. Status s = EnvWrapper::DeleteFile(f);
  267. EXPECT_LEVELDB_OK(s);
  268. if (s.ok()) {
  269. UntrackFile(f);
  270. }
  271. return s;
  272. }
  273. Status FaultInjectionTestEnv::RenameFile(const std::string& s,
  274. const std::string& t) {
  275. Status ret = EnvWrapper::RenameFile(s, t);
  276. if (ret.ok()) {
  277. MutexLock l(&mutex_);
  278. if (db_file_state_.find(s) != db_file_state_.end()) {
  279. db_file_state_[t] = db_file_state_[s];
  280. db_file_state_.erase(s);
  281. }
  282. if (new_files_since_last_dir_sync_.erase(s) != 0) {
  283. assert(new_files_since_last_dir_sync_.find(t) ==
  284. new_files_since_last_dir_sync_.end());
  285. new_files_since_last_dir_sync_.insert(t);
  286. }
  287. }
  288. return ret;
  289. }
  290. void FaultInjectionTestEnv::ResetState() {
  291. // Since we are not destroying the database, the existing files
  292. // should keep their recorded synced/flushed state. Therefore
  293. // we do not reset db_file_state_ and new_files_since_last_dir_sync_.
  294. SetFilesystemActive(true);
  295. }
  296. Status FaultInjectionTestEnv::DeleteFilesCreatedAfterLastDirSync() {
  297. // Because DeleteFile access this container make a copy to avoid deadlock
  298. mutex_.Lock();
  299. std::set<std::string> new_files(new_files_since_last_dir_sync_.begin(),
  300. new_files_since_last_dir_sync_.end());
  301. mutex_.Unlock();
  302. Status status;
  303. for (const auto& new_file : new_files) {
  304. Status delete_status = DeleteFile(new_file);
  305. if (!delete_status.ok() && status.ok()) {
  306. status = std::move(delete_status);
  307. }
  308. }
  309. return status;
  310. }
  311. void FaultInjectionTestEnv::WritableFileClosed(const FileState& state) {
  312. MutexLock l(&mutex_);
  313. db_file_state_[state.filename_] = state;
  314. }
  315. Status FileState::DropUnsyncedData() const {
  316. int64_t sync_pos = pos_at_last_sync_ == -1 ? 0 : pos_at_last_sync_;
  317. return Truncate(filename_, sync_pos);
  318. }
  319. class FaultInjectionTest : public testing::Test {
  320. public:
  321. enum ExpectedVerifResult { VAL_EXPECT_NO_ERROR, VAL_EXPECT_ERROR };
  322. enum ResetMethod { RESET_DROP_UNSYNCED_DATA, RESET_DELETE_UNSYNCED_FILES };
  323. FaultInjectionTestEnv* env_;
  324. std::string dbname_;
  325. Cache* tiny_cache_;
  326. Options options_;
  327. DB* db_;
  328. FaultInjectionTest()
  329. : env_(new FaultInjectionTestEnv),
  330. tiny_cache_(NewLRUCache(100)),
  331. db_(nullptr) {
  332. dbname_ = testing::TempDir() + "fault_test";
  333. DestroyDB(dbname_, Options()); // Destroy any db from earlier run
  334. options_.reuse_logs = true;
  335. options_.env = env_;
  336. options_.paranoid_checks = true;
  337. options_.block_cache = tiny_cache_;
  338. options_.create_if_missing = true;
  339. }
  340. ~FaultInjectionTest() {
  341. CloseDB();
  342. DestroyDB(dbname_, Options());
  343. delete tiny_cache_;
  344. delete env_;
  345. }
  346. void ReuseLogs(bool reuse) { options_.reuse_logs = reuse; }
  347. void Build(int start_idx, int num_vals) {
  348. std::string key_space, value_space;
  349. WriteBatch batch;
  350. for (int i = start_idx; i < start_idx + num_vals; i++) {
  351. Slice key = Key(i, &key_space);
  352. batch.Clear();
  353. batch.Put(key, Value(i, &value_space));
  354. WriteOptions options;
  355. ASSERT_LEVELDB_OK(db_->Write(options, &batch));
  356. }
  357. }
  358. Status ReadValue(int i, std::string* val) const {
  359. std::string key_space, value_space;
  360. Slice key = Key(i, &key_space);
  361. Value(i, &value_space);
  362. ReadOptions options;
  363. return db_->Get(options, key, val);
  364. }
  365. Status Verify(int start_idx, int num_vals,
  366. ExpectedVerifResult expected) const {
  367. std::string val;
  368. std::string value_space;
  369. Status s;
  370. for (int i = start_idx; i < start_idx + num_vals && s.ok(); i++) {
  371. Value(i, &value_space);
  372. s = ReadValue(i, &val);
  373. if (expected == VAL_EXPECT_NO_ERROR) {
  374. if (s.ok()) {
  375. EXPECT_EQ(value_space, val);
  376. }
  377. } else if (s.ok()) {
  378. fprintf(stderr, "Expected an error at %d, but was OK\n", i);
  379. s = Status::IOError(dbname_, "Expected value error:");
  380. } else {
  381. s = Status::OK(); // An expected error
  382. }
  383. }
  384. return s;
  385. }
  386. // Return the ith key
  387. Slice Key(int i, std::string* storage) const {
  388. char buf[100];
  389. snprintf(buf, sizeof(buf), "%016d", i);
  390. storage->assign(buf, strlen(buf));
  391. return Slice(*storage);
  392. }
  393. // Return the value to associate with the specified key
  394. Slice Value(int k, std::string* storage) const {
  395. Random r(k);
  396. return test::RandomString(&r, kValueSize, storage);
  397. }
  398. Status OpenDB() {
  399. delete db_;
  400. db_ = nullptr;
  401. env_->ResetState();
  402. return DB::Open(options_, dbname_, &db_);
  403. }
  404. void CloseDB() {
  405. delete db_;
  406. db_ = nullptr;
  407. }
  408. void DeleteAllData() {
  409. Iterator* iter = db_->NewIterator(ReadOptions());
  410. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  411. ASSERT_LEVELDB_OK(db_->Delete(WriteOptions(), iter->key()));
  412. }
  413. delete iter;
  414. }
  415. void ResetDBState(ResetMethod reset_method) {
  416. switch (reset_method) {
  417. case RESET_DROP_UNSYNCED_DATA:
  418. ASSERT_LEVELDB_OK(env_->DropUnsyncedFileData());
  419. break;
  420. case RESET_DELETE_UNSYNCED_FILES:
  421. ASSERT_LEVELDB_OK(env_->DeleteFilesCreatedAfterLastDirSync());
  422. break;
  423. default:
  424. assert(false);
  425. }
  426. }
  427. void PartialCompactTestPreFault(int num_pre_sync, int num_post_sync) {
  428. DeleteAllData();
  429. Build(0, num_pre_sync);
  430. db_->CompactRange(nullptr, nullptr);
  431. Build(num_pre_sync, num_post_sync);
  432. }
  433. void PartialCompactTestReopenWithFault(ResetMethod reset_method,
  434. int num_pre_sync, int num_post_sync) {
  435. env_->SetFilesystemActive(false);
  436. CloseDB();
  437. ResetDBState(reset_method);
  438. ASSERT_LEVELDB_OK(OpenDB());
  439. ASSERT_LEVELDB_OK(
  440. Verify(0, num_pre_sync, FaultInjectionTest::VAL_EXPECT_NO_ERROR));
  441. ASSERT_LEVELDB_OK(Verify(num_pre_sync, num_post_sync,
  442. FaultInjectionTest::VAL_EXPECT_ERROR));
  443. }
  444. void NoWriteTestPreFault() {}
  445. void NoWriteTestReopenWithFault(ResetMethod reset_method) {
  446. CloseDB();
  447. ResetDBState(reset_method);
  448. ASSERT_LEVELDB_OK(OpenDB());
  449. }
  450. void DoTest() {
  451. Random rnd(0);
  452. ASSERT_LEVELDB_OK(OpenDB());
  453. for (size_t idx = 0; idx < kNumIterations; idx++) {
  454. int num_pre_sync = rnd.Uniform(kMaxNumValues);
  455. int num_post_sync = rnd.Uniform(kMaxNumValues);
  456. PartialCompactTestPreFault(num_pre_sync, num_post_sync);
  457. PartialCompactTestReopenWithFault(RESET_DROP_UNSYNCED_DATA, num_pre_sync,
  458. num_post_sync);
  459. NoWriteTestPreFault();
  460. NoWriteTestReopenWithFault(RESET_DROP_UNSYNCED_DATA);
  461. PartialCompactTestPreFault(num_pre_sync, num_post_sync);
  462. // No new files created so we expect all values since no files will be
  463. // dropped.
  464. PartialCompactTestReopenWithFault(RESET_DELETE_UNSYNCED_FILES,
  465. num_pre_sync + num_post_sync, 0);
  466. NoWriteTestPreFault();
  467. NoWriteTestReopenWithFault(RESET_DELETE_UNSYNCED_FILES);
  468. }
  469. }
  470. };
  471. TEST_F(FaultInjectionTest, FaultTestNoLogReuse) {
  472. ReuseLogs(false);
  473. DoTest();
  474. }
  475. TEST_F(FaultInjectionTest, FaultTestWithLogReuse) {
  476. ReuseLogs(true);
  477. DoTest();
  478. }
  479. } // namespace leveldb
  480. int main(int argc, char** argv) {
  481. testing::InitGoogleTest(&argc, argv);
  482. return RUN_ALL_TESTS();
  483. }