作者: 韩晨旭 10225101440 李畅 10225102463
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1236 рядки
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. namespace {
  789. struct IterState {
  790. port::Mutex* mu;
  791. Version* version;
  792. MemTable* mem;
  793. MemTable* imm;
  794. };
  795. static void CleanupIteratorState(void* arg1, void* arg2) {
  796. IterState* state = reinterpret_cast<IterState*>(arg1);
  797. state->mu->Lock();
  798. state->mem->Unref();
  799. if (state->imm != NULL) state->imm->Unref();
  800. state->version->Unref();
  801. state->mu->Unlock();
  802. delete state;
  803. }
  804. }
  805. Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
  806. SequenceNumber* latest_snapshot) {
  807. IterState* cleanup = new IterState;
  808. mutex_.Lock();
  809. *latest_snapshot = versions_->LastSequence();
  810. // Collect together all needed child iterators
  811. std::vector<Iterator*> list;
  812. list.push_back(mem_->NewIterator());
  813. mem_->Ref();
  814. if (imm_ != NULL) {
  815. list.push_back(imm_->NewIterator());
  816. imm_->Ref();
  817. }
  818. versions_->current()->AddIterators(options, &list);
  819. Iterator* internal_iter =
  820. NewMergingIterator(&internal_comparator_, &list[0], list.size());
  821. versions_->current()->Ref();
  822. cleanup->mu = &mutex_;
  823. cleanup->mem = mem_;
  824. cleanup->imm = imm_;
  825. cleanup->version = versions_->current();
  826. internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, NULL);
  827. mutex_.Unlock();
  828. return internal_iter;
  829. }
  830. Iterator* DBImpl::TEST_NewInternalIterator() {
  831. SequenceNumber ignored;
  832. return NewInternalIterator(ReadOptions(), &ignored);
  833. }
  834. int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {
  835. MutexLock l(&mutex_);
  836. return versions_->MaxNextLevelOverlappingBytes();
  837. }
  838. Status DBImpl::Get(const ReadOptions& options,
  839. const Slice& key,
  840. std::string* value) {
  841. // TODO(opt): faster implementation
  842. Iterator* iter = NewIterator(options);
  843. iter->Seek(key);
  844. bool found = false;
  845. if (iter->Valid() && user_comparator()->Compare(key, iter->key()) == 0) {
  846. Slice v = iter->value();
  847. value->assign(v.data(), v.size());
  848. found = true;
  849. }
  850. // Non-OK iterator status trumps everything else
  851. Status result = iter->status();
  852. if (result.ok() && !found) {
  853. result = Status::NotFound(Slice()); // Use an empty error message for speed
  854. }
  855. delete iter;
  856. return result;
  857. }
  858. Iterator* DBImpl::NewIterator(const ReadOptions& options) {
  859. SequenceNumber latest_snapshot;
  860. Iterator* internal_iter = NewInternalIterator(options, &latest_snapshot);
  861. return NewDBIterator(
  862. &dbname_, env_, user_comparator(), internal_iter,
  863. (options.snapshot != NULL
  864. ? reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_
  865. : latest_snapshot));
  866. }
  867. const Snapshot* DBImpl::GetSnapshot() {
  868. MutexLock l(&mutex_);
  869. return snapshots_.New(versions_->LastSequence());
  870. }
  871. void DBImpl::ReleaseSnapshot(const Snapshot* s) {
  872. MutexLock l(&mutex_);
  873. snapshots_.Delete(reinterpret_cast<const SnapshotImpl*>(s));
  874. }
  875. // Convenience methods
  876. Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
  877. return DB::Put(o, key, val);
  878. }
  879. Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
  880. return DB::Delete(options, key);
  881. }
  882. Status DBImpl::Write(const WriteOptions& options, WriteBatch* updates) {
  883. Status status;
  884. MutexLock l(&mutex_);
  885. status = MakeRoomForWrite(false); // May temporarily release lock and wait
  886. uint64_t last_sequence = versions_->LastSequence();
  887. if (status.ok()) {
  888. WriteBatchInternal::SetSequence(updates, last_sequence + 1);
  889. last_sequence += WriteBatchInternal::Count(updates);
  890. versions_->SetLastSequence(last_sequence);
  891. // Add to log and apply to memtable
  892. status = log_->AddRecord(WriteBatchInternal::Contents(updates));
  893. if (status.ok() && options.sync) {
  894. status = logfile_->Sync();
  895. }
  896. if (status.ok()) {
  897. status = WriteBatchInternal::InsertInto(updates, mem_);
  898. }
  899. }
  900. if (options.post_write_snapshot != NULL) {
  901. *options.post_write_snapshot =
  902. status.ok() ? snapshots_.New(last_sequence) : NULL;
  903. }
  904. return status;
  905. }
  906. Status DBImpl::MakeRoomForWrite(bool force) {
  907. mutex_.AssertHeld();
  908. bool allow_delay = !force;
  909. Status s;
  910. while (true) {
  911. if (!bg_error_.ok()) {
  912. // Yield previous error
  913. s = bg_error_;
  914. break;
  915. } else if (
  916. allow_delay &&
  917. versions_->NumLevelFiles(0) >= config::kL0_SlowdownWritesTrigger) {
  918. // We are getting close to hitting a hard limit on the number of
  919. // L0 files. Rather than delaying a single write by several
  920. // seconds when we hit the hard limit, start delaying each
  921. // individual write by 1ms to reduce latency variance. Also,
  922. // this delay hands over some CPU to the compaction thread in
  923. // case it is sharing the same core as the writer.
  924. mutex_.Unlock();
  925. env_->SleepForMicroseconds(1000);
  926. allow_delay = false; // Do not delay a single write more than once
  927. mutex_.Lock();
  928. } else if (!force &&
  929. (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) {
  930. // There is room in current memtable
  931. break;
  932. } else if (imm_ != NULL) {
  933. // We have filled up the current memtable, but the previous
  934. // one is still being compacted, so we wait.
  935. compacting_cv_.Wait();
  936. } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) {
  937. // There are too many level-0 files.
  938. compacting_cv_.Wait();
  939. } else {
  940. // Attempt to switch to a new memtable and trigger compaction of old
  941. assert(versions_->PrevLogNumber() == 0);
  942. uint64_t new_log_number = versions_->NewFileNumber();
  943. WritableFile* lfile = NULL;
  944. s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile);
  945. if (!s.ok()) {
  946. break;
  947. }
  948. VersionEdit edit;
  949. edit.SetPrevLogNumber(versions_->LogNumber());
  950. edit.SetLogNumber(new_log_number);
  951. s = versions_->LogAndApply(&edit);
  952. if (!s.ok()) {
  953. delete lfile;
  954. env_->DeleteFile(LogFileName(dbname_, new_log_number));
  955. break;
  956. }
  957. delete log_;
  958. delete logfile_;
  959. logfile_ = lfile;
  960. log_ = new log::Writer(lfile);
  961. imm_ = mem_;
  962. has_imm_.Release_Store(imm_);
  963. mem_ = new MemTable(internal_comparator_);
  964. mem_->Ref();
  965. force = false; // Do not force another compaction if have room
  966. MaybeScheduleCompaction();
  967. }
  968. }
  969. return s;
  970. }
  971. bool DBImpl::GetProperty(const Slice& property, std::string* value) {
  972. value->clear();
  973. MutexLock l(&mutex_);
  974. Slice in = property;
  975. Slice prefix("leveldb.");
  976. if (!in.starts_with(prefix)) return false;
  977. in.remove_prefix(prefix.size());
  978. if (in.starts_with("num-files-at-level")) {
  979. in.remove_prefix(strlen("num-files-at-level"));
  980. uint64_t level;
  981. bool ok = ConsumeDecimalNumber(&in, &level) && in.empty();
  982. if (!ok || level < 0 || level >= config::kNumLevels) {
  983. return false;
  984. } else {
  985. char buf[100];
  986. snprintf(buf, sizeof(buf), "%d",
  987. versions_->NumLevelFiles(static_cast<int>(level)));
  988. *value = buf;
  989. return true;
  990. }
  991. } else if (in == "stats") {
  992. char buf[200];
  993. snprintf(buf, sizeof(buf),
  994. " Compactions\n"
  995. "Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n"
  996. "--------------------------------------------------\n"
  997. );
  998. value->append(buf);
  999. for (int level = 0; level < config::kNumLevels; level++) {
  1000. int files = versions_->NumLevelFiles(level);
  1001. if (stats_[level].micros > 0 || files > 0) {
  1002. snprintf(
  1003. buf, sizeof(buf),
  1004. "%3d %8d %8.0f %9.0f %8.0f %9.0f\n",
  1005. level,
  1006. files,
  1007. versions_->NumLevelBytes(level) / 1048576.0,
  1008. stats_[level].micros / 1e6,
  1009. stats_[level].bytes_read / 1048576.0,
  1010. stats_[level].bytes_written / 1048576.0);
  1011. value->append(buf);
  1012. }
  1013. }
  1014. return true;
  1015. }
  1016. return false;
  1017. }
  1018. void DBImpl::GetApproximateSizes(
  1019. const Range* range, int n,
  1020. uint64_t* sizes) {
  1021. // TODO(opt): better implementation
  1022. Version* v;
  1023. {
  1024. MutexLock l(&mutex_);
  1025. versions_->current()->Ref();
  1026. v = versions_->current();
  1027. }
  1028. for (int i = 0; i < n; i++) {
  1029. // Convert user_key into a corresponding internal key.
  1030. InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek);
  1031. InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek);
  1032. uint64_t start = versions_->ApproximateOffsetOf(v, k1);
  1033. uint64_t limit = versions_->ApproximateOffsetOf(v, k2);
  1034. sizes[i] = (limit >= start ? limit - start : 0);
  1035. }
  1036. {
  1037. MutexLock l(&mutex_);
  1038. v->Unref();
  1039. }
  1040. }
  1041. // Default implementations of convenience methods that subclasses of DB
  1042. // can call if they wish
  1043. Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
  1044. WriteBatch batch;
  1045. batch.Put(key, value);
  1046. return Write(opt, &batch);
  1047. }
  1048. Status DB::Delete(const WriteOptions& opt, const Slice& key) {
  1049. WriteBatch batch;
  1050. batch.Delete(key);
  1051. return Write(opt, &batch);
  1052. }
  1053. DB::~DB() { }
  1054. Status DB::Open(const Options& options, const std::string& dbname,
  1055. DB** dbptr) {
  1056. *dbptr = NULL;
  1057. DBImpl* impl = new DBImpl(options, dbname);
  1058. impl->mutex_.Lock();
  1059. VersionEdit edit;
  1060. Status s = impl->Recover(&edit); // Handles create_if_missing, error_if_exists
  1061. if (s.ok()) {
  1062. uint64_t new_log_number = impl->versions_->NewFileNumber();
  1063. WritableFile* lfile;
  1064. s = options.env->NewWritableFile(LogFileName(dbname, new_log_number),
  1065. &lfile);
  1066. if (s.ok()) {
  1067. edit.SetLogNumber(new_log_number);
  1068. impl->logfile_ = lfile;
  1069. impl->log_ = new log::Writer(lfile);
  1070. s = impl->versions_->LogAndApply(&edit);
  1071. }
  1072. if (s.ok()) {
  1073. impl->DeleteObsoleteFiles();
  1074. impl->MaybeScheduleCompaction();
  1075. }
  1076. }
  1077. impl->mutex_.Unlock();
  1078. if (s.ok()) {
  1079. *dbptr = impl;
  1080. } else {
  1081. delete impl;
  1082. }
  1083. return s;
  1084. }
  1085. Snapshot::~Snapshot() {
  1086. }
  1087. Status DestroyDB(const std::string& dbname, const Options& options) {
  1088. Env* env = options.env;
  1089. std::vector<std::string> filenames;
  1090. // Ignore error in case directory does not exist
  1091. env->GetChildren(dbname, &filenames);
  1092. if (filenames.empty()) {
  1093. return Status::OK();
  1094. }
  1095. FileLock* lock;
  1096. Status result = env->LockFile(LockFileName(dbname), &lock);
  1097. if (result.ok()) {
  1098. uint64_t number;
  1099. FileType type;
  1100. for (size_t i = 0; i < filenames.size(); i++) {
  1101. if (ParseFileName(filenames[i], &number, &type)) {
  1102. Status del = env->DeleteFile(dbname + "/" + filenames[i]);
  1103. if (result.ok() && !del.ok()) {
  1104. result = del;
  1105. }
  1106. }
  1107. }
  1108. env->UnlockFile(lock); // Ignore error since state is already gone
  1109. env->DeleteFile(LockFileName(dbname));
  1110. env->DeleteDir(dbname); // Ignore error in case dir contains other files
  1111. }
  1112. return result;
  1113. }
  1114. }