Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1692 wiersze
52 KiB

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