db_impl.h 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. #ifndef STORAGE_LEVELDB_DB_DB_IMPL_H_
  5. #define STORAGE_LEVELDB_DB_DB_IMPL_H_
  6. #include <deque>
  7. #include <set>
  8. #include "db/dbformat.h"
  9. #include "db/log_writer.h"
  10. #include "db/snapshot.h"
  11. #include "leveldb/db.h"
  12. #include "leveldb/env.h"
  13. #include "port/port.h"
  14. #include "port/thread_annotations.h"
  15. namespace leveldb {
  16. class MemTable;
  17. class TableCache;
  18. class Version;
  19. class VersionEdit;
  20. class VersionSet;
  21. class DBImpl : public DB {
  22. public:
  23. DBImpl(const Options& options, const std::string& dbname);
  24. virtual ~DBImpl();
  25. // Implementations of the DB interface
  26. virtual Status Put(const WriteOptions&, const Slice& key, const Slice& value);
  27. virtual Status Delete(const WriteOptions&, const Slice& key);
  28. virtual Status Write(const WriteOptions& options, WriteBatch* updates);
  29. virtual Status Get(const ReadOptions& options,
  30. const Slice& key,
  31. std::string* value);
  32. virtual Iterator* NewIterator(const ReadOptions&);
  33. virtual const Snapshot* GetSnapshot();
  34. virtual void ReleaseSnapshot(const Snapshot* snapshot);
  35. virtual bool GetProperty(const Slice& property, std::string* value);
  36. virtual void GetApproximateSizes(const Range* range, int n, uint64_t* sizes);
  37. virtual void CompactRange(const Slice* begin, const Slice* end);
  38. // Extra methods (for testing) that are not in the public DB interface
  39. // Compact any files in the named level that overlap [*begin,*end]
  40. void TEST_CompactRange(int level, const Slice* begin, const Slice* end);
  41. // Force current memtable contents to be compacted.
  42. Status TEST_CompactMemTable();
  43. // Return an internal iterator over the current state of the database.
  44. // The keys of this iterator are internal keys (see format.h).
  45. // The returned iterator should be deleted when no longer needed.
  46. Iterator* TEST_NewInternalIterator();
  47. // Return the maximum overlapping data (in bytes) at next level for any
  48. // file at a level >= 1.
  49. int64_t TEST_MaxNextLevelOverlappingBytes();
  50. private:
  51. friend class DB;
  52. struct CompactionState;
  53. struct Writer;
  54. Iterator* NewInternalIterator(const ReadOptions&,
  55. SequenceNumber* latest_snapshot);
  56. Status NewDB();
  57. // Recover the descriptor from persistent storage. May do a significant
  58. // amount of work to recover recently logged updates. Any changes to
  59. // be made to the descriptor are added to *edit.
  60. Status Recover(VersionEdit* edit) EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  61. void MaybeIgnoreError(Status* s) const;
  62. // Delete any unneeded files and stale in-memory entries.
  63. void DeleteObsoleteFiles();
  64. // Compact the in-memory write buffer to disk. Switches to a new
  65. // log-file/memtable and writes a new descriptor iff successful.
  66. Status CompactMemTable()
  67. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  68. Status RecoverLogFile(uint64_t log_number,
  69. VersionEdit* edit,
  70. SequenceNumber* max_sequence)
  71. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  72. Status WriteLevel0Table(MemTable* mem, VersionEdit* edit, Version* base)
  73. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  74. Status MakeRoomForWrite(bool force /* compact even if there is room? */)
  75. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  76. WriteBatch* BuildBatchGroup(Writer** last_writer);
  77. void MaybeScheduleCompaction() EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  78. static void BGWork(void* db);
  79. void BackgroundCall();
  80. Status BackgroundCompaction() EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  81. void CleanupCompaction(CompactionState* compact)
  82. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  83. Status DoCompactionWork(CompactionState* compact)
  84. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  85. Status OpenCompactionOutputFile(CompactionState* compact);
  86. Status FinishCompactionOutputFile(CompactionState* compact, Iterator* input);
  87. Status InstallCompactionResults(CompactionState* compact)
  88. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  89. // Constant after construction
  90. Env* const env_;
  91. const InternalKeyComparator internal_comparator_;
  92. const InternalFilterPolicy internal_filter_policy_;
  93. const Options options_; // options_.comparator == &internal_comparator_
  94. bool owns_info_log_;
  95. bool owns_cache_;
  96. const std::string dbname_;
  97. // table_cache_ provides its own synchronization
  98. TableCache* table_cache_;
  99. // Lock over the persistent DB state. Non-NULL iff successfully acquired.
  100. FileLock* db_lock_;
  101. // State below is protected by mutex_
  102. port::Mutex mutex_;
  103. port::AtomicPointer shutting_down_;
  104. port::CondVar bg_cv_; // Signalled when background work finishes
  105. MemTable* mem_;
  106. MemTable* imm_; // Memtable being compacted
  107. port::AtomicPointer has_imm_; // So bg thread can detect non-NULL imm_
  108. WritableFile* logfile_;
  109. uint64_t logfile_number_;
  110. log::Writer* log_;
  111. // Queue of writers.
  112. std::deque<Writer*> writers_;
  113. WriteBatch* tmp_batch_;
  114. SnapshotList snapshots_;
  115. // Set of table files to protect from deletion because they are
  116. // part of ongoing compactions.
  117. std::set<uint64_t> pending_outputs_;
  118. // Has a background compaction been scheduled or is running?
  119. bool bg_compaction_scheduled_;
  120. // Information for a manual compaction
  121. struct ManualCompaction {
  122. int level;
  123. bool done;
  124. const InternalKey* begin; // NULL means beginning of key range
  125. const InternalKey* end; // NULL means end of key range
  126. InternalKey tmp_storage; // Used to keep track of compaction progress
  127. };
  128. ManualCompaction* manual_compaction_;
  129. VersionSet* versions_;
  130. // Have we encountered a background error in paranoid mode?
  131. Status bg_error_;
  132. int consecutive_compaction_errors_;
  133. // Per level compaction stats. stats_[level] stores the stats for
  134. // compactions that produced data for the specified "level".
  135. struct CompactionStats {
  136. int64_t micros;
  137. int64_t bytes_read;
  138. int64_t bytes_written;
  139. CompactionStats() : micros(0), bytes_read(0), bytes_written(0) { }
  140. void Add(const CompactionStats& c) {
  141. this->micros += c.micros;
  142. this->bytes_read += c.bytes_read;
  143. this->bytes_written += c.bytes_written;
  144. }
  145. };
  146. CompactionStats stats_[config::kNumLevels];
  147. // No copying allowed
  148. DBImpl(const DBImpl&);
  149. void operator=(const DBImpl&);
  150. const Comparator* user_comparator() const {
  151. return internal_comparator_.user_comparator();
  152. }
  153. };
  154. // Sanitize db options. The caller should delete result.info_log if
  155. // it is not equal to src.info_log.
  156. extern Options SanitizeOptions(const std::string& db,
  157. const InternalKeyComparator* icmp,
  158. const InternalFilterPolicy* ipolicy,
  159. const Options& src);
  160. } // namespace leveldb
  161. #endif // STORAGE_LEVELDB_DB_DB_IMPL_H_