小组成员:姚凯文(kevinyao0901),姜嘉琪
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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