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

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