db_impl.h 7.4 KB

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