作者: 谢瑞阳 10225101483 徐翔宇 10225101535
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.

1578 lines
47 KiB

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