作者: 韩晨旭 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.

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