小组成员:陈予曈,朱陈媛
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

220 lines
7.6 KiB

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