db_impl.h 7.3 KB

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