作者: 韩晨旭 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.

221 line
7.7 KiB

Add Env::Remove{File,Dir} which obsolete Env::Delete{File,Dir}. The "DeleteFile" method name causes pain for Windows developers, because <windows.h> #defines a DeleteFile macro to DeleteFileW or DeleteFileA. Current code uses workarounds, like #undefining DeleteFile everywhere an Env is declared, implemented, or used. This CL removes the need for workarounds by renaming Env::DeleteFile to Env::RemoveFile. For consistency, Env::DeleteDir is also renamed to Env::RemoveDir. A few internal methods are also renamed for consistency. Software that supports Windows is expected to migrate any Env implementations and usage to Remove{File,Dir}, and never use the name Env::Delete{File,Dir} in its code. The renaming is done in a backwards-compatible way, at the risk of making it slightly more difficult to build a new correct Env implementation. The backwards compatibility is achieved using the following hacks: 1) Env::Remove{File,Dir} methods are added, with a default implementation that calls into Env::Delete{File,Dir}. This makes old Env implementations compatible with code that calls into the updated API. 2) The Env::Delete{File,Dir} methods are no longer pure virtuals. Instead, they gain a default implementation that calls into Env::Remove{File,Dir}. This makes updated Env implementations compatible with code that calls into the old API. The cost of this approach is that it's possible to write an Env without overriding either Rename{File,Dir} or Delete{File,Dir}, without getting a compiler warning. However, attempting to run the test suite will immediately fail with an infinite call stack ending in {Remove,Delete}{File,Dir}, making developers aware of the problem. PiperOrigin-RevId: 288710907
4 年之前
  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 Put(const WriteOptions& options, const Slice& key, const Slice& value,
  33. uint64_t ttl) override;
  34. Status Delete(const WriteOptions&, const Slice& key) override;
  35. Status Write(const WriteOptions& options, WriteBatch* updates) override;
  36. Status Get(const ReadOptions& options, const Slice& key,
  37. std::string* value) override;
  38. Iterator* NewIterator(const ReadOptions&) override;
  39. const Snapshot* GetSnapshot() override;
  40. void ReleaseSnapshot(const Snapshot* snapshot) override;
  41. bool GetProperty(const Slice& property, std::string* value) override;
  42. void GetApproximateSizes(const Range* range, int n, uint64_t* sizes) override;
  43. void CompactRange(const Slice* begin, const Slice* end) override;
  44. // Extra methods (for testing) that are not in the public DB interface
  45. // Compact any files in the named level that overlap [*begin,*end]
  46. void TEST_CompactRange(int level, const Slice* begin, const Slice* end,
  47. bool is_last_level);
  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 is_last_level; // TTL: Used to check if last level with files
  69. bool done;
  70. const InternalKey* begin; // null means beginning of key range
  71. const InternalKey* end; // null means end of key range
  72. InternalKey tmp_storage; // Used to keep track of compaction progress
  73. };
  74. // Per level compaction stats. stats_[level] stores the stats for
  75. // compactions that produced data for the specified "level".
  76. struct CompactionStats {
  77. CompactionStats() : micros(0), bytes_read(0), bytes_written(0) {}
  78. void Add(const CompactionStats& c) {
  79. this->micros += c.micros;
  80. this->bytes_read += c.bytes_read;
  81. this->bytes_written += c.bytes_written;
  82. }
  83. int64_t micros;
  84. int64_t bytes_read;
  85. int64_t bytes_written;
  86. };
  87. Iterator* NewInternalIterator(const ReadOptions&,
  88. SequenceNumber* latest_snapshot,
  89. uint32_t* seed);
  90. Status NewDB();
  91. // Recover the descriptor from persistent storage. May do a significant
  92. // amount of work to recover recently logged updates. Any changes to
  93. // be made to the descriptor are added to *edit.
  94. Status Recover(VersionEdit* edit, bool* save_manifest)
  95. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  96. void MaybeIgnoreError(Status* s) const;
  97. // Delete any unneeded files and stale in-memory entries.
  98. void RemoveObsoleteFiles() EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  99. // Compact the in-memory write buffer to disk. Switches to a new
  100. // log-file/memtable and writes a new descriptor iff successful.
  101. // Errors are recorded in bg_error_.
  102. void CompactMemTable() EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  103. Status RecoverLogFile(uint64_t log_number, bool last_log, bool* save_manifest,
  104. VersionEdit* edit, SequenceNumber* max_sequence)
  105. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  106. Status WriteLevel0Table(MemTable* mem, VersionEdit* edit, Version* base)
  107. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  108. Status MakeRoomForWrite(bool force /* compact even if there is room? */)
  109. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  110. WriteBatch* BuildBatchGroup(Writer** last_writer)
  111. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  112. void RecordBackgroundError(const Status& s);
  113. void MaybeScheduleCompaction() EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  114. static void BGWork(void* db);
  115. void BackgroundCall();
  116. void BackgroundCompaction() EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  117. void CleanupCompaction(CompactionState* compact)
  118. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  119. Status DoCompactionWork(CompactionState* compact)
  120. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  121. Status OpenCompactionOutputFile(CompactionState* compact);
  122. Status FinishCompactionOutputFile(CompactionState* compact, Iterator* input);
  123. Status InstallCompactionResults(CompactionState* compact)
  124. EXCLUSIVE_LOCKS_REQUIRED(mutex_);
  125. const Comparator* user_comparator() const {
  126. return internal_comparator_.user_comparator();
  127. }
  128. // Constant after construction
  129. Env* const env_;
  130. const InternalKeyComparator internal_comparator_;
  131. const InternalFilterPolicy internal_filter_policy_;
  132. const Options options_; // options_.comparator == &internal_comparator_
  133. const bool owns_info_log_;
  134. const bool owns_cache_;
  135. const std::string dbname_;
  136. // table_cache_ provides its own synchronization
  137. TableCache* const table_cache_;
  138. // Lock over the persistent DB state. Non-null iff successfully acquired.
  139. FileLock* db_lock_;
  140. // State below is protected by mutex_
  141. port::Mutex mutex_;
  142. std::atomic<bool> shutting_down_;
  143. port::CondVar background_work_finished_signal_ GUARDED_BY(mutex_);
  144. MemTable* mem_;
  145. MemTable* imm_ GUARDED_BY(mutex_); // Memtable being compacted
  146. std::atomic<bool> has_imm_; // So bg thread can detect non-null imm_
  147. WritableFile* logfile_;
  148. uint64_t logfile_number_ GUARDED_BY(mutex_);
  149. log::Writer* log_;
  150. uint32_t seed_ GUARDED_BY(mutex_); // For sampling.
  151. // Queue of writers.
  152. std::deque<Writer*> writers_ GUARDED_BY(mutex_);
  153. WriteBatch* tmp_batch_ GUARDED_BY(mutex_);
  154. SnapshotList snapshots_ GUARDED_BY(mutex_);
  155. // Set of table files to protect from deletion because they are
  156. // part of ongoing compactions.
  157. std::set<uint64_t> pending_outputs_ GUARDED_BY(mutex_);
  158. // Has a background compaction been scheduled or is running?
  159. bool background_compaction_scheduled_ GUARDED_BY(mutex_);
  160. ManualCompaction* manual_compaction_ GUARDED_BY(mutex_);
  161. VersionSet* const versions_ GUARDED_BY(mutex_);
  162. // Have we encountered a background error in paranoid mode?
  163. Status bg_error_ GUARDED_BY(mutex_);
  164. CompactionStats stats_[config::kNumLevels] GUARDED_BY(mutex_);
  165. };
  166. // Sanitize db options. The caller should delete result.info_log if
  167. // it is not equal to src.info_log.
  168. Options SanitizeOptions(const std::string& db,
  169. const InternalKeyComparator* icmp,
  170. const InternalFilterPolicy* ipolicy,
  171. const Options& src);
  172. } // namespace leveldb
  173. #endif // STORAGE_LEVELDB_DB_DB_IMPL_H_