作者: 韩晨旭 10225101440 李畅 10225102463
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.

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