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