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.
5 #include "db/db_impl.h"
13 #include "db/builder.h"
14 #include "db/db_iter.h"
15 #include "db/dbformat.h"
16 #include "db/filename.h"
17 #include "db/log_reader.h"
18 #include "db/log_writer.h"
19 #include "db/memtable.h"
20 #include "db/table_cache.h"
21 #include "db/version_set.h"
22 #include "db/write_batch_internal.h"
23 #include "leveldb/db.h"
24 #include "leveldb/env.h"
25 #include "leveldb/status.h"
26 #include "leveldb/table.h"
27 #include "leveldb/table_builder.h"
28 #include "port/port.h"
29 #include "table/block.h"
30 #include "table/merger.h"
31 #include "table/two_level_iterator.h"
32 #include "util/coding.h"
33 #include "util/logging.h"
34 #include "util/mutexlock.h"
38 const int kNumNonTableCacheFiles = 10;
40 // Information kept for every waiting writer
41 struct DBImpl::Writer {
48 explicit Writer(port::Mutex* mu) : cv(mu) { }
51 struct DBImpl::CompactionState {
52 Compaction* const compaction;
54 // Sequence numbers < smallest_snapshot are not significant since we
55 // will never have to service a snapshot below smallest_snapshot.
56 // Therefore if we have seen a sequence number S <= smallest_snapshot,
57 // we can drop all entries for the same key with sequence numbers < S.
58 SequenceNumber smallest_snapshot;
60 // Files produced by compaction
64 InternalKey smallest, largest;
66 std::vector<Output> outputs;
68 // State kept for output being generated
69 WritableFile* outfile;
70 TableBuilder* builder;
74 Output* current_output() { return &outputs[outputs.size()-1]; }
76 explicit CompactionState(Compaction* c)
84 // Fix user-supplied options to be reasonable
85 template <class T,class V>
86 static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
87 if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
88 if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
90 Options SanitizeOptions(const std::string& dbname,
91 const InternalKeyComparator* icmp,
92 const InternalFilterPolicy* ipolicy,
95 result.comparator = icmp;
96 result.filter_policy = (src.filter_policy != NULL) ? ipolicy : NULL;
97 ClipToRange(&result.max_open_files, 64 + kNumNonTableCacheFiles, 50000);
98 ClipToRange(&result.write_buffer_size, 64<<10, 1<<30);
99 ClipToRange(&result.block_size, 1<<10, 4<<20);
100 if (result.info_log == NULL) {
101 // Open a log file in the same directory as the db
102 src.env->CreateDir(dbname); // In case it does not exist
103 src.env->RenameFile(InfoLogFileName(dbname), OldInfoLogFileName(dbname));
104 Status s = src.env->NewLogger(InfoLogFileName(dbname), &result.info_log);
106 // No place suitable for logging
107 result.info_log = NULL;
110 if (result.block_cache == NULL) {
111 result.block_cache = NewLRUCache(8 << 20);
116 DBImpl::DBImpl(const Options& raw_options, const std::string& dbname)
117 : env_(raw_options.env),
118 internal_comparator_(raw_options.comparator),
119 internal_filter_policy_(raw_options.filter_policy),
120 options_(SanitizeOptions(dbname, &internal_comparator_,
121 &internal_filter_policy_, raw_options)),
122 owns_info_log_(options_.info_log != raw_options.info_log),
123 owns_cache_(options_.block_cache != raw_options.block_cache),
126 shutting_down_(NULL),
128 mem_(new MemTable(internal_comparator_)),
134 tmp_batch_(new WriteBatch),
135 bg_compaction_scheduled_(false),
136 manual_compaction_(NULL) {
138 has_imm_.Release_Store(NULL);
140 // Reserve ten files or so for other uses and give the rest to TableCache.
141 const int table_cache_size = options_.max_open_files - kNumNonTableCacheFiles;
142 table_cache_ = new TableCache(dbname_, &options_, table_cache_size);
144 versions_ = new VersionSet(dbname_, &options_, table_cache_,
145 &internal_comparator_);
149 // Wait for background work to finish
151 shutting_down_.Release_Store(this); // Any non-NULL value is ok
152 while (bg_compaction_scheduled_) {
157 if (db_lock_ != NULL) {
158 env_->UnlockFile(db_lock_);
162 if (mem_ != NULL) mem_->Unref();
163 if (imm_ != NULL) imm_->Unref();
169 if (owns_info_log_) {
170 delete options_.info_log;
173 delete options_.block_cache;
177 Status DBImpl::NewDB() {
179 new_db.SetComparatorName(user_comparator()->Name());
180 new_db.SetLogNumber(0);
181 new_db.SetNextFile(2);
182 new_db.SetLastSequence(0);
184 const std::string manifest = DescriptorFileName(dbname_, 1);
186 Status s = env_->NewWritableFile(manifest, &file);
191 log::Writer log(file);
193 new_db.EncodeTo(&record);
194 s = log.AddRecord(record);
201 // Make "CURRENT" file that points to the new manifest file.
202 s = SetCurrentFile(env_, dbname_, 1);
204 env_->DeleteFile(manifest);
209 void DBImpl::MaybeIgnoreError(Status* s) const {
210 if (s->ok() || options_.paranoid_checks) {
213 Log(options_.info_log, "Ignoring error %s", s->ToString().c_str());
218 void DBImpl::DeleteObsoleteFiles() {
219 if (!bg_error_.ok()) {
220 // After a background error, we don't know whether a new version may
221 // or may not have been committed, so we cannot safely garbage collect.
225 // Make a set of all of the live files
226 std::set<uint64_t> live = pending_outputs_;
227 versions_->AddLiveFiles(&live);
229 std::vector<std::string> filenames;
230 env_->GetChildren(dbname_, &filenames); // Ignoring errors on purpose
233 for (size_t i = 0; i < filenames.size(); i++) {
234 if (ParseFileName(filenames[i], &number, &type)) {
238 keep = ((number >= versions_->LogNumber()) ||
239 (number == versions_->PrevLogNumber()));
241 case kDescriptorFile:
242 // Keep my manifest file, and any newer incarnations'
243 // (in case there is a race that allows other incarnations)
244 keep = (number >= versions_->ManifestFileNumber());
247 keep = (live.find(number) != live.end());
250 // Any temp files that are currently being written to must
251 // be recorded in pending_outputs_, which is inserted into "live"
252 keep = (live.find(number) != live.end());
262 if (type == kTableFile) {
263 table_cache_->Evict(number);
265 Log(options_.info_log, "Delete type=%d #%lld\n",
267 static_cast<unsigned long long>(number));
268 env_->DeleteFile(dbname_ + "/" + filenames[i]);
274 Status DBImpl::Recover(VersionEdit* edit) {
277 // Ignore error from CreateDir since the creation of the DB is
278 // committed only when the descriptor is created, and this directory
279 // may already exist from a previous failed creation attempt.
280 env_->CreateDir(dbname_);
281 assert(db_lock_ == NULL);
282 Status s = env_->LockFile(LockFileName(dbname_), &db_lock_);
287 if (!env_->FileExists(CurrentFileName(dbname_))) {
288 if (options_.create_if_missing) {
294 return Status::InvalidArgument(
295 dbname_, "does not exist (create_if_missing is false)");
298 if (options_.error_if_exists) {
299 return Status::InvalidArgument(
300 dbname_, "exists (error_if_exists is true)");
304 s = versions_->Recover();
306 SequenceNumber max_sequence(0);
308 // Recover from all newer log files than the ones named in the
309 // descriptor (new log files may have been added by the previous
310 // incarnation without registering them in the descriptor).
312 // Note that PrevLogNumber() is no longer used, but we pay
313 // attention to it in case we are recovering a database
314 // produced by an older version of leveldb.
315 const uint64_t min_log = versions_->LogNumber();
316 const uint64_t prev_log = versions_->PrevLogNumber();
317 std::vector<std::string> filenames;
318 s = env_->GetChildren(dbname_, &filenames);
322 std::set<uint64_t> expected;
323 versions_->AddLiveFiles(&expected);
326 std::vector<uint64_t> logs;
327 for (size_t i = 0; i < filenames.size(); i++) {
328 if (ParseFileName(filenames[i], &number, &type)) {
329 expected.erase(number);
330 if (type == kLogFile && ((number >= min_log) || (number == prev_log)))
331 logs.push_back(number);
334 if (!expected.empty()) {
336 snprintf(buf, sizeof(buf), "%d missing files; e.g.",
337 static_cast<int>(expected.size()));
338 return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin())));
341 // Recover in the order in which the logs were generated
342 std::sort(logs.begin(), logs.end());
343 for (size_t i = 0; i < logs.size(); i++) {
344 s = RecoverLogFile(logs[i], edit, &max_sequence);
346 // The previous incarnation may not have written any MANIFEST
347 // records after allocating this log number. So we manually
348 // update the file number allocation counter in VersionSet.
349 versions_->MarkFileNumberUsed(logs[i]);
353 if (versions_->LastSequence() < max_sequence) {
354 versions_->SetLastSequence(max_sequence);
362 Status DBImpl::RecoverLogFile(uint64_t log_number,
364 SequenceNumber* max_sequence) {
365 struct LogReporter : public log::Reader::Reporter {
369 Status* status; // NULL if options_.paranoid_checks==false
370 virtual void Corruption(size_t bytes, const Status& s) {
371 Log(info_log, "%s%s: dropping %d bytes; %s",
372 (this->status == NULL ? "(ignoring error) " : ""),
373 fname, static_cast<int>(bytes), s.ToString().c_str());
374 if (this->status != NULL && this->status->ok()) *this->status = s;
381 std::string fname = LogFileName(dbname_, log_number);
382 SequentialFile* file;
383 Status status = env_->NewSequentialFile(fname, &file);
385 MaybeIgnoreError(&status);
389 // Create the log reader.
390 LogReporter reporter;
392 reporter.info_log = options_.info_log;
393 reporter.fname = fname.c_str();
394 reporter.status = (options_.paranoid_checks ? &status : NULL);
395 // We intentionally make log::Reader do checksumming even if
396 // paranoid_checks==false so that corruptions cause entire commits
397 // to be skipped instead of propagating bad information (like overly
398 // large sequence numbers).
399 log::Reader reader(file, &reporter, true/*checksum*/,
400 0/*initial_offset*/);
401 Log(options_.info_log, "Recovering log #%llu",
402 (unsigned long long) log_number);
404 // Read all the records and add to a memtable
408 MemTable* mem = NULL;
409 while (reader.ReadRecord(&record, &scratch) &&
411 if (record.size() < 12) {
413 record.size(), Status::Corruption("log record too small"));
416 WriteBatchInternal::SetContents(&batch, record);
419 mem = new MemTable(internal_comparator_);
422 status = WriteBatchInternal::InsertInto(&batch, mem);
423 MaybeIgnoreError(&status);
427 const SequenceNumber last_seq =
428 WriteBatchInternal::Sequence(&batch) +
429 WriteBatchInternal::Count(&batch) - 1;
430 if (last_seq > *max_sequence) {
431 *max_sequence = last_seq;
434 if (mem->ApproximateMemoryUsage() > options_.write_buffer_size) {
435 status = WriteLevel0Table(mem, edit, NULL);
437 // Reflect errors immediately so that conditions like full
438 // file-systems cause the DB::Open() to fail.
446 if (status.ok() && mem != NULL) {
447 status = WriteLevel0Table(mem, edit, NULL);
448 // Reflect errors immediately so that conditions like full
449 // file-systems cause the DB::Open() to fail.
452 if (mem != NULL) mem->Unref();
457 Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit,
460 const uint64_t start_micros = env_->NowMicros();
462 meta.number = versions_->NewFileNumber();
463 pending_outputs_.insert(meta.number);
464 Iterator* iter = mem->NewIterator();
465 Log(options_.info_log, "Level-0 table #%llu: started",
466 (unsigned long long) meta.number);
471 s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta);
475 Log(options_.info_log, "Level-0 table #%llu: %lld bytes %s",
476 (unsigned long long) meta.number,
477 (unsigned long long) meta.file_size,
478 s.ToString().c_str());
480 pending_outputs_.erase(meta.number);
483 // Note that if file_size is zero, the file has been deleted and
484 // should not be added to the manifest.
486 if (s.ok() && meta.file_size > 0) {
487 const Slice min_user_key = meta.smallest.user_key();
488 const Slice max_user_key = meta.largest.user_key();
490 level = base->PickLevelForMemTableOutput(min_user_key, max_user_key);
492 edit->AddFile(level, meta.number, meta.file_size,
493 meta.smallest, meta.largest);
496 CompactionStats stats;
497 stats.micros = env_->NowMicros() - start_micros;
498 stats.bytes_written = meta.file_size;
499 stats_[level].Add(stats);
503 void DBImpl::CompactMemTable() {
505 assert(imm_ != NULL);
507 // Save the contents of the memtable as a new Table
509 Version* base = versions_->current();
511 Status s = WriteLevel0Table(imm_, &edit, base);
514 if (s.ok() && shutting_down_.Acquire_Load()) {
515 s = Status::IOError("Deleting DB during memtable compaction");
518 // Replace immutable memtable with the generated Table
520 edit.SetPrevLogNumber(0);
521 edit.SetLogNumber(logfile_number_); // Earlier logs no longer needed
522 s = versions_->LogAndApply(&edit, &mutex_);
526 // Commit to the new state
529 has_imm_.Release_Store(NULL);
530 DeleteObsoleteFiles();
532 RecordBackgroundError(s);
536 void DBImpl::CompactRange(const Slice* begin, const Slice* end) {
537 int max_level_with_files = 1;
539 MutexLock l(&mutex_);
540 Version* base = versions_->current();
541 for (int level = 1; level < config::kNumLevels; level++) {
542 if (base->OverlapInLevel(level, begin, end)) {
543 max_level_with_files = level;
547 TEST_CompactMemTable(); // TODO(sanjay): Skip if memtable does not overlap
548 for (int level = 0; level < max_level_with_files; level++) {
549 TEST_CompactRange(level, begin, end);
553 void DBImpl::TEST_CompactRange(int level, const Slice* begin,const Slice* end) {
555 assert(level + 1 < config::kNumLevels);
557 InternalKey begin_storage, end_storage;
559 ManualCompaction manual;
560 manual.level = level;
565 begin_storage = InternalKey(*begin, kMaxSequenceNumber, kValueTypeForSeek);
566 manual.begin = &begin_storage;
571 end_storage = InternalKey(*end, 0, static_cast<ValueType>(0));
572 manual.end = &end_storage;
575 MutexLock l(&mutex_);
576 while (!manual.done && !shutting_down_.Acquire_Load() && bg_error_.ok()) {
577 if (manual_compaction_ == NULL) { // Idle
578 manual_compaction_ = &manual;
579 MaybeScheduleCompaction();
580 } else { // Running either my compaction or another compaction.
584 if (manual_compaction_ == &manual) {
585 // Cancel my manual compaction since we aborted early for some reason.
586 manual_compaction_ = NULL;
590 Status DBImpl::TEST_CompactMemTable() {
591 // NULL batch means just wait for earlier writes to be done
592 Status s = Write(WriteOptions(), NULL);
594 // Wait until the compaction completes
595 MutexLock l(&mutex_);
596 while (imm_ != NULL && bg_error_.ok()) {
606 void DBImpl::RecordBackgroundError(const Status& s) {
608 if (bg_error_.ok()) {
614 void DBImpl::MaybeScheduleCompaction() {
616 if (bg_compaction_scheduled_) {
618 } else if (shutting_down_.Acquire_Load()) {
619 // DB is being deleted; no more background compactions
620 } else if (!bg_error_.ok()) {
621 // Already got an error; no more changes
622 } else if (imm_ == NULL &&
623 manual_compaction_ == NULL &&
624 !versions_->NeedsCompaction()) {
625 // No work to be done
627 bg_compaction_scheduled_ = true;
628 env_->Schedule(&DBImpl::BGWork, this);
632 void DBImpl::BGWork(void* db) {
633 reinterpret_cast<DBImpl*>(db)->BackgroundCall();
636 void DBImpl::BackgroundCall() {
637 MutexLock l(&mutex_);
638 assert(bg_compaction_scheduled_);
639 if (shutting_down_.Acquire_Load()) {
640 // No more background work when shutting down.
641 } else if (!bg_error_.ok()) {
642 // No more background work after a background error.
644 BackgroundCompaction();
647 bg_compaction_scheduled_ = false;
649 // Previous compaction may have produced too many files in a level,
650 // so reschedule another compaction if needed.
651 MaybeScheduleCompaction();
655 void DBImpl::BackgroundCompaction() {
664 bool is_manual = (manual_compaction_ != NULL);
665 InternalKey manual_end;
667 ManualCompaction* m = manual_compaction_;
668 c = versions_->CompactRange(m->level, m->begin, m->end);
669 m->done = (c == NULL);
671 manual_end = c->input(0, c->num_input_files(0) - 1)->largest;
673 Log(options_.info_log,
674 "Manual compaction at level-%d from %s .. %s; will stop at %s\n",
676 (m->begin ? m->begin->DebugString().c_str() : "(begin)"),
677 (m->end ? m->end->DebugString().c_str() : "(end)"),
678 (m->done ? "(end)" : manual_end.DebugString().c_str()));
680 c = versions_->PickCompaction();
686 } else if (!is_manual && c->IsTrivialMove()) {
687 // Move file to next level
688 assert(c->num_input_files(0) == 1);
689 FileMetaData* f = c->input(0, 0);
690 c->edit()->DeleteFile(c->level(), f->number);
691 c->edit()->AddFile(c->level() + 1, f->number, f->file_size,
692 f->smallest, f->largest);
693 status = versions_->LogAndApply(c->edit(), &mutex_);
695 RecordBackgroundError(status);
697 VersionSet::LevelSummaryStorage tmp;
698 Log(options_.info_log, "Moved #%lld to level-%d %lld bytes %s: %s\n",
699 static_cast<unsigned long long>(f->number),
701 static_cast<unsigned long long>(f->file_size),
702 status.ToString().c_str(),
703 versions_->LevelSummary(&tmp));
705 CompactionState* compact = new CompactionState(c);
706 status = DoCompactionWork(compact);
708 RecordBackgroundError(status);
710 CleanupCompaction(compact);
712 DeleteObsoleteFiles();
718 } else if (shutting_down_.Acquire_Load()) {
719 // Ignore compaction errors found during shutting down
721 Log(options_.info_log,
722 "Compaction error: %s", status.ToString().c_str());
726 ManualCompaction* m = manual_compaction_;
731 // We only compacted part of the requested range. Update *m
732 // to the range that is left to be compacted.
733 m->tmp_storage = manual_end;
734 m->begin = &m->tmp_storage;
736 manual_compaction_ = NULL;
740 void DBImpl::CleanupCompaction(CompactionState* compact) {
742 if (compact->builder != NULL) {
743 // May happen if we get a shutdown call in the middle of compaction
744 compact->builder->Abandon();
745 delete compact->builder;
747 assert(compact->outfile == NULL);
749 delete compact->outfile;
750 for (size_t i = 0; i < compact->outputs.size(); i++) {
751 const CompactionState::Output& out = compact->outputs[i];
752 pending_outputs_.erase(out.number);
757 Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) {
758 assert(compact != NULL);
759 assert(compact->builder == NULL);
760 uint64_t file_number;
763 file_number = versions_->NewFileNumber();
764 pending_outputs_.insert(file_number);
765 CompactionState::Output out;
766 out.number = file_number;
767 out.smallest.Clear();
769 compact->outputs.push_back(out);
773 // Make the output file
774 std::string fname = TableFileName(dbname_, file_number);
775 Status s = env_->NewWritableFile(fname, &compact->outfile);
777 compact->builder = new TableBuilder(options_, compact->outfile);
782 Status DBImpl::FinishCompactionOutputFile(CompactionState* compact,
784 assert(compact != NULL);
785 assert(compact->outfile != NULL);
786 assert(compact->builder != NULL);
788 const uint64_t output_number = compact->current_output()->number;
789 assert(output_number != 0);
791 // Check for iterator errors
792 Status s = input->status();
793 const uint64_t current_entries = compact->builder->NumEntries();
795 s = compact->builder->Finish();
797 compact->builder->Abandon();
799 const uint64_t current_bytes = compact->builder->FileSize();
800 compact->current_output()->file_size = current_bytes;
801 compact->total_bytes += current_bytes;
802 delete compact->builder;
803 compact->builder = NULL;
805 // Finish and check for file errors
807 s = compact->outfile->Sync();
810 s = compact->outfile->Close();
812 delete compact->outfile;
813 compact->outfile = NULL;
815 if (s.ok() && current_entries > 0) {
816 // Verify that the table is usable
817 Iterator* iter = table_cache_->NewIterator(ReadOptions(),
823 Log(options_.info_log,
824 "Generated table #%llu: %lld keys, %lld bytes",
825 (unsigned long long) output_number,
826 (unsigned long long) current_entries,
827 (unsigned long long) current_bytes);
834 Status DBImpl::InstallCompactionResults(CompactionState* compact) {
836 Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes",
837 compact->compaction->num_input_files(0),
838 compact->compaction->level(),
839 compact->compaction->num_input_files(1),
840 compact->compaction->level() + 1,
841 static_cast<long long>(compact->total_bytes));
843 // Add compaction outputs
844 compact->compaction->AddInputDeletions(compact->compaction->edit());
845 const int level = compact->compaction->level();
846 for (size_t i = 0; i < compact->outputs.size(); i++) {
847 const CompactionState::Output& out = compact->outputs[i];
848 compact->compaction->edit()->AddFile(
850 out.number, out.file_size, out.smallest, out.largest);
852 return versions_->LogAndApply(compact->compaction->edit(), &mutex_);
855 Status DBImpl::DoCompactionWork(CompactionState* compact) {
856 const uint64_t start_micros = env_->NowMicros();
857 int64_t imm_micros = 0; // Micros spent doing imm_ compactions
859 Log(options_.info_log, "Compacting %d@%d + %d@%d files",
860 compact->compaction->num_input_files(0),
861 compact->compaction->level(),
862 compact->compaction->num_input_files(1),
863 compact->compaction->level() + 1);
865 assert(versions_->NumLevelFiles(compact->compaction->level()) > 0);
866 assert(compact->builder == NULL);
867 assert(compact->outfile == NULL);
868 if (snapshots_.empty()) {
869 compact->smallest_snapshot = versions_->LastSequence();
871 compact->smallest_snapshot = snapshots_.oldest()->number_;
874 // Release mutex while we're actually doing the compaction work
877 Iterator* input = versions_->MakeInputIterator(compact->compaction);
878 input->SeekToFirst();
880 ParsedInternalKey ikey;
881 std::string current_user_key;
882 bool has_current_user_key = false;
883 SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
884 for (; input->Valid() && !shutting_down_.Acquire_Load(); ) {
885 // Prioritize immutable compaction work
886 if (has_imm_.NoBarrier_Load() != NULL) {
887 const uint64_t imm_start = env_->NowMicros();
891 bg_cv_.SignalAll(); // Wakeup MakeRoomForWrite() if necessary
894 imm_micros += (env_->NowMicros() - imm_start);
897 Slice key = input->key();
898 if (compact->compaction->ShouldStopBefore(key) &&
899 compact->builder != NULL) {
900 status = FinishCompactionOutputFile(compact, input);
906 // Handle key/value, add to state, etc.
908 if (!ParseInternalKey(key, &ikey)) {
909 // Do not hide error keys
910 current_user_key.clear();
911 has_current_user_key = false;
912 last_sequence_for_key = kMaxSequenceNumber;
914 if (!has_current_user_key ||
915 user_comparator()->Compare(ikey.user_key,
916 Slice(current_user_key)) != 0) {
917 // First occurrence of this user key
918 current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
919 has_current_user_key = true;
920 last_sequence_for_key = kMaxSequenceNumber;
923 if (last_sequence_for_key <= compact->smallest_snapshot) {
924 // Hidden by an newer entry for same user key
926 } else if (ikey.type == kTypeDeletion &&
927 ikey.sequence <= compact->smallest_snapshot &&
928 compact->compaction->IsBaseLevelForKey(ikey.user_key)) {
929 // For this user key:
930 // (1) there is no data in higher levels
931 // (2) data in lower levels will have larger sequence numbers
932 // (3) data in layers that are being compacted here and have
933 // smaller sequence numbers will be dropped in the next
934 // few iterations of this loop (by rule (A) above).
935 // Therefore this deletion marker is obsolete and can be dropped.
939 last_sequence_for_key = ikey.sequence;
942 Log(options_.info_log,
943 " Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
944 "%d smallest_snapshot: %d",
945 ikey.user_key.ToString().c_str(),
946 (int)ikey.sequence, ikey.type, kTypeValue, drop,
947 compact->compaction->IsBaseLevelForKey(ikey.user_key),
948 (int)last_sequence_for_key, (int)compact->smallest_snapshot);
952 // Open output file if necessary
953 if (compact->builder == NULL) {
954 status = OpenCompactionOutputFile(compact);
959 if (compact->builder->NumEntries() == 0) {
960 compact->current_output()->smallest.DecodeFrom(key);
962 compact->current_output()->largest.DecodeFrom(key);
963 compact->builder->Add(key, input->value());
965 // Close output file if it is big enough
966 if (compact->builder->FileSize() >=
967 compact->compaction->MaxOutputFileSize()) {
968 status = FinishCompactionOutputFile(compact, input);
978 if (status.ok() && shutting_down_.Acquire_Load()) {
979 status = Status::IOError("Deleting DB during compaction");
981 if (status.ok() && compact->builder != NULL) {
982 status = FinishCompactionOutputFile(compact, input);
985 status = input->status();
990 CompactionStats stats;
991 stats.micros = env_->NowMicros() - start_micros - imm_micros;
992 for (int which = 0; which < 2; which++) {
993 for (int i = 0; i < compact->compaction->num_input_files(which); i++) {
994 stats.bytes_read += compact->compaction->input(which, i)->file_size;
997 for (size_t i = 0; i < compact->outputs.size(); i++) {
998 stats.bytes_written += compact->outputs[i].file_size;
1002 stats_[compact->compaction->level() + 1].Add(stats);
1005 status = InstallCompactionResults(compact);
1008 RecordBackgroundError(status);
1010 VersionSet::LevelSummaryStorage tmp;
1011 Log(options_.info_log,
1012 "compacted to: %s", versions_->LevelSummary(&tmp));
1024 static void CleanupIteratorState(void* arg1, void* arg2) {
1025 IterState* state = reinterpret_cast<IterState*>(arg1);
1027 state->mem->Unref();
1028 if (state->imm != NULL) state->imm->Unref();
1029 state->version->Unref();
1030 state->mu->Unlock();
1035 Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
1036 SequenceNumber* latest_snapshot,
1038 IterState* cleanup = new IterState;
1040 *latest_snapshot = versions_->LastSequence();
1042 // Collect together all needed child iterators
1043 std::vector<Iterator*> list;
1044 list.push_back(mem_->NewIterator());
1047 list.push_back(imm_->NewIterator());
1050 versions_->current()->AddIterators(options, &list);
1051 Iterator* internal_iter =
1052 NewMergingIterator(&internal_comparator_, &list[0], list.size());
1053 versions_->current()->Ref();
1055 cleanup->mu = &mutex_;
1056 cleanup->mem = mem_;
1057 cleanup->imm = imm_;
1058 cleanup->version = versions_->current();
1059 internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, NULL);
1063 return internal_iter;
1066 Iterator* DBImpl::TEST_NewInternalIterator() {
1067 SequenceNumber ignored;
1068 uint32_t ignored_seed;
1069 return NewInternalIterator(ReadOptions(), &ignored, &ignored_seed);
1072 int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {
1073 MutexLock l(&mutex_);
1074 return versions_->MaxNextLevelOverlappingBytes();
1077 Status DBImpl::Get(const ReadOptions& options,
1079 std::string* value) {
1081 MutexLock l(&mutex_);
1082 SequenceNumber snapshot;
1083 if (options.snapshot != NULL) {
1084 snapshot = reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_;
1086 snapshot = versions_->LastSequence();
1089 MemTable* mem = mem_;
1090 MemTable* imm = imm_;
1091 Version* current = versions_->current();
1093 if (imm != NULL) imm->Ref();
1096 bool have_stat_update = false;
1097 Version::GetStats stats;
1099 // Unlock while reading from files and memtables
1102 // First look in the memtable, then in the immutable memtable (if any).
1103 LookupKey lkey(key, snapshot);
1104 if (mem->Get(lkey, value, &s)) {
1106 } else if (imm != NULL && imm->Get(lkey, value, &s)) {
1109 s = current->Get(options, lkey, value, &stats);
1110 have_stat_update = true;
1115 if (have_stat_update && current->UpdateStats(stats)) {
1116 MaybeScheduleCompaction();
1119 if (imm != NULL) imm->Unref();
1124 Iterator* DBImpl::NewIterator(const ReadOptions& options) {
1125 SequenceNumber latest_snapshot;
1127 Iterator* iter = NewInternalIterator(options, &latest_snapshot, &seed);
1128 return NewDBIterator(
1129 this, user_comparator(), iter,
1130 (options.snapshot != NULL
1131 ? reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_
1136 void DBImpl::RecordReadSample(Slice key) {
1137 MutexLock l(&mutex_);
1138 if (versions_->current()->RecordReadSample(key)) {
1139 MaybeScheduleCompaction();
1143 const Snapshot* DBImpl::GetSnapshot() {
1144 MutexLock l(&mutex_);
1145 return snapshots_.New(versions_->LastSequence());
1148 void DBImpl::ReleaseSnapshot(const Snapshot* s) {
1149 MutexLock l(&mutex_);
1150 snapshots_.Delete(reinterpret_cast<const SnapshotImpl*>(s));
1153 // Convenience methods
1154 Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
1155 return DB::Put(o, key, val);
1158 Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
1159 return DB::Delete(options, key);
1162 Status DBImpl::Write(const WriteOptions& options, WriteBatch* my_batch) {
1165 w.sync = options.sync;
1168 MutexLock l(&mutex_);
1169 writers_.push_back(&w);
1170 while (!w.done && &w != writers_.front()) {
1177 // May temporarily unlock and wait.
1178 Status status = MakeRoomForWrite(my_batch == NULL);
1179 uint64_t last_sequence = versions_->LastSequence();
1180 Writer* last_writer = &w;
1181 if (status.ok() && my_batch != NULL) { // NULL batch is for compactions
1182 WriteBatch* updates = BuildBatchGroup(&last_writer);
1183 WriteBatchInternal::SetSequence(updates, last_sequence + 1);
1184 last_sequence += WriteBatchInternal::Count(updates);
1186 // Add to log and apply to memtable. We can release the lock
1187 // during this phase since &w is currently responsible for logging
1188 // and protects against concurrent loggers and concurrent writes
1192 status = log_->AddRecord(WriteBatchInternal::Contents(updates));
1193 bool sync_error = false;
1194 if (status.ok() && options.sync) {
1195 status = logfile_->Sync();
1201 status = WriteBatchInternal::InsertInto(updates, mem_);
1205 // The state of the log file is indeterminate: the log record we
1206 // just added may or may not show up when the DB is re-opened.
1207 // So we force the DB into a mode where all future writes fail.
1208 RecordBackgroundError(status);
1211 if (updates == tmp_batch_) tmp_batch_->Clear();
1213 versions_->SetLastSequence(last_sequence);
1217 Writer* ready = writers_.front();
1218 writers_.pop_front();
1220 ready->status = status;
1224 if (ready == last_writer) break;
1227 // Notify new head of write queue
1228 if (!writers_.empty()) {
1229 writers_.front()->cv.Signal();
1235 // REQUIRES: Writer list must be non-empty
1236 // REQUIRES: First writer must have a non-NULL batch
1237 WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) {
1238 assert(!writers_.empty());
1239 Writer* first = writers_.front();
1240 WriteBatch* result = first->batch;
1241 assert(result != NULL);
1243 size_t size = WriteBatchInternal::ByteSize(first->batch);
1245 // Allow the group to grow up to a maximum size, but if the
1246 // original write is small, limit the growth so we do not slow
1247 // down the small write too much.
1248 size_t max_size = 1 << 20;
1249 if (size <= (128<<10)) {
1250 max_size = size + (128<<10);
1253 *last_writer = first;
1254 std::deque<Writer*>::iterator iter = writers_.begin();
1255 ++iter; // Advance past "first"
1256 for (; iter != writers_.end(); ++iter) {
1258 if (w->sync && !first->sync) {
1259 // Do not include a sync write into a batch handled by a non-sync write.
1263 if (w->batch != NULL) {
1264 size += WriteBatchInternal::ByteSize(w->batch);
1265 if (size > max_size) {
1266 // Do not make batch too big
1270 // Append to *result
1271 if (result == first->batch) {
1272 // Switch to temporary batch instead of disturbing caller's batch
1273 result = tmp_batch_;
1274 assert(WriteBatchInternal::Count(result) == 0);
1275 WriteBatchInternal::Append(result, first->batch);
1277 WriteBatchInternal::Append(result, w->batch);
1284 // REQUIRES: mutex_ is held
1285 // REQUIRES: this thread is currently at the front of the writer queue
1286 Status DBImpl::MakeRoomForWrite(bool force) {
1287 mutex_.AssertHeld();
1288 assert(!writers_.empty());
1289 bool allow_delay = !force;
1292 if (!bg_error_.ok()) {
1293 // Yield previous error
1298 versions_->NumLevelFiles(0) >= config::kL0_SlowdownWritesTrigger) {
1299 // We are getting close to hitting a hard limit on the number of
1300 // L0 files. Rather than delaying a single write by several
1301 // seconds when we hit the hard limit, start delaying each
1302 // individual write by 1ms to reduce latency variance. Also,
1303 // this delay hands over some CPU to the compaction thread in
1304 // case it is sharing the same core as the writer.
1306 env_->SleepForMicroseconds(1000);
1307 allow_delay = false; // Do not delay a single write more than once
1309 } else if (!force &&
1310 (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) {
1311 // There is room in current memtable
1313 } else if (imm_ != NULL) {
1314 // We have filled up the current memtable, but the previous
1315 // one is still being compacted, so we wait.
1316 Log(options_.info_log, "Current memtable full; waiting...\n");
1318 } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) {
1319 // There are too many level-0 files.
1320 Log(options_.info_log, "Too many L0 files; waiting...\n");
1323 // Attempt to switch to a new memtable and trigger compaction of old
1324 assert(versions_->PrevLogNumber() == 0);
1325 uint64_t new_log_number = versions_->NewFileNumber();
1326 WritableFile* lfile = NULL;
1327 s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile);
1329 // Avoid chewing through file number space in a tight loop.
1330 versions_->ReuseFileNumber(new_log_number);
1336 logfile_number_ = new_log_number;
1337 log_ = new log::Writer(lfile);
1339 has_imm_.Release_Store(imm_);
1340 mem_ = new MemTable(internal_comparator_);
1342 force = false; // Do not force another compaction if have room
1343 MaybeScheduleCompaction();
1349 bool DBImpl::GetProperty(const Slice& property, std::string* value) {
1352 MutexLock l(&mutex_);
1353 Slice in = property;
1354 Slice prefix("leveldb.");
1355 if (!in.starts_with(prefix)) return false;
1356 in.remove_prefix(prefix.size());
1358 if (in.starts_with("num-files-at-level")) {
1359 in.remove_prefix(strlen("num-files-at-level"));
1361 bool ok = ConsumeDecimalNumber(&in, &level) && in.empty();
1362 if (!ok || level >= config::kNumLevels) {
1366 snprintf(buf, sizeof(buf), "%d",
1367 versions_->NumLevelFiles(static_cast<int>(level)));
1371 } else if (in == "stats") {
1373 snprintf(buf, sizeof(buf),
1375 "Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n"
1376 "--------------------------------------------------\n"
1379 for (int level = 0; level < config::kNumLevels; level++) {
1380 int files = versions_->NumLevelFiles(level);
1381 if (stats_[level].micros > 0 || files > 0) {
1384 "%3d %8d %8.0f %9.0f %8.0f %9.0f\n",
1387 versions_->NumLevelBytes(level) / 1048576.0,
1388 stats_[level].micros / 1e6,
1389 stats_[level].bytes_read / 1048576.0,
1390 stats_[level].bytes_written / 1048576.0);
1395 } else if (in == "sstables") {
1396 *value = versions_->current()->DebugString();
1403 void DBImpl::GetApproximateSizes(
1404 const Range* range, int n,
1406 // TODO(opt): better implementation
1409 MutexLock l(&mutex_);
1410 versions_->current()->Ref();
1411 v = versions_->current();
1414 for (int i = 0; i < n; i++) {
1415 // Convert user_key into a corresponding internal key.
1416 InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek);
1417 InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek);
1418 uint64_t start = versions_->ApproximateOffsetOf(v, k1);
1419 uint64_t limit = versions_->ApproximateOffsetOf(v, k2);
1420 sizes[i] = (limit >= start ? limit - start : 0);
1424 MutexLock l(&mutex_);
1429 // Default implementations of convenience methods that subclasses of DB
1430 // can call if they wish
1431 Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
1433 batch.Put(key, value);
1434 return Write(opt, &batch);
1437 Status DB::Delete(const WriteOptions& opt, const Slice& key) {
1440 return Write(opt, &batch);
1445 Status DB::Open(const Options& options, const std::string& dbname,
1449 DBImpl* impl = new DBImpl(options, dbname);
1450 impl->mutex_.Lock();
1452 Status s = impl->Recover(&edit); // Handles create_if_missing, error_if_exists
1454 uint64_t new_log_number = impl->versions_->NewFileNumber();
1455 WritableFile* lfile;
1456 s = options.env->NewWritableFile(LogFileName(dbname, new_log_number),
1459 edit.SetLogNumber(new_log_number);
1460 impl->logfile_ = lfile;
1461 impl->logfile_number_ = new_log_number;
1462 impl->log_ = new log::Writer(lfile);
1463 s = impl->versions_->LogAndApply(&edit, &impl->mutex_);
1466 impl->DeleteObsoleteFiles();
1467 impl->MaybeScheduleCompaction();
1470 impl->mutex_.Unlock();
1479 Snapshot::~Snapshot() {
1482 Status DestroyDB(const std::string& dbname, const Options& options) {
1483 Env* env = options.env;
1484 std::vector<std::string> filenames;
1485 // Ignore error in case directory does not exist
1486 env->GetChildren(dbname, &filenames);
1487 if (filenames.empty()) {
1488 return Status::OK();
1492 const std::string lockname = LockFileName(dbname);
1493 Status result = env->LockFile(lockname, &lock);
1497 for (size_t i = 0; i < filenames.size(); i++) {
1498 if (ParseFileName(filenames[i], &number, &type) &&
1499 type != kDBLockFile) { // Lock file will be deleted at end
1500 Status del = env->DeleteFile(dbname + "/" + filenames[i]);
1501 if (result.ok() && !del.ok()) {
1506 env->UnlockFile(lock); // Ignore error since state is already gone
1507 env->DeleteFile(lockname);
1508 env->DeleteDir(dbname); // Ignore error in case dir contains other files
1513 } // namespace leveldb