10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
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.

1343 lines
40 KiB

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