小组成员:姚凯文(kevinyao0901),姜嘉琪
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.

1666 lines
52 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 years ago
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 years ago
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 years ago
Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 years ago
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 years ago
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 years ago
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 years ago
Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 years ago
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 years ago
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 years ago
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 years ago
  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. #include "db/db_impl.h"
  5. #include <algorithm>
  6. #include <atomic>
  7. #include <cstdint>
  8. #include <cstdio>
  9. #include <set>
  10. #include <string>
  11. #include <vector>
  12. #include "db/builder.h"
  13. #include "db/db_iter.h"
  14. #include "db/dbformat.h"
  15. #include "db/filename.h"
  16. #include "db/log_reader.h"
  17. #include "db/log_writer.h"
  18. #include "db/memtable.h"
  19. #include "db/table_cache.h"
  20. #include "db/version_set.h"
  21. #include "db/write_batch_internal.h"
  22. #include "leveldb/db.h"
  23. #include "leveldb/env.h"
  24. #include "leveldb/status.h"
  25. #include "leveldb/table.h"
  26. #include "leveldb/table_builder.h"
  27. #include "port/port.h"
  28. #include "table/block.h"
  29. #include "table/merger.h"
  30. #include "table/two_level_iterator.h"
  31. #include "util/coding.h"
  32. #include "util/logging.h"
  33. #include "util/mutexlock.h"
  34. namespace leveldb {
  35. const int kNumNonTableCacheFiles = 10;
  36. //TTL ToDo : add func for TTL Put
  37. void AppendExpirationTime(std::string* value, uint64_t expiration_time) {
  38. // 将过期时间戳(64位整数)附加到值的前面
  39. value->append(reinterpret_cast<const char*>(&expiration_time), sizeof(expiration_time));
  40. }
  41. uint64_t GetCurrentTime() {
  42. // 返回当前的Unix时间戳
  43. return static_cast<uint64_t>(time(nullptr));
  44. }
  45. // 解析过期时间戳
  46. uint64_t ParseExpirationTime(const std::string& value) {
  47. // 假设过期时间戳在值的前 8 字节,以大端序存储
  48. assert(value.size() >= sizeof(uint64_t));
  49. uint64_t expiration_time;
  50. memcpy(&expiration_time, value.data(), sizeof(uint64_t));
  51. return expiration_time;
  52. }
  53. // 解析出实际的值(去掉前面的过期时间戳部分)
  54. std::string ParseActualValue(const std::string& value) {
  55. // 去掉前 8 字节(存储过期时间戳),返回实际值
  56. return value.substr(sizeof(uint64_t));
  57. }
  58. //finish modify
  59. // Information kept for every waiting writer
  60. struct DBImpl::Writer {
  61. explicit Writer(port::Mutex* mu)
  62. : batch(nullptr), sync(false), done(false), cv(mu) {}
  63. Status status;
  64. WriteBatch* batch;
  65. bool sync;
  66. bool done;
  67. port::CondVar cv;
  68. };
  69. struct DBImpl::CompactionState {
  70. // Files produced by compaction
  71. struct Output {
  72. uint64_t number;
  73. uint64_t file_size;
  74. InternalKey smallest, largest;
  75. };
  76. Output* current_output() { return &outputs[outputs.size() - 1]; }
  77. explicit CompactionState(Compaction* c)
  78. : compaction(c),
  79. smallest_snapshot(0),
  80. outfile(nullptr),
  81. builder(nullptr),
  82. total_bytes(0) {}
  83. Compaction* const compaction;
  84. // Sequence numbers < smallest_snapshot are not significant since we
  85. // will never have to service a snapshot below smallest_snapshot.
  86. // Therefore if we have seen a sequence number S <= smallest_snapshot,
  87. // we can drop all entries for the same key with sequence numbers < S.
  88. SequenceNumber smallest_snapshot;
  89. std::vector<Output> outputs;
  90. // State kept for output being generated
  91. WritableFile* outfile;
  92. TableBuilder* builder;
  93. uint64_t total_bytes;
  94. };
  95. // Fix user-supplied options to be reasonable
  96. template <class T, class V>
  97. static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
  98. if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
  99. if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
  100. }
  101. Options SanitizeOptions(const std::string& dbname,
  102. const InternalKeyComparator* icmp,
  103. const InternalFilterPolicy* ipolicy,
  104. const Options& src) {
  105. Options result = src;
  106. result.comparator = icmp;
  107. result.filter_policy = (src.filter_policy != nullptr) ? ipolicy : nullptr;
  108. ClipToRange(&result.max_open_files, 64 + kNumNonTableCacheFiles, 50000);
  109. ClipToRange(&result.write_buffer_size, 64 << 10, 1 << 30);
  110. ClipToRange(&result.max_file_size, 1 << 20, 1 << 30);
  111. ClipToRange(&result.block_size, 1 << 10, 4 << 20);
  112. if (result.info_log == nullptr) {
  113. // Open a log file in the same directory as the db
  114. src.env->CreateDir(dbname); // In case it does not exist
  115. src.env->RenameFile(InfoLogFileName(dbname), OldInfoLogFileName(dbname));
  116. Status s = src.env->NewLogger(InfoLogFileName(dbname), &result.info_log);
  117. if (!s.ok()) {
  118. // No place suitable for logging
  119. result.info_log = nullptr;
  120. }
  121. }
  122. if (result.block_cache == nullptr) {
  123. result.block_cache = NewLRUCache(8 << 20);
  124. }
  125. return result;
  126. }
  127. static int TableCacheSize(const Options& sanitized_options) {
  128. // Reserve ten files or so for other uses and give the rest to TableCache.
  129. return sanitized_options.max_open_files - kNumNonTableCacheFiles;
  130. }
  131. DBImpl::DBImpl(const Options& raw_options, const std::string& dbname)
  132. : env_(raw_options.env),
  133. internal_comparator_(raw_options.comparator),
  134. internal_filter_policy_(raw_options.filter_policy),
  135. options_(SanitizeOptions(dbname, &internal_comparator_,
  136. &internal_filter_policy_, raw_options)),
  137. owns_info_log_(options_.info_log != raw_options.info_log),
  138. owns_cache_(options_.block_cache != raw_options.block_cache),
  139. dbname_(dbname),
  140. table_cache_(new TableCache(dbname_, options_, TableCacheSize(options_))),
  141. db_lock_(nullptr),
  142. shutting_down_(false),
  143. background_work_finished_signal_(&mutex_),
  144. mem_(nullptr),
  145. imm_(nullptr),
  146. has_imm_(false),
  147. logfile_(nullptr),
  148. logfile_number_(0),
  149. log_(nullptr),
  150. seed_(0),
  151. tmp_batch_(new WriteBatch),
  152. background_compaction_scheduled_(false),
  153. manual_compaction_(nullptr),
  154. versions_(new VersionSet(dbname_, &options_, table_cache_,
  155. &internal_comparator_)) {}
  156. DBImpl::~DBImpl() {
  157. // Wait for background work to finish.
  158. mutex_.Lock();
  159. shutting_down_.store(true, std::memory_order_release);
  160. while (background_compaction_scheduled_) {
  161. background_work_finished_signal_.Wait();
  162. }
  163. mutex_.Unlock();
  164. if (db_lock_ != nullptr) {
  165. env_->UnlockFile(db_lock_);
  166. }
  167. delete versions_;
  168. if (mem_ != nullptr) mem_->Unref();
  169. if (imm_ != nullptr) imm_->Unref();
  170. delete tmp_batch_;
  171. delete log_;
  172. delete logfile_;
  173. delete table_cache_;
  174. if (owns_info_log_) {
  175. delete options_.info_log;
  176. }
  177. if (owns_cache_) {
  178. delete options_.block_cache;
  179. }
  180. }
  181. Status DBImpl::NewDB() {
  182. VersionEdit new_db;
  183. new_db.SetComparatorName(user_comparator()->Name());
  184. new_db.SetLogNumber(0);
  185. new_db.SetNextFile(2);
  186. new_db.SetLastSequence(0);
  187. const std::string manifest = DescriptorFileName(dbname_, 1);
  188. WritableFile* file;
  189. Status s = env_->NewWritableFile(manifest, &file);
  190. if (!s.ok()) {
  191. return s;
  192. }
  193. {
  194. log::Writer log(file);
  195. std::string record;
  196. new_db.EncodeTo(&record);
  197. s = log.AddRecord(record);
  198. if (s.ok()) {
  199. s = file->Sync();
  200. }
  201. if (s.ok()) {
  202. s = file->Close();
  203. }
  204. }
  205. delete file;
  206. if (s.ok()) {
  207. // Make "CURRENT" file that points to the new manifest file.
  208. s = SetCurrentFile(env_, dbname_, 1);
  209. } else {
  210. env_->RemoveFile(manifest);
  211. }
  212. return s;
  213. }
  214. void DBImpl::MaybeIgnoreError(Status* s) const {
  215. if (s->ok() || options_.paranoid_checks) {
  216. // No change needed
  217. } else {
  218. Log(options_.info_log, "Ignoring error %s", s->ToString().c_str());
  219. *s = Status::OK();
  220. }
  221. }
  222. void DBImpl::RemoveObsoleteFiles() {
  223. mutex_.AssertHeld();
  224. if (!bg_error_.ok()) {
  225. // After a background error, we don't know whether a new version may
  226. // or may not have been committed, so we cannot safely garbage collect.
  227. return;
  228. }
  229. // Make a set of all of the live files
  230. std::set<uint64_t> live = pending_outputs_;
  231. versions_->AddLiveFiles(&live);
  232. std::vector<std::string> filenames;
  233. env_->GetChildren(dbname_, &filenames); // Ignoring errors on purpose
  234. uint64_t number;
  235. FileType type;
  236. std::vector<std::string> files_to_delete;
  237. for (std::string& filename : filenames) {
  238. if (ParseFileName(filename, &number, &type)) {
  239. bool keep = true;
  240. switch (type) {
  241. case kLogFile:
  242. keep = ((number >= versions_->LogNumber()) ||
  243. (number == versions_->PrevLogNumber()));
  244. break;
  245. case kDescriptorFile:
  246. // Keep my manifest file, and any newer incarnations'
  247. // (in case there is a race that allows other incarnations)
  248. keep = (number >= versions_->ManifestFileNumber());
  249. break;
  250. case kTableFile:
  251. keep = (live.find(number) != live.end());
  252. break;
  253. case kTempFile:
  254. // Any temp files that are currently being written to must
  255. // be recorded in pending_outputs_, which is inserted into "live"
  256. keep = (live.find(number) != live.end());
  257. break;
  258. case kCurrentFile:
  259. case kDBLockFile:
  260. case kInfoLogFile:
  261. keep = true;
  262. break;
  263. }
  264. if (!keep) {
  265. files_to_delete.push_back(std::move(filename));
  266. if (type == kTableFile) {
  267. table_cache_->Evict(number);
  268. }
  269. Log(options_.info_log, "Delete type=%d #%lld\n", static_cast<int>(type),
  270. static_cast<unsigned long long>(number));
  271. }
  272. }
  273. }
  274. // While deleting all files unblock other threads. All files being deleted
  275. // have unique names which will not collide with newly created files and
  276. // are therefore safe to delete while allowing other threads to proceed.
  277. mutex_.Unlock();
  278. for (const std::string& filename : files_to_delete) {
  279. env_->RemoveFile(dbname_ + "/" + filename);
  280. }
  281. mutex_.Lock();
  282. }
  283. Status DBImpl::Recover(VersionEdit* edit, bool* save_manifest) {
  284. mutex_.AssertHeld();
  285. // Ignore error from CreateDir since the creation of the DB is
  286. // committed only when the descriptor is created, and this directory
  287. // may already exist from a previous failed creation attempt.
  288. env_->CreateDir(dbname_);
  289. assert(db_lock_ == nullptr);
  290. Status s = env_->LockFile(LockFileName(dbname_), &db_lock_);
  291. if (!s.ok()) {
  292. return s;
  293. }
  294. if (!env_->FileExists(CurrentFileName(dbname_))) {
  295. if (options_.create_if_missing) {
  296. Log(options_.info_log, "Creating DB %s since it was missing.",
  297. dbname_.c_str());
  298. s = NewDB();
  299. if (!s.ok()) {
  300. return s;
  301. }
  302. } else {
  303. return Status::InvalidArgument(
  304. dbname_, "does not exist (create_if_missing is false)");
  305. }
  306. } else {
  307. if (options_.error_if_exists) {
  308. return Status::InvalidArgument(dbname_,
  309. "exists (error_if_exists is true)");
  310. }
  311. }
  312. s = versions_->Recover(save_manifest);
  313. if (!s.ok()) {
  314. return s;
  315. }
  316. SequenceNumber max_sequence(0);
  317. // Recover from all newer log files than the ones named in the
  318. // descriptor (new log files may have been added by the previous
  319. // incarnation without registering them in the descriptor).
  320. //
  321. // Note that PrevLogNumber() is no longer used, but we pay
  322. // attention to it in case we are recovering a database
  323. // produced by an older version of leveldb.
  324. const uint64_t min_log = versions_->LogNumber();
  325. const uint64_t prev_log = versions_->PrevLogNumber();
  326. std::vector<std::string> filenames;
  327. s = env_->GetChildren(dbname_, &filenames);
  328. if (!s.ok()) {
  329. return s;
  330. }
  331. std::set<uint64_t> expected;
  332. versions_->AddLiveFiles(&expected);
  333. uint64_t number;
  334. FileType type;
  335. std::vector<uint64_t> logs;
  336. for (size_t i = 0; i < filenames.size(); i++) {
  337. if (ParseFileName(filenames[i], &number, &type)) {
  338. expected.erase(number);
  339. if (type == kLogFile && ((number >= min_log) || (number == prev_log)))
  340. logs.push_back(number);
  341. }
  342. }
  343. if (!expected.empty()) {
  344. char buf[50];
  345. std::snprintf(buf, sizeof(buf), "%d missing files; e.g.",
  346. static_cast<int>(expected.size()));
  347. return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin())));
  348. }
  349. // Recover in the order in which the logs were generated
  350. std::sort(logs.begin(), logs.end());
  351. for (size_t i = 0; i < logs.size(); i++) {
  352. s = RecoverLogFile(logs[i], (i == logs.size() - 1), save_manifest, edit,
  353. &max_sequence);
  354. if (!s.ok()) {
  355. return s;
  356. }
  357. // The previous incarnation may not have written any MANIFEST
  358. // records after allocating this log number. So we manually
  359. // update the file number allocation counter in VersionSet.
  360. versions_->MarkFileNumberUsed(logs[i]);
  361. }
  362. if (versions_->LastSequence() < max_sequence) {
  363. versions_->SetLastSequence(max_sequence);
  364. }
  365. return Status::OK();
  366. }
  367. Status DBImpl::RecoverLogFile(uint64_t log_number, bool last_log,
  368. bool* save_manifest, VersionEdit* edit,
  369. SequenceNumber* max_sequence) {
  370. struct LogReporter : public log::Reader::Reporter {
  371. Env* env;
  372. Logger* info_log;
  373. const char* fname;
  374. Status* status; // null if options_.paranoid_checks==false
  375. void Corruption(size_t bytes, const Status& s) override {
  376. Log(info_log, "%s%s: dropping %d bytes; %s",
  377. (this->status == nullptr ? "(ignoring error) " : ""), fname,
  378. static_cast<int>(bytes), s.ToString().c_str());
  379. if (this->status != nullptr && this->status->ok()) *this->status = s;
  380. }
  381. };
  382. mutex_.AssertHeld();
  383. // Open the log file
  384. std::string fname = LogFileName(dbname_, log_number);
  385. SequentialFile* file;
  386. Status status = env_->NewSequentialFile(fname, &file);
  387. if (!status.ok()) {
  388. MaybeIgnoreError(&status);
  389. return status;
  390. }
  391. // Create the log reader.
  392. LogReporter reporter;
  393. reporter.env = env_;
  394. reporter.info_log = options_.info_log;
  395. reporter.fname = fname.c_str();
  396. reporter.status = (options_.paranoid_checks ? &status : nullptr);
  397. // We intentionally make log::Reader do checksumming even if
  398. // paranoid_checks==false so that corruptions cause entire commits
  399. // to be skipped instead of propagating bad information (like overly
  400. // large sequence numbers).
  401. log::Reader reader(file, &reporter, true /*checksum*/, 0 /*initial_offset*/);
  402. Log(options_.info_log, "Recovering log #%llu",
  403. (unsigned long long)log_number);
  404. // Read all the records and add to a memtable
  405. std::string scratch;
  406. Slice record;
  407. WriteBatch batch;
  408. int compactions = 0;
  409. MemTable* mem = nullptr;
  410. while (reader.ReadRecord(&record, &scratch) && status.ok()) {
  411. if (record.size() < 12) {
  412. reporter.Corruption(record.size(),
  413. Status::Corruption("log record too small"));
  414. continue;
  415. }
  416. WriteBatchInternal::SetContents(&batch, record);
  417. if (mem == nullptr) {
  418. mem = new MemTable(internal_comparator_);
  419. mem->Ref();
  420. }
  421. status = WriteBatchInternal::InsertInto(&batch, mem);
  422. MaybeIgnoreError(&status);
  423. if (!status.ok()) {
  424. break;
  425. }
  426. const SequenceNumber last_seq = WriteBatchInternal::Sequence(&batch) +
  427. WriteBatchInternal::Count(&batch) - 1;
  428. if (last_seq > *max_sequence) {
  429. *max_sequence = last_seq;
  430. }
  431. if (mem->ApproximateMemoryUsage() > options_.write_buffer_size) {
  432. compactions++;
  433. *save_manifest = true;
  434. status = WriteLevel0Table(mem, edit, nullptr);
  435. mem->Unref();
  436. mem = nullptr;
  437. if (!status.ok()) {
  438. // Reflect errors immediately so that conditions like full
  439. // file-systems cause the DB::Open() to fail.
  440. break;
  441. }
  442. }
  443. }
  444. delete file;
  445. // See if we should keep reusing the last log file.
  446. if (status.ok() && options_.reuse_logs && last_log && compactions == 0) {
  447. assert(logfile_ == nullptr);
  448. assert(log_ == nullptr);
  449. assert(mem_ == nullptr);
  450. uint64_t lfile_size;
  451. if (env_->GetFileSize(fname, &lfile_size).ok() &&
  452. env_->NewAppendableFile(fname, &logfile_).ok()) {
  453. Log(options_.info_log, "Reusing old log %s \n", fname.c_str());
  454. log_ = new log::Writer(logfile_, lfile_size);
  455. logfile_number_ = log_number;
  456. if (mem != nullptr) {
  457. mem_ = mem;
  458. mem = nullptr;
  459. } else {
  460. // mem can be nullptr if lognum exists but was empty.
  461. mem_ = new MemTable(internal_comparator_);
  462. mem_->Ref();
  463. }
  464. }
  465. }
  466. if (mem != nullptr) {
  467. // mem did not get reused; compact it.
  468. if (status.ok()) {
  469. *save_manifest = true;
  470. status = WriteLevel0Table(mem, edit, nullptr);
  471. }
  472. mem->Unref();
  473. }
  474. return status;
  475. }
  476. Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit,
  477. Version* base) {
  478. mutex_.AssertHeld();
  479. const uint64_t start_micros = env_->NowMicros();
  480. FileMetaData meta;
  481. meta.number = versions_->NewFileNumber();
  482. pending_outputs_.insert(meta.number);
  483. Iterator* iter = mem->NewIterator();
  484. Log(options_.info_log, "Level-0 table #%llu: started",
  485. (unsigned long long)meta.number);
  486. Status s;
  487. {
  488. mutex_.Unlock();
  489. s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta);
  490. mutex_.Lock();
  491. }
  492. Log(options_.info_log, "Level-0 table #%llu: %lld bytes %s",
  493. (unsigned long long)meta.number, (unsigned long long)meta.file_size,
  494. s.ToString().c_str());
  495. delete iter;
  496. pending_outputs_.erase(meta.number);
  497. // Note that if file_size is zero, the file has been deleted and
  498. // should not be added to the manifest.
  499. int level = 0;
  500. if (s.ok() && meta.file_size > 0) {
  501. const Slice min_user_key = meta.smallest.user_key();
  502. const Slice max_user_key = meta.largest.user_key();
  503. if (base != nullptr) {
  504. level = base->PickLevelForMemTableOutput(min_user_key, max_user_key);
  505. }
  506. edit->AddFile(level, meta.number, meta.file_size, meta.smallest,
  507. meta.largest);
  508. }
  509. CompactionStats stats;
  510. stats.micros = env_->NowMicros() - start_micros;
  511. stats.bytes_written = meta.file_size;
  512. stats_[level].Add(stats);
  513. return s;
  514. }
  515. void DBImpl::CompactMemTable() {
  516. mutex_.AssertHeld();
  517. assert(imm_ != nullptr);
  518. // Save the contents of the memtable as a new Table
  519. VersionEdit edit;
  520. Version* base = versions_->current();
  521. base->Ref();
  522. Status s = WriteLevel0Table(imm_, &edit, base);
  523. base->Unref();
  524. if (s.ok() && shutting_down_.load(std::memory_order_acquire)) {
  525. s = Status::IOError("Deleting DB during memtable compaction");
  526. }
  527. // Replace immutable memtable with the generated Table
  528. if (s.ok()) {
  529. edit.SetPrevLogNumber(0);
  530. edit.SetLogNumber(logfile_number_); // Earlier logs no longer needed
  531. s = versions_->LogAndApply(&edit, &mutex_);
  532. }
  533. if (s.ok()) {
  534. // Commit to the new state
  535. imm_->Unref();
  536. imm_ = nullptr;
  537. has_imm_.store(false, std::memory_order_release);
  538. RemoveObsoleteFiles();
  539. } else {
  540. RecordBackgroundError(s);
  541. }
  542. }
  543. void DBImpl::CompactRange(const Slice* begin, const Slice* end) {
  544. int max_level_with_files = 1;
  545. {
  546. MutexLock l(&mutex_);
  547. Version* base = versions_->current();
  548. for (int level = 1; level < config::kNumLevels; level++) {
  549. if (base->OverlapInLevel(level, begin, end)) {
  550. max_level_with_files = level;
  551. }
  552. }
  553. }
  554. TEST_CompactMemTable(); // TODO(sanjay): Skip if memtable does not overlap
  555. for (int level = 0; level < max_level_with_files; level++) {
  556. TEST_CompactRange(level, begin, end);
  557. }
  558. }
  559. void DBImpl::TEST_CompactRange(int level, const Slice* begin,
  560. const Slice* end) {
  561. assert(level >= 0);
  562. assert(level + 1 < config::kNumLevels);
  563. InternalKey begin_storage, end_storage;
  564. ManualCompaction manual;
  565. manual.level = level;
  566. manual.done = false;
  567. if (begin == nullptr) {
  568. manual.begin = nullptr;
  569. } else {
  570. begin_storage = InternalKey(*begin, kMaxSequenceNumber, kValueTypeForSeek);
  571. manual.begin = &begin_storage;
  572. }
  573. if (end == nullptr) {
  574. manual.end = nullptr;
  575. } else {
  576. end_storage = InternalKey(*end, 0, static_cast<ValueType>(0));
  577. manual.end = &end_storage;
  578. }
  579. MutexLock l(&mutex_);
  580. while (!manual.done && !shutting_down_.load(std::memory_order_acquire) &&
  581. bg_error_.ok()) {
  582. if (manual_compaction_ == nullptr) { // Idle
  583. manual_compaction_ = &manual;
  584. MaybeScheduleCompaction();
  585. } else { // Running either my compaction or another compaction.
  586. background_work_finished_signal_.Wait();
  587. }
  588. }
  589. // Finish current background compaction in the case where
  590. // `background_work_finished_signal_` was signalled due to an error.
  591. while (background_compaction_scheduled_) {
  592. background_work_finished_signal_.Wait();
  593. }
  594. if (manual_compaction_ == &manual) {
  595. // Cancel my manual compaction since we aborted early for some reason.
  596. manual_compaction_ = nullptr;
  597. }
  598. }
  599. Status DBImpl::TEST_CompactMemTable() {
  600. // nullptr batch means just wait for earlier writes to be done
  601. Status s = Write(WriteOptions(), nullptr);
  602. if (s.ok()) {
  603. // Wait until the compaction completes
  604. MutexLock l(&mutex_);
  605. while (imm_ != nullptr && bg_error_.ok()) {
  606. background_work_finished_signal_.Wait();
  607. }
  608. if (imm_ != nullptr) {
  609. s = bg_error_;
  610. }
  611. }
  612. return s;
  613. }
  614. void DBImpl::RecordBackgroundError(const Status& s) {
  615. mutex_.AssertHeld();
  616. if (bg_error_.ok()) {
  617. bg_error_ = s;
  618. background_work_finished_signal_.SignalAll();
  619. }
  620. }
  621. void DBImpl::MaybeScheduleCompaction() {
  622. mutex_.AssertHeld();
  623. if (background_compaction_scheduled_) {
  624. // Already scheduled
  625. } else if (shutting_down_.load(std::memory_order_acquire)) {
  626. // DB is being deleted; no more background compactions
  627. } else if (!bg_error_.ok()) {
  628. // Already got an error; no more changes
  629. } else if (imm_ == nullptr && manual_compaction_ == nullptr &&
  630. !versions_->NeedsCompaction()) {
  631. // No work to be done
  632. } else {
  633. background_compaction_scheduled_ = true;
  634. env_->Schedule(&DBImpl::BGWork, this);
  635. }
  636. }
  637. void DBImpl::BGWork(void* db) {
  638. reinterpret_cast<DBImpl*>(db)->BackgroundCall();
  639. }
  640. void DBImpl::BackgroundCall() {
  641. MutexLock l(&mutex_);
  642. assert(background_compaction_scheduled_);
  643. if (shutting_down_.load(std::memory_order_acquire)) {
  644. // No more background work when shutting down.
  645. } else if (!bg_error_.ok()) {
  646. // No more background work after a background error.
  647. } else {
  648. BackgroundCompaction();
  649. }
  650. background_compaction_scheduled_ = false;
  651. // Previous compaction may have produced too many files in a level,
  652. // so reschedule another compaction if needed.
  653. MaybeScheduleCompaction();
  654. background_work_finished_signal_.SignalAll();
  655. }
  656. void DBImpl::BackgroundCompaction() {
  657. mutex_.AssertHeld();
  658. if (imm_ != nullptr) {
  659. CompactMemTable();
  660. return;
  661. }
  662. Compaction* c;
  663. bool is_manual = (manual_compaction_ != nullptr);
  664. InternalKey manual_end;
  665. if (is_manual) {
  666. ManualCompaction* m = manual_compaction_;
  667. c = versions_->CompactRange(m->level, m->begin, m->end);
  668. m->done = (c == nullptr);
  669. if (c != nullptr) {
  670. manual_end = c->input(0, c->num_input_files(0) - 1)->largest;
  671. }
  672. Log(options_.info_log,
  673. "Manual compaction at level-%d from %s .. %s; will stop at %s\n",
  674. m->level, (m->begin ? m->begin->DebugString().c_str() : "(begin)"),
  675. (m->end ? m->end->DebugString().c_str() : "(end)"),
  676. (m->done ? "(end)" : manual_end.DebugString().c_str()));
  677. } else {
  678. c = versions_->PickCompaction();
  679. }
  680. Status status;
  681. if (c == nullptr) {
  682. // Nothing to do
  683. } else if (!is_manual && c->IsTrivialMove()) {
  684. // Move file to next level
  685. assert(c->num_input_files(0) == 1);
  686. FileMetaData* f = c->input(0, 0);
  687. c->edit()->RemoveFile(c->level(), f->number);
  688. c->edit()->AddFile(c->level() + 1, f->number, f->file_size, f->smallest,
  689. f->largest);
  690. status = versions_->LogAndApply(c->edit(), &mutex_);
  691. if (!status.ok()) {
  692. RecordBackgroundError(status);
  693. }
  694. VersionSet::LevelSummaryStorage tmp;
  695. Log(options_.info_log, "Moved #%lld to level-%d %lld bytes %s: %s\n",
  696. static_cast<unsigned long long>(f->number), c->level() + 1,
  697. static_cast<unsigned long long>(f->file_size),
  698. status.ToString().c_str(), versions_->LevelSummary(&tmp));
  699. } else {
  700. CompactionState* compact = new CompactionState(c);
  701. status = DoCompactionWork(compact);
  702. if (!status.ok()) {
  703. RecordBackgroundError(status);
  704. }
  705. CleanupCompaction(compact);
  706. c->ReleaseInputs();
  707. RemoveObsoleteFiles();
  708. }
  709. delete c;
  710. if (status.ok()) {
  711. // Done
  712. } else if (shutting_down_.load(std::memory_order_acquire)) {
  713. // Ignore compaction errors found during shutting down
  714. } else {
  715. Log(options_.info_log, "Compaction error: %s", status.ToString().c_str());
  716. }
  717. if (is_manual) {
  718. ManualCompaction* m = manual_compaction_;
  719. if (!status.ok()) {
  720. m->done = true;
  721. }
  722. if (!m->done) {
  723. // We only compacted part of the requested range. Update *m
  724. // to the range that is left to be compacted.
  725. m->tmp_storage = manual_end;
  726. m->begin = &m->tmp_storage;
  727. }
  728. manual_compaction_ = nullptr;
  729. }
  730. }
  731. void DBImpl::CleanupCompaction(CompactionState* compact) {
  732. mutex_.AssertHeld();
  733. if (compact->builder != nullptr) {
  734. // May happen if we get a shutdown call in the middle of compaction
  735. compact->builder->Abandon();
  736. delete compact->builder;
  737. } else {
  738. assert(compact->outfile == nullptr);
  739. }
  740. delete compact->outfile;
  741. for (size_t i = 0; i < compact->outputs.size(); i++) {
  742. const CompactionState::Output& out = compact->outputs[i];
  743. pending_outputs_.erase(out.number);
  744. }
  745. delete compact;
  746. }
  747. Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) {
  748. assert(compact != nullptr);
  749. assert(compact->builder == nullptr);
  750. uint64_t file_number;
  751. {
  752. mutex_.Lock();
  753. file_number = versions_->NewFileNumber();
  754. pending_outputs_.insert(file_number);
  755. CompactionState::Output out;
  756. out.number = file_number;
  757. out.smallest.Clear();
  758. out.largest.Clear();
  759. compact->outputs.push_back(out);
  760. mutex_.Unlock();
  761. }
  762. // Make the output file
  763. std::string fname = TableFileName(dbname_, file_number);
  764. Status s = env_->NewWritableFile(fname, &compact->outfile);
  765. if (s.ok()) {
  766. compact->builder = new TableBuilder(options_, compact->outfile);
  767. }
  768. return s;
  769. }
  770. Status DBImpl::FinishCompactionOutputFile(CompactionState* compact,
  771. Iterator* input) {
  772. assert(compact != nullptr);
  773. assert(compact->outfile != nullptr);
  774. assert(compact->builder != nullptr);
  775. const uint64_t output_number = compact->current_output()->number;
  776. assert(output_number != 0);
  777. // Check for iterator errors
  778. Status s = input->status();
  779. const uint64_t current_entries = compact->builder->NumEntries();
  780. if (s.ok()) {
  781. s = compact->builder->Finish();
  782. } else {
  783. compact->builder->Abandon();
  784. }
  785. const uint64_t current_bytes = compact->builder->FileSize();
  786. compact->current_output()->file_size = current_bytes;
  787. compact->total_bytes += current_bytes;
  788. delete compact->builder;
  789. compact->builder = nullptr;
  790. // Finish and check for file errors
  791. if (s.ok()) {
  792. s = compact->outfile->Sync();
  793. }
  794. if (s.ok()) {
  795. s = compact->outfile->Close();
  796. }
  797. delete compact->outfile;
  798. compact->outfile = nullptr;
  799. if (s.ok() && current_entries > 0) {
  800. // Verify that the table is usable
  801. Iterator* iter =
  802. table_cache_->NewIterator(ReadOptions(), output_number, current_bytes);
  803. s = iter->status();
  804. delete iter;
  805. if (s.ok()) {
  806. Log(options_.info_log, "Generated table #%llu@%d: %lld keys, %lld bytes",
  807. (unsigned long long)output_number, compact->compaction->level(),
  808. (unsigned long long)current_entries,
  809. (unsigned long long)current_bytes);
  810. }
  811. }
  812. return s;
  813. }
  814. Status DBImpl::InstallCompactionResults(CompactionState* compact) {
  815. mutex_.AssertHeld();
  816. Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes",
  817. compact->compaction->num_input_files(0), compact->compaction->level(),
  818. compact->compaction->num_input_files(1), compact->compaction->level() + 1,
  819. static_cast<long long>(compact->total_bytes));
  820. // Add compaction outputs
  821. compact->compaction->AddInputDeletions(compact->compaction->edit());
  822. const int level = compact->compaction->level();
  823. for (size_t i = 0; i < compact->outputs.size(); i++) {
  824. const CompactionState::Output& out = compact->outputs[i];
  825. compact->compaction->edit()->AddFile(level + 1, out.number, out.file_size,
  826. out.smallest, out.largest);
  827. }
  828. return versions_->LogAndApply(compact->compaction->edit(), &mutex_);
  829. }
  830. Status DBImpl::DoCompactionWork(CompactionState* compact) {
  831. const uint64_t start_micros = env_->NowMicros();
  832. int64_t imm_micros = 0; // Micros spent doing imm_ compactions
  833. Log(options_.info_log, "Compacting %d@%d + %d@%d files",
  834. compact->compaction->num_input_files(0), compact->compaction->level(),
  835. compact->compaction->num_input_files(1),
  836. compact->compaction->level() + 1);
  837. assert(versions_->NumLevelFiles(compact->compaction->level()) > 0);
  838. assert(compact->builder == nullptr);
  839. assert(compact->outfile == nullptr);
  840. if (snapshots_.empty()) {
  841. compact->smallest_snapshot = versions_->LastSequence();
  842. } else {
  843. compact->smallest_snapshot = snapshots_.oldest()->sequence_number();
  844. }
  845. Iterator* input = versions_->MakeInputIterator(compact->compaction);
  846. // Release mutex while we're actually doing the compaction work
  847. mutex_.Unlock();
  848. input->SeekToFirst();
  849. Status status;
  850. ParsedInternalKey ikey;
  851. std::string current_user_key;
  852. bool has_current_user_key = false;
  853. SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
  854. while (input->Valid() && !shutting_down_.load(std::memory_order_acquire)) {
  855. // Prioritize immutable compaction work
  856. if (has_imm_.load(std::memory_order_relaxed)) {
  857. const uint64_t imm_start = env_->NowMicros();
  858. mutex_.Lock();
  859. if (imm_ != nullptr) {
  860. CompactMemTable();
  861. // Wake up MakeRoomForWrite() if necessary.
  862. background_work_finished_signal_.SignalAll();
  863. }
  864. mutex_.Unlock();
  865. imm_micros += (env_->NowMicros() - imm_start);
  866. }
  867. Slice key = input->key();
  868. if (compact->compaction->ShouldStopBefore(key) &&
  869. compact->builder != nullptr) {
  870. status = FinishCompactionOutputFile(compact, input);
  871. if (!status.ok()) {
  872. break;
  873. }
  874. }
  875. // Handle key/value, add to state, etc.
  876. bool drop = false;
  877. if (!ParseInternalKey(key, &ikey)) {
  878. // Do not hide error keys
  879. current_user_key.clear();
  880. has_current_user_key = false;
  881. last_sequence_for_key = kMaxSequenceNumber;
  882. } else {
  883. if (!has_current_user_key ||
  884. user_comparator()->Compare(ikey.user_key, Slice(current_user_key)) !=
  885. 0) {
  886. // First occurrence of this user key
  887. current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
  888. has_current_user_key = true;
  889. last_sequence_for_key = kMaxSequenceNumber;
  890. }
  891. if (last_sequence_for_key <= compact->smallest_snapshot) {
  892. // Hidden by an newer entry for same user key
  893. drop = true; // (A)
  894. } else if (ikey.type == kTypeDeletion &&
  895. ikey.sequence <= compact->smallest_snapshot &&
  896. compact->compaction->IsBaseLevelForKey(ikey.user_key)) {
  897. // For this user key:
  898. // (1) there is no data in higher levels
  899. // (2) data in lower levels will have larger sequence numbers
  900. // (3) data in layers that are being compacted here and have
  901. // smaller sequence numbers will be dropped in the next
  902. // few iterations of this loop (by rule (A) above).
  903. // Therefore this deletion marker is obsolete and can be dropped.
  904. drop = true;
  905. }
  906. // TTL ToDo: add expiration time check
  907. if (!drop) { // 如果还未被标记为丢弃
  908. Slice value = input->value();
  909. if (value.size() >= sizeof(uint64_t)) {
  910. const char* ptr = value.data();
  911. uint64_t expiration_time = DecodeFixed64(ptr);
  912. uint64_t current_time = env_->NowMicros() / 1000000;
  913. if (current_time > expiration_time) {
  914. drop = true; // 过期的键值对,标记为丢弃
  915. }
  916. }
  917. }
  918. last_sequence_for_key = ikey.sequence;
  919. }
  920. #if 0
  921. Log(options_.info_log,
  922. " Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
  923. "%d smallest_snapshot: %d",
  924. ikey.user_key.ToString().c_str(),
  925. (int)ikey.sequence, ikey.type, kTypeValue, drop,
  926. compact->compaction->IsBaseLevelForKey(ikey.user_key),
  927. (int)last_sequence_for_key, (int)compact->smallest_snapshot);
  928. #endif
  929. if (!drop) {
  930. // Open output file if necessary
  931. if (compact->builder == nullptr) {
  932. status = OpenCompactionOutputFile(compact);
  933. if (!status.ok()) {
  934. break;
  935. }
  936. }
  937. if (compact->builder->NumEntries() == 0) {
  938. compact->current_output()->smallest.DecodeFrom(key);
  939. }
  940. compact->current_output()->largest.DecodeFrom(key);
  941. compact->builder->Add(key, input->value());
  942. // Close output file if it is big enough
  943. if (compact->builder->FileSize() >=
  944. compact->compaction->MaxOutputFileSize()) {
  945. status = FinishCompactionOutputFile(compact, input);
  946. if (!status.ok()) {
  947. break;
  948. }
  949. }
  950. }
  951. input->Next();
  952. }
  953. if (status.ok() && shutting_down_.load(std::memory_order_acquire)) {
  954. status = Status::IOError("Deleting DB during compaction");
  955. }
  956. if (status.ok() && compact->builder != nullptr) {
  957. status = FinishCompactionOutputFile(compact, input);
  958. }
  959. if (status.ok()) {
  960. status = input->status();
  961. }
  962. delete input;
  963. input = nullptr;
  964. CompactionStats stats;
  965. stats.micros = env_->NowMicros() - start_micros - imm_micros;
  966. for (int which = 0; which < 2; which++) {
  967. for (int i = 0; i < compact->compaction->num_input_files(which); i++) {
  968. stats.bytes_read += compact->compaction->input(which, i)->file_size;
  969. }
  970. }
  971. for (size_t i = 0; i < compact->outputs.size(); i++) {
  972. stats.bytes_written += compact->outputs[i].file_size;
  973. }
  974. mutex_.Lock();
  975. stats_[compact->compaction->level() + 1].Add(stats);
  976. if (status.ok()) {
  977. status = InstallCompactionResults(compact);
  978. }
  979. if (!status.ok()) {
  980. RecordBackgroundError(status);
  981. }
  982. VersionSet::LevelSummaryStorage tmp;
  983. Log(options_.info_log, "compacted to: %s", versions_->LevelSummary(&tmp));
  984. return status;
  985. }
  986. namespace {
  987. struct IterState {
  988. port::Mutex* const mu;
  989. Version* const version GUARDED_BY(mu);
  990. MemTable* const mem GUARDED_BY(mu);
  991. MemTable* const imm GUARDED_BY(mu);
  992. IterState(port::Mutex* mutex, MemTable* mem, MemTable* imm, Version* version)
  993. : mu(mutex), version(version), mem(mem), imm(imm) {}
  994. };
  995. static void CleanupIteratorState(void* arg1, void* arg2) {
  996. IterState* state = reinterpret_cast<IterState*>(arg1);
  997. state->mu->Lock();
  998. state->mem->Unref();
  999. if (state->imm != nullptr) state->imm->Unref();
  1000. state->version->Unref();
  1001. state->mu->Unlock();
  1002. delete state;
  1003. }
  1004. } // anonymous namespace
  1005. Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
  1006. SequenceNumber* latest_snapshot,
  1007. uint32_t* seed) {
  1008. mutex_.Lock();
  1009. *latest_snapshot = versions_->LastSequence();
  1010. // Collect together all needed child iterators
  1011. std::vector<Iterator*> list;
  1012. list.push_back(mem_->NewIterator());
  1013. mem_->Ref();
  1014. if (imm_ != nullptr) {
  1015. list.push_back(imm_->NewIterator());
  1016. imm_->Ref();
  1017. }
  1018. versions_->current()->AddIterators(options, &list);
  1019. Iterator* internal_iter =
  1020. NewMergingIterator(&internal_comparator_, &list[0], list.size());
  1021. versions_->current()->Ref();
  1022. IterState* cleanup = new IterState(&mutex_, mem_, imm_, versions_->current());
  1023. internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, nullptr);
  1024. *seed = ++seed_;
  1025. mutex_.Unlock();
  1026. return internal_iter;
  1027. }
  1028. Iterator* DBImpl::TEST_NewInternalIterator() {
  1029. SequenceNumber ignored;
  1030. uint32_t ignored_seed;
  1031. return NewInternalIterator(ReadOptions(), &ignored, &ignored_seed);
  1032. }
  1033. int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {
  1034. MutexLock l(&mutex_);
  1035. return versions_->MaxNextLevelOverlappingBytes();
  1036. }
  1037. Status DBImpl::Get(const ReadOptions& options, const Slice& key,
  1038. std::string* value) {
  1039. Status s;
  1040. MutexLock l(&mutex_);
  1041. SequenceNumber snapshot;
  1042. if (options.snapshot != nullptr) {
  1043. snapshot =
  1044. static_cast<const SnapshotImpl*>(options.snapshot)->sequence_number();
  1045. } else {
  1046. snapshot = versions_->LastSequence();
  1047. }
  1048. MemTable* mem = mem_;
  1049. MemTable* imm = imm_;
  1050. Version* current = versions_->current();
  1051. mem->Ref();
  1052. if (imm != nullptr) imm->Ref();
  1053. current->Ref();
  1054. bool have_stat_update = false;
  1055. Version::GetStats stats;
  1056. // Unlock while reading from files and memtables
  1057. {
  1058. mutex_.Unlock();
  1059. // First look in the memtable, then in the immutable memtable (if any).
  1060. LookupKey lkey(key, snapshot);
  1061. if (mem->Get(lkey, value, &s)) {
  1062. // Done
  1063. } else if (imm != nullptr && imm->Get(lkey, value, &s)) {
  1064. // Done
  1065. } else {
  1066. s = current->Get(options, lkey, value, &stats);
  1067. have_stat_update = true;
  1068. }
  1069. mutex_.Lock();
  1070. }
  1071. // TTL ToDo : add check for TTL
  1072. // 如果从 memtable、imm 或 sstable 获取到了数据,则需要检查TTL
  1073. if (s.ok()) {
  1074. // 从 value 中解析出过期时间戳(假设值存储格式为:[过期时间戳][实际值])
  1075. uint64_t expiration_time = ParseExpirationTime(*value);
  1076. uint64_t current_time = GetCurrentTime();
  1077. // 如果当前时间已经超过过期时间,则认为数据过期,返回 NotFound
  1078. if (current_time > expiration_time) {
  1079. s = Status::NotFound("Key expired");
  1080. } else {
  1081. // 数据未过期,解析出实际的值
  1082. *value = ParseActualValue(*value);
  1083. }
  1084. }
  1085. //finish modify
  1086. if (have_stat_update && current->UpdateStats(stats)) {
  1087. MaybeScheduleCompaction();
  1088. }
  1089. mem->Unref();
  1090. if (imm != nullptr) imm->Unref();
  1091. current->Unref();
  1092. return s;
  1093. }
  1094. Iterator* DBImpl::NewIterator(const ReadOptions& options) {
  1095. SequenceNumber latest_snapshot;
  1096. uint32_t seed;
  1097. Iterator* iter = NewInternalIterator(options, &latest_snapshot, &seed);
  1098. return NewDBIterator(this, user_comparator(), iter,
  1099. (options.snapshot != nullptr
  1100. ? static_cast<const SnapshotImpl*>(options.snapshot)
  1101. ->sequence_number()
  1102. : latest_snapshot),
  1103. seed);
  1104. }
  1105. void DBImpl::RecordReadSample(Slice key) {
  1106. MutexLock l(&mutex_);
  1107. if (versions_->current()->RecordReadSample(key)) {
  1108. MaybeScheduleCompaction();
  1109. }
  1110. }
  1111. const Snapshot* DBImpl::GetSnapshot() {
  1112. MutexLock l(&mutex_);
  1113. return snapshots_.New(versions_->LastSequence());
  1114. }
  1115. void DBImpl::ReleaseSnapshot(const Snapshot* snapshot) {
  1116. MutexLock l(&mutex_);
  1117. snapshots_.Delete(static_cast<const SnapshotImpl*>(snapshot));
  1118. }
  1119. // Convenience methods
  1120. Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
  1121. return DB::Put(o, key, val);
  1122. }
  1123. // TTL ToDo: add DBImpl for Put
  1124. // 新增支持TTL的Put方法
  1125. Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val, uint64_t ttl) {
  1126. return DB::Put(o, key, val, ttl);
  1127. }
  1128. //finish modify
  1129. Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
  1130. return DB::Delete(options, key);
  1131. }
  1132. Status DBImpl::Write(const WriteOptions& options, WriteBatch* updates) {
  1133. Writer w(&mutex_);
  1134. w.batch = updates;
  1135. w.sync = options.sync;
  1136. w.done = false;
  1137. MutexLock l(&mutex_);
  1138. writers_.push_back(&w);
  1139. while (!w.done && &w != writers_.front()) {
  1140. w.cv.Wait();
  1141. }
  1142. if (w.done) {
  1143. return w.status;
  1144. }
  1145. // May temporarily unlock and wait.
  1146. Status status = MakeRoomForWrite(updates == nullptr);
  1147. uint64_t last_sequence = versions_->LastSequence();
  1148. Writer* last_writer = &w;
  1149. if (status.ok() && updates != nullptr) { // nullptr batch is for compactions
  1150. WriteBatch* write_batch = BuildBatchGroup(&last_writer);
  1151. WriteBatchInternal::SetSequence(write_batch, last_sequence + 1);
  1152. last_sequence += WriteBatchInternal::Count(write_batch);
  1153. // Add to log and apply to memtable. We can release the lock
  1154. // during this phase since &w is currently responsible for logging
  1155. // and protects against concurrent loggers and concurrent writes
  1156. // into mem_.
  1157. {
  1158. mutex_.Unlock();
  1159. status = log_->AddRecord(WriteBatchInternal::Contents(write_batch));
  1160. bool sync_error = false;
  1161. if (status.ok() && options.sync) {
  1162. status = logfile_->Sync();
  1163. if (!status.ok()) {
  1164. sync_error = true;
  1165. }
  1166. }
  1167. if (status.ok()) {
  1168. status = WriteBatchInternal::InsertInto(write_batch, mem_);
  1169. }
  1170. mutex_.Lock();
  1171. if (sync_error) {
  1172. // The state of the log file is indeterminate: the log record we
  1173. // just added may or may not show up when the DB is re-opened.
  1174. // So we force the DB into a mode where all future writes fail.
  1175. RecordBackgroundError(status);
  1176. }
  1177. }
  1178. if (write_batch == tmp_batch_) tmp_batch_->Clear();
  1179. versions_->SetLastSequence(last_sequence);
  1180. }
  1181. while (true) {
  1182. Writer* ready = writers_.front();
  1183. writers_.pop_front();
  1184. if (ready != &w) {
  1185. ready->status = status;
  1186. ready->done = true;
  1187. ready->cv.Signal();
  1188. }
  1189. if (ready == last_writer) break;
  1190. }
  1191. // Notify new head of write queue
  1192. if (!writers_.empty()) {
  1193. writers_.front()->cv.Signal();
  1194. }
  1195. return status;
  1196. }
  1197. // REQUIRES: Writer list must be non-empty
  1198. // REQUIRES: First writer must have a non-null batch
  1199. WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) {
  1200. mutex_.AssertHeld();
  1201. assert(!writers_.empty());
  1202. Writer* first = writers_.front();
  1203. WriteBatch* result = first->batch;
  1204. assert(result != nullptr);
  1205. size_t size = WriteBatchInternal::ByteSize(first->batch);
  1206. // Allow the group to grow up to a maximum size, but if the
  1207. // original write is small, limit the growth so we do not slow
  1208. // down the small write too much.
  1209. size_t max_size = 1 << 20;
  1210. if (size <= (128 << 10)) {
  1211. max_size = size + (128 << 10);
  1212. }
  1213. *last_writer = first;
  1214. std::deque<Writer*>::iterator iter = writers_.begin();
  1215. ++iter; // Advance past "first"
  1216. for (; iter != writers_.end(); ++iter) {
  1217. Writer* w = *iter;
  1218. if (w->sync && !first->sync) {
  1219. // Do not include a sync write into a batch handled by a non-sync write.
  1220. break;
  1221. }
  1222. if (w->batch != nullptr) {
  1223. size += WriteBatchInternal::ByteSize(w->batch);
  1224. if (size > max_size) {
  1225. // Do not make batch too big
  1226. break;
  1227. }
  1228. // Append to *result
  1229. if (result == first->batch) {
  1230. // Switch to temporary batch instead of disturbing caller's batch
  1231. result = tmp_batch_;
  1232. assert(WriteBatchInternal::Count(result) == 0);
  1233. WriteBatchInternal::Append(result, first->batch);
  1234. }
  1235. WriteBatchInternal::Append(result, w->batch);
  1236. }
  1237. *last_writer = w;
  1238. }
  1239. return result;
  1240. }
  1241. // REQUIRES: mutex_ is held
  1242. // REQUIRES: this thread is currently at the front of the writer queue
  1243. Status DBImpl::MakeRoomForWrite(bool force) {
  1244. mutex_.AssertHeld();
  1245. assert(!writers_.empty());
  1246. bool allow_delay = !force;
  1247. Status s;
  1248. while (true) {
  1249. if (!bg_error_.ok()) {
  1250. // Yield previous error
  1251. s = bg_error_;
  1252. break;
  1253. } else if (allow_delay && versions_->NumLevelFiles(0) >=
  1254. config::kL0_SlowdownWritesTrigger) {
  1255. // We are getting close to hitting a hard limit on the number of
  1256. // L0 files. Rather than delaying a single write by several
  1257. // seconds when we hit the hard limit, start delaying each
  1258. // individual write by 1ms to reduce latency variance. Also,
  1259. // this delay hands over some CPU to the compaction thread in
  1260. // case it is sharing the same core as the writer.
  1261. mutex_.Unlock();
  1262. env_->SleepForMicroseconds(1000);
  1263. allow_delay = false; // Do not delay a single write more than once
  1264. mutex_.Lock();
  1265. } else if (!force &&
  1266. (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) {
  1267. // There is room in current memtable
  1268. break;
  1269. } else if (imm_ != nullptr) {
  1270. // We have filled up the current memtable, but the previous
  1271. // one is still being compacted, so we wait.
  1272. Log(options_.info_log, "Current memtable full; waiting...\n");
  1273. background_work_finished_signal_.Wait();
  1274. } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) {
  1275. // There are too many level-0 files.
  1276. Log(options_.info_log, "Too many L0 files; waiting...\n");
  1277. background_work_finished_signal_.Wait();
  1278. } else {
  1279. // Attempt to switch to a new memtable and trigger compaction of old
  1280. assert(versions_->PrevLogNumber() == 0);
  1281. uint64_t new_log_number = versions_->NewFileNumber();
  1282. WritableFile* lfile = nullptr;
  1283. s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile);
  1284. if (!s.ok()) {
  1285. // Avoid chewing through file number space in a tight loop.
  1286. versions_->ReuseFileNumber(new_log_number);
  1287. break;
  1288. }
  1289. delete log_;
  1290. s = logfile_->Close();
  1291. if (!s.ok()) {
  1292. // We may have lost some data written to the previous log file.
  1293. // Switch to the new log file anyway, but record as a background
  1294. // error so we do not attempt any more writes.
  1295. //
  1296. // We could perhaps attempt to save the memtable corresponding
  1297. // to log file and suppress the error if that works, but that
  1298. // would add more complexity in a critical code path.
  1299. RecordBackgroundError(s);
  1300. }
  1301. delete logfile_;
  1302. logfile_ = lfile;
  1303. logfile_number_ = new_log_number;
  1304. log_ = new log::Writer(lfile);
  1305. imm_ = mem_;
  1306. has_imm_.store(true, std::memory_order_release);
  1307. mem_ = new MemTable(internal_comparator_);
  1308. mem_->Ref();
  1309. force = false; // Do not force another compaction if have room
  1310. MaybeScheduleCompaction();
  1311. }
  1312. }
  1313. return s;
  1314. }
  1315. bool DBImpl::GetProperty(const Slice& property, std::string* value) {
  1316. value->clear();
  1317. MutexLock l(&mutex_);
  1318. Slice in = property;
  1319. Slice prefix("leveldb.");
  1320. if (!in.starts_with(prefix)) return false;
  1321. in.remove_prefix(prefix.size());
  1322. if (in.starts_with("num-files-at-level")) {
  1323. in.remove_prefix(strlen("num-files-at-level"));
  1324. uint64_t level;
  1325. bool ok = ConsumeDecimalNumber(&in, &level) && in.empty();
  1326. if (!ok || level >= config::kNumLevels) {
  1327. return false;
  1328. } else {
  1329. char buf[100];
  1330. std::snprintf(buf, sizeof(buf), "%d",
  1331. versions_->NumLevelFiles(static_cast<int>(level)));
  1332. *value = buf;
  1333. return true;
  1334. }
  1335. } else if (in == "stats") {
  1336. char buf[200];
  1337. std::snprintf(buf, sizeof(buf),
  1338. " Compactions\n"
  1339. "Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n"
  1340. "--------------------------------------------------\n");
  1341. value->append(buf);
  1342. for (int level = 0; level < config::kNumLevels; level++) {
  1343. int files = versions_->NumLevelFiles(level);
  1344. if (stats_[level].micros > 0 || files > 0) {
  1345. std::snprintf(buf, sizeof(buf), "%3d %8d %8.0f %9.0f %8.0f %9.0f\n",
  1346. level, files, versions_->NumLevelBytes(level) / 1048576.0,
  1347. stats_[level].micros / 1e6,
  1348. stats_[level].bytes_read / 1048576.0,
  1349. stats_[level].bytes_written / 1048576.0);
  1350. value->append(buf);
  1351. }
  1352. }
  1353. return true;
  1354. } else if (in == "sstables") {
  1355. *value = versions_->current()->DebugString();
  1356. return true;
  1357. } else if (in == "approximate-memory-usage") {
  1358. size_t total_usage = options_.block_cache->TotalCharge();
  1359. if (mem_) {
  1360. total_usage += mem_->ApproximateMemoryUsage();
  1361. }
  1362. if (imm_) {
  1363. total_usage += imm_->ApproximateMemoryUsage();
  1364. }
  1365. char buf[50];
  1366. std::snprintf(buf, sizeof(buf), "%llu",
  1367. static_cast<unsigned long long>(total_usage));
  1368. value->append(buf);
  1369. return true;
  1370. }
  1371. return false;
  1372. }
  1373. void DBImpl::GetApproximateSizes(const Range* range, int n, uint64_t* sizes) {
  1374. // TODO(opt): better implementation
  1375. MutexLock l(&mutex_);
  1376. Version* v = versions_->current();
  1377. v->Ref();
  1378. for (int i = 0; i < n; i++) {
  1379. // Convert user_key into a corresponding internal key.
  1380. InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek);
  1381. InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek);
  1382. uint64_t start = versions_->ApproximateOffsetOf(v, k1);
  1383. uint64_t limit = versions_->ApproximateOffsetOf(v, k2);
  1384. sizes[i] = (limit >= start ? limit - start : 0);
  1385. }
  1386. v->Unref();
  1387. }
  1388. // Default implementations of convenience methods that subclasses of DB
  1389. // can call if they wish
  1390. Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
  1391. WriteBatch batch;
  1392. batch.Put(key, value);
  1393. return Write(opt, &batch);
  1394. }
  1395. //TTL ToDo: add a func for TTL Put
  1396. Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value, uint64_t ttl) {
  1397. // 获取当前时间并计算过期时间戳
  1398. uint64_t expiration_time = GetCurrentTime() + ttl;
  1399. // 将过期时间戳和值一起存储(假设值前面附加过期时间戳)
  1400. std::string new_value;
  1401. AppendExpirationTime(&new_value, expiration_time);
  1402. new_value.append(value.data(), value.size());
  1403. // 构造 WriteBatch,并将键值对加入到批处理中
  1404. WriteBatch batch;
  1405. batch.Put(key, new_value);
  1406. // 执行写操作
  1407. return Write(opt, &batch);
  1408. }
  1409. //finish modify
  1410. Status DB::Delete(const WriteOptions& opt, const Slice& key) {
  1411. WriteBatch batch;
  1412. batch.Delete(key);
  1413. return Write(opt, &batch);
  1414. }
  1415. DB::~DB() = default;
  1416. Status DB::Open(const Options& options, const std::string& dbname, DB** dbptr) {
  1417. *dbptr = nullptr;
  1418. DBImpl* impl = new DBImpl(options, dbname);
  1419. impl->mutex_.Lock();
  1420. VersionEdit edit;
  1421. // Recover handles create_if_missing, error_if_exists
  1422. bool save_manifest = false;
  1423. Status s = impl->Recover(&edit, &save_manifest);
  1424. if (s.ok() && impl->mem_ == nullptr) {
  1425. // Create new log and a corresponding memtable.
  1426. uint64_t new_log_number = impl->versions_->NewFileNumber();
  1427. WritableFile* lfile;
  1428. s = options.env->NewWritableFile(LogFileName(dbname, new_log_number),
  1429. &lfile);
  1430. if (s.ok()) {
  1431. edit.SetLogNumber(new_log_number);
  1432. impl->logfile_ = lfile;
  1433. impl->logfile_number_ = new_log_number;
  1434. impl->log_ = new log::Writer(lfile);
  1435. impl->mem_ = new MemTable(impl->internal_comparator_);
  1436. impl->mem_->Ref();
  1437. }
  1438. }
  1439. if (s.ok() && save_manifest) {
  1440. edit.SetPrevLogNumber(0); // No older logs needed after recovery.
  1441. edit.SetLogNumber(impl->logfile_number_);
  1442. s = impl->versions_->LogAndApply(&edit, &impl->mutex_);
  1443. }
  1444. if (s.ok()) {
  1445. impl->RemoveObsoleteFiles();
  1446. impl->MaybeScheduleCompaction();
  1447. }
  1448. impl->mutex_.Unlock();
  1449. if (s.ok()) {
  1450. assert(impl->mem_ != nullptr);
  1451. *dbptr = impl;
  1452. } else {
  1453. delete impl;
  1454. }
  1455. return s;
  1456. }
  1457. Snapshot::~Snapshot() = default;
  1458. Status DestroyDB(const std::string& dbname, const Options& options) {
  1459. Env* env = options.env;
  1460. std::vector<std::string> filenames;
  1461. Status result = env->GetChildren(dbname, &filenames);
  1462. if (!result.ok()) {
  1463. // Ignore error in case directory does not exist
  1464. return Status::OK();
  1465. }
  1466. FileLock* lock;
  1467. const std::string lockname = LockFileName(dbname);
  1468. result = env->LockFile(lockname, &lock);
  1469. if (result.ok()) {
  1470. uint64_t number;
  1471. FileType type;
  1472. for (size_t i = 0; i < filenames.size(); i++) {
  1473. if (ParseFileName(filenames[i], &number, &type) &&
  1474. type != kDBLockFile) { // Lock file will be deleted at end
  1475. Status del = env->RemoveFile(dbname + "/" + filenames[i]);
  1476. if (result.ok() && !del.ok()) {
  1477. result = del;
  1478. }
  1479. }
  1480. }
  1481. env->UnlockFile(lock); // Ignore error since state is already gone
  1482. env->RemoveFile(lockname);
  1483. env->RemoveDir(dbname); // Ignore error in case dir contains other files
  1484. }
  1485. return result;
  1486. }
  1487. } // namespace leveldb