sst_file_manager_impl.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #pragma once
  6. #include <optional>
  7. #include <string>
  8. #include "db/compaction/compaction.h"
  9. #include "file/delete_scheduler.h"
  10. #include "port/port.h"
  11. #include "rocksdb/sst_file_manager.h"
  12. namespace ROCKSDB_NAMESPACE {
  13. class ErrorHandler;
  14. class FileSystem;
  15. class SystemClock;
  16. class Logger;
  17. // SstFileManager is used to track SST and blob files in the DB and control
  18. // their deletion rate. All SstFileManager public functions are thread-safe.
  19. class SstFileManagerImpl : public SstFileManager {
  20. public:
  21. explicit SstFileManagerImpl(const std::shared_ptr<SystemClock>& clock,
  22. const std::shared_ptr<FileSystem>& fs,
  23. const std::shared_ptr<Logger>& logger,
  24. int64_t rate_bytes_per_sec,
  25. double max_trash_db_ratio,
  26. uint64_t bytes_max_delete_chunk);
  27. // No copy
  28. SstFileManagerImpl(const SstFileManagerImpl& sfm) = delete;
  29. SstFileManagerImpl& operator=(const SstFileManagerImpl& sfm) = delete;
  30. ~SstFileManagerImpl();
  31. // DB will call OnAddFile whenever a new sst/blob file is added.
  32. Status OnAddFile(const std::string& file_path);
  33. // Overload where size of the file is provided by the caller rather than
  34. // queried from the filesystem. This is an optimization.
  35. Status OnAddFile(const std::string& file_path, uint64_t file_size);
  36. // DB will call OnDeleteFile whenever a sst/blob file is deleted.
  37. Status OnDeleteFile(const std::string& file_path);
  38. // DB will call OnMoveFile whenever a sst/blob file is move to a new path.
  39. Status OnMoveFile(const std::string& old_path, const std::string& new_path,
  40. uint64_t* file_size = nullptr);
  41. // DB will call OnUntrackFile when closing with an unowned SstFileManager.
  42. Status OnUntrackFile(const std::string& file_path);
  43. // Update the maximum allowed space that should be used by RocksDB, if
  44. // the total size of the SST and blob files exceeds max_allowed_space, writes
  45. // to RocksDB will fail.
  46. //
  47. // Setting max_allowed_space to 0 will disable this feature, maximum allowed
  48. // space will be infinite (Default value).
  49. //
  50. // thread-safe.
  51. void SetMaxAllowedSpaceUsage(uint64_t max_allowed_space) override;
  52. void SetCompactionBufferSize(uint64_t compaction_buffer_size) override;
  53. // Return true if the total size of SST and blob files exceeded the maximum
  54. // allowed space usage.
  55. //
  56. // thread-safe.
  57. bool IsMaxAllowedSpaceReached() override;
  58. bool IsMaxAllowedSpaceReachedIncludingCompactions() override;
  59. // Returns true is there is enough (approximate) space for the specified
  60. // compaction. Space is approximate because this function conservatively
  61. // estimates how much space is currently being used by compactions (i.e.
  62. // if a compaction has started, this function bumps the used space by
  63. // the full compaction size).
  64. bool EnoughRoomForCompaction(ColumnFamilyData* cfd,
  65. const std::vector<CompactionInputFiles>& inputs,
  66. const Status& bg_error);
  67. // Bookkeeping so total_file_sizes_ goes back to normal after compaction
  68. // finishes
  69. void OnCompactionCompletion(Compaction* c);
  70. uint64_t GetCompactionsReservedSize();
  71. // Return the total size of all tracked files.
  72. uint64_t GetTotalSize() override;
  73. // Return a map containing all tracked files and there corresponding sizes.
  74. std::unordered_map<std::string, uint64_t> GetTrackedFiles() override;
  75. // Return delete rate limit in bytes per second.
  76. int64_t GetDeleteRateBytesPerSecond() override;
  77. // Update the delete rate limit in bytes per second.
  78. void SetDeleteRateBytesPerSecond(int64_t delete_rate) override;
  79. // Return trash/DB size ratio where new files will be deleted immediately
  80. double GetMaxTrashDBRatio() override;
  81. // Update trash/DB size ratio where new files will be deleted immediately
  82. void SetMaxTrashDBRatio(double ratio) override;
  83. // Return the total size of trash files
  84. uint64_t GetTotalTrashSize() override;
  85. // Called by each DB instance using this sst file manager to reserve
  86. // disk buffer space for recovery from out of space errors
  87. void ReserveDiskBuffer(uint64_t buffer, const std::string& path);
  88. // Set a flag upon encountering disk full. May enqueue the ErrorHandler
  89. // instance for background polling and recovery
  90. void StartErrorRecovery(ErrorHandler* db, Status bg_error);
  91. // Remove the given Errorhandler instance from the recovery queue. Its
  92. // not guaranteed
  93. bool CancelErrorRecovery(ErrorHandler* db);
  94. // Mark a file as trash and schedule its deletion. If force_bg is set, it
  95. // forces the file to be deleting in the background regardless of DB size,
  96. // except when rate limited delete is disabled.
  97. virtual Status ScheduleFileDeletion(const std::string& file_path,
  98. const std::string& dir_to_sync,
  99. const bool force_bg = false);
  100. // Delete an unaccounted file. The file is deleted immediately if slow
  101. // deletion is disabled. A file with more than 1 hard links will be deleted
  102. // immediately unless force_bg is set. In other cases, files will be scheduled
  103. // for slow deletion, and assigned to the specified bucket if a legitimate one
  104. // is provided. A legitimate bucket is one that is created with the
  105. // `NewTrashBucket` API, and for which `WaitForEmptyTrashBucket` hasn't been
  106. // called yet.
  107. virtual Status ScheduleUnaccountedFileDeletion(
  108. const std::string& file_path, const std::string& dir_to_sync,
  109. const bool force_bg = false,
  110. std::optional<int32_t> bucket = std::nullopt);
  111. // Wait for all files being deleted in the background to finish or for
  112. // destructor to be called.
  113. virtual void WaitForEmptyTrash();
  114. // Creates a new trash bucket. A legitimate bucket is only created and
  115. // returned when slow deletion is enabled.
  116. // For each bucket that is created and used, the user should also call
  117. // `WaitForEmptyTrashBucket` after scheduling file deletions to make sure all
  118. // the trash files are cleared.
  119. std::optional<int32_t> NewTrashBucket();
  120. // Wait for all the files in the specified bucket to be deleted in the
  121. // background or for destructor to be called.
  122. virtual void WaitForEmptyTrashBucket(int32_t bucket);
  123. DeleteScheduler* delete_scheduler() { return &delete_scheduler_; }
  124. // Stop the error recovery background thread. This should be called only
  125. // once in the object's lifetime, and before the destructor
  126. void Close();
  127. void SetStatisticsPtr(const std::shared_ptr<Statistics>& stats) override {
  128. delete_scheduler_.SetStatisticsPtr(stats);
  129. }
  130. private:
  131. // REQUIRES: mutex locked
  132. void OnAddFileImpl(const std::string& file_path, uint64_t file_size);
  133. // REQUIRES: mutex locked
  134. void OnDeleteFileImpl(const std::string& file_path);
  135. void ClearError();
  136. bool CheckFreeSpace() {
  137. return bg_err_.severity() == Status::Severity::kSoftError;
  138. }
  139. std::shared_ptr<SystemClock> clock_;
  140. std::shared_ptr<FileSystem> fs_;
  141. std::shared_ptr<Logger> logger_;
  142. // Mutex to protect tracked_files_, total_files_size_
  143. port::Mutex mu_;
  144. // The summation of the sizes of all files in tracked_files_ map
  145. uint64_t total_files_size_;
  146. // Compactions should only execute if they can leave at least
  147. // this amount of buffer space for logs and flushes
  148. uint64_t compaction_buffer_size_;
  149. // Estimated size of the current ongoing compactions
  150. uint64_t cur_compactions_reserved_size_;
  151. // A map containing all tracked files and there sizes
  152. // file_path => file_size
  153. std::unordered_map<std::string, uint64_t> tracked_files_;
  154. // The maximum allowed space (in bytes) for sst and blob files.
  155. uint64_t max_allowed_space_;
  156. // DeleteScheduler used to throttle file deletion.
  157. DeleteScheduler delete_scheduler_;
  158. port::CondVar cv_;
  159. // Flag to force error recovery thread to exit
  160. bool closing_;
  161. // Background error recovery thread
  162. std::unique_ptr<port::Thread> bg_thread_;
  163. // A path in the filesystem corresponding to this SFM. This is used for
  164. // calling Env::GetFreeSpace. Posix requires a path in the filesystem
  165. std::string path_;
  166. // Save the current background error
  167. Status bg_err_;
  168. // Amount of free disk headroom before allowing recovery from hard errors
  169. uint64_t reserved_disk_buffer_;
  170. // For soft errors, amount of free disk space before we can allow
  171. // compactions to run full throttle. If disk space is below this trigger,
  172. // compactions will be gated by free disk space > input size
  173. uint64_t free_space_trigger_;
  174. // List of database error handler instances tracked by this SstFileManager.
  175. std::list<ErrorHandler*> error_handler_list_;
  176. // Pointer to ErrorHandler instance that is currently processing recovery
  177. ErrorHandler* cur_instance_;
  178. };
  179. } // namespace ROCKSDB_NAMESPACE