25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1213 lines
36 KiB

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