作者: 韩晨旭 10225101440 李畅 10225102463
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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