作者: 谢瑞阳 10225101483 徐翔宇 10225101535
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1345 linhas
40 KiB

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