Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

1211 rindas
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 "include/db.h"
  22. #include "include/env.h"
  23. #include "include/status.h"
  24. #include "include/table.h"
  25. #include "include/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(),output_number);
  579. s = iter->status();
  580. delete iter;
  581. if (s.ok()) {
  582. Log(env_, options_.info_log,
  583. "Generated table #%llu: %lld keys, %lld bytes",
  584. (unsigned long long) output_number,
  585. (unsigned long long) current_entries,
  586. (unsigned long long) current_bytes);
  587. }
  588. }
  589. return s;
  590. }
  591. Status DBImpl::InstallCompactionResults(CompactionState* compact) {
  592. mutex_.AssertHeld();
  593. Log(env_, options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes",
  594. compact->compaction->num_input_files(0),
  595. compact->compaction->level(),
  596. compact->compaction->num_input_files(1),
  597. compact->compaction->level() + 1,
  598. static_cast<long long>(compact->total_bytes));
  599. // Add compaction outputs
  600. compact->compaction->AddInputDeletions(compact->compaction->edit());
  601. const int level = compact->compaction->level();
  602. for (int i = 0; i < compact->outputs.size(); i++) {
  603. const CompactionState::Output& out = compact->outputs[i];
  604. compact->compaction->edit()->AddFile(
  605. level + 1,
  606. out.number, out.file_size, out.smallest, out.largest);
  607. pending_outputs_.erase(out.number);
  608. }
  609. compact->outputs.clear();
  610. Status s = Install(compact->compaction->edit(), log_number_, NULL);
  611. if (s.ok()) {
  612. compact->compaction->ReleaseInputs();
  613. DeleteObsoleteFiles();
  614. } else {
  615. // Discard any files we may have created during this failed compaction
  616. for (int i = 0; i < compact->outputs.size(); i++) {
  617. env_->DeleteFile(TableFileName(dbname_, compact->outputs[i].number));
  618. }
  619. }
  620. return s;
  621. }
  622. Status DBImpl::DoCompactionWork(CompactionState* compact) {
  623. Log(env_, options_.info_log, "Compacting %d@%d + %d@%d files",
  624. compact->compaction->num_input_files(0),
  625. compact->compaction->level(),
  626. compact->compaction->num_input_files(1),
  627. compact->compaction->level() + 1);
  628. assert(versions_->NumLevelFiles(compact->compaction->level()) > 0);
  629. assert(compact->builder == NULL);
  630. assert(compact->outfile == NULL);
  631. if (snapshots_.empty()) {
  632. compact->smallest_snapshot = last_sequence_;
  633. } else {
  634. compact->smallest_snapshot = snapshots_.oldest()->number_;
  635. }
  636. // Release mutex while we're actually doing the compaction work
  637. compacting_ = true;
  638. mutex_.Unlock();
  639. Iterator* input = versions_->MakeInputIterator(compact->compaction);
  640. input->SeekToFirst();
  641. Status status;
  642. ParsedInternalKey ikey;
  643. std::string current_user_key;
  644. bool has_current_user_key = false;
  645. SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
  646. for (; input->Valid() && !shutting_down_.Acquire_Load(); ) {
  647. Slice key = input->key();
  648. InternalKey tmp_internal_key;
  649. tmp_internal_key.DecodeFrom(key);
  650. if (compact->compaction->ShouldStopBefore(tmp_internal_key) &&
  651. compact->builder != NULL) {
  652. status = FinishCompactionOutputFile(compact, input);
  653. if (!status.ok()) {
  654. break;
  655. }
  656. }
  657. // Handle key/value, add to state, etc.
  658. bool drop = false;
  659. if (!ParseInternalKey(key, &ikey)) {
  660. // Do not hide error keys
  661. current_user_key.clear();
  662. has_current_user_key = false;
  663. last_sequence_for_key = kMaxSequenceNumber;
  664. } else {
  665. if (!has_current_user_key ||
  666. user_comparator()->Compare(ikey.user_key,
  667. Slice(current_user_key)) != 0) {
  668. // First occurrence of this user key
  669. current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
  670. has_current_user_key = true;
  671. last_sequence_for_key = kMaxSequenceNumber;
  672. }
  673. if (last_sequence_for_key <= compact->smallest_snapshot) {
  674. // Hidden by an newer entry for same user key
  675. drop = true; // (A)
  676. } else if (ikey.type == kTypeDeletion &&
  677. ikey.sequence <= compact->smallest_snapshot &&
  678. compact->compaction->IsBaseLevelForKey(ikey.user_key)) {
  679. // For this user key:
  680. // (1) there is no data in higher levels
  681. // (2) data in lower levels will have larger sequence numbers
  682. // (3) data in layers that are being compacted here and have
  683. // smaller sequence numbers will be dropped in the next
  684. // few iterations of this loop (by rule (A) above).
  685. // Therefore this deletion marker is obsolete and can be dropped.
  686. drop = true;
  687. }
  688. last_sequence_for_key = ikey.sequence;
  689. }
  690. #if 0
  691. Log(env_, options_.info_log,
  692. " Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
  693. "%d smallest_snapshot: %d",
  694. ikey.user_key.ToString().c_str(),
  695. (int)ikey.sequence, ikey.type, kTypeLargeValueRef, drop,
  696. compact->compaction->IsBaseLevelForKey(ikey.user_key),
  697. (int)last_sequence_for_key, (int)compact->smallest_snapshot);
  698. #endif
  699. if (!drop) {
  700. // Open output file if necessary
  701. if (compact->builder == NULL) {
  702. status = OpenCompactionOutputFile(compact);
  703. if (!status.ok()) {
  704. break;
  705. }
  706. }
  707. if (compact->builder->NumEntries() == 0) {
  708. compact->current_output()->smallest.DecodeFrom(key);
  709. }
  710. compact->current_output()->largest.DecodeFrom(key);
  711. if (ikey.type == kTypeLargeValueRef) {
  712. if (input->value().size() != LargeValueRef::ByteSize()) {
  713. if (options_.paranoid_checks) {
  714. status = Status::Corruption("invalid large value ref");
  715. break;
  716. } else {
  717. Log(env_, options_.info_log,
  718. "compaction found invalid large value ref");
  719. }
  720. } else {
  721. compact->compaction->edit()->AddLargeValueRef(
  722. LargeValueRef::FromRef(input->value()),
  723. compact->current_output()->number,
  724. input->key());
  725. compact->builder->Add(key, input->value());
  726. }
  727. } else {
  728. compact->builder->Add(key, input->value());
  729. }
  730. // Close output file if it is big enough
  731. if (compact->builder->FileSize() >=
  732. compact->compaction->MaxOutputFileSize()) {
  733. status = FinishCompactionOutputFile(compact, input);
  734. if (!status.ok()) {
  735. break;
  736. }
  737. }
  738. }
  739. input->Next();
  740. }
  741. if (status.ok() && shutting_down_.Acquire_Load()) {
  742. status = Status::IOError("Deleting DB during compaction");
  743. }
  744. if (status.ok() && compact->builder != NULL) {
  745. status = FinishCompactionOutputFile(compact, input);
  746. }
  747. if (status.ok()) {
  748. status = input->status();
  749. }
  750. delete input;
  751. input = NULL;
  752. mutex_.Lock();
  753. if (status.ok()) {
  754. status = InstallCompactionResults(compact);
  755. }
  756. compacting_ = false;
  757. compacting_cv_.SignalAll();
  758. return status;
  759. }
  760. Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
  761. SequenceNumber* latest_snapshot) {
  762. mutex_.Lock();
  763. *latest_snapshot = last_sequence_;
  764. // Collect together all needed child iterators
  765. std::vector<Iterator*> list;
  766. list.push_back(mem_->NewIterator());
  767. versions_->current()->AddIterators(options, &list);
  768. Iterator* internal_iter =
  769. NewMergingIterator(&internal_comparator_, &list[0], list.size());
  770. versions_->current()->Ref();
  771. internal_iter->RegisterCleanup(&DBImpl::Unref, this, versions_->current());
  772. mutex_.Unlock();
  773. return internal_iter;
  774. }
  775. Iterator* DBImpl::TEST_NewInternalIterator() {
  776. SequenceNumber ignored;
  777. return NewInternalIterator(ReadOptions(), &ignored);
  778. }
  779. int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {
  780. MutexLock l(&mutex_);
  781. return versions_->MaxNextLevelOverlappingBytes();
  782. }
  783. Status DBImpl::Get(const ReadOptions& options,
  784. const Slice& key,
  785. std::string* value) {
  786. // TODO(opt): faster implementation
  787. Iterator* iter = NewIterator(options);
  788. iter->Seek(key);
  789. bool found = false;
  790. if (iter->Valid() && user_comparator()->Compare(key, iter->key()) == 0) {
  791. Slice v = iter->value();
  792. value->assign(v.data(), v.size());
  793. found = true;
  794. }
  795. // Non-OK iterator status trumps everything else
  796. Status result = iter->status();
  797. if (result.ok() && !found) {
  798. result = Status::NotFound(Slice()); // Use an empty error message for speed
  799. }
  800. delete iter;
  801. return result;
  802. }
  803. Iterator* DBImpl::NewIterator(const ReadOptions& options) {
  804. SequenceNumber latest_snapshot;
  805. Iterator* internal_iter = NewInternalIterator(options, &latest_snapshot);
  806. SequenceNumber sequence =
  807. (options.snapshot ? options.snapshot->number_ : latest_snapshot);
  808. return NewDBIterator(&dbname_, env_,
  809. user_comparator(), internal_iter, sequence);
  810. }
  811. void DBImpl::Unref(void* arg1, void* arg2) {
  812. DBImpl* impl = reinterpret_cast<DBImpl*>(arg1);
  813. Version* v = reinterpret_cast<Version*>(arg2);
  814. MutexLock l(&impl->mutex_);
  815. v->Unref();
  816. }
  817. const Snapshot* DBImpl::GetSnapshot() {
  818. MutexLock l(&mutex_);
  819. return snapshots_.New(last_sequence_);
  820. }
  821. void DBImpl::ReleaseSnapshot(const Snapshot* s) {
  822. MutexLock l(&mutex_);
  823. snapshots_.Delete(s);
  824. }
  825. // Convenience methods
  826. Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
  827. return DB::Put(o, key, val);
  828. }
  829. Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
  830. return DB::Delete(options, key);
  831. }
  832. Status DBImpl::Write(const WriteOptions& options, WriteBatch* updates) {
  833. Status status;
  834. WriteBatch* final = NULL;
  835. {
  836. MutexLock l(&mutex_);
  837. if (!bg_error_.ok()) {
  838. status = bg_error_;
  839. } else if (mem_->ApproximateMemoryUsage() > options_.write_buffer_size) {
  840. status = CompactMemTable();
  841. }
  842. if (status.ok()) {
  843. status = HandleLargeValues(last_sequence_ + 1, updates, &final);
  844. }
  845. if (status.ok()) {
  846. WriteBatchInternal::SetSequence(final, last_sequence_ + 1);
  847. last_sequence_ += WriteBatchInternal::Count(final);
  848. // Add to log and apply to memtable
  849. status = log_->AddRecord(WriteBatchInternal::Contents(final));
  850. if (status.ok() && options.sync) {
  851. status = logfile_->Sync();
  852. }
  853. if (status.ok()) {
  854. status = WriteBatchInternal::InsertInto(final, mem_);
  855. }
  856. }
  857. if (options.post_write_snapshot != NULL) {
  858. *options.post_write_snapshot =
  859. status.ok() ? snapshots_.New(last_sequence_) : NULL;
  860. }
  861. }
  862. if (final != updates) {
  863. delete final;
  864. }
  865. return status;
  866. }
  867. bool DBImpl::HasLargeValues(const WriteBatch& batch) const {
  868. if (WriteBatchInternal::ByteSize(&batch) >= options_.large_value_threshold) {
  869. for (WriteBatchInternal::Iterator it(batch); !it.Done(); it.Next()) {
  870. if (it.op() == kTypeValue &&
  871. it.value().size() >= options_.large_value_threshold) {
  872. return true;
  873. }
  874. }
  875. }
  876. return false;
  877. }
  878. // Given "raw_value", determines the appropriate compression format to use
  879. // and stores the data that should be written to the large value file in
  880. // "*file_bytes", and sets "*ref" to the appropriate large value reference.
  881. // May use "*scratch" as backing store for "*file_bytes".
  882. void DBImpl::MaybeCompressLargeValue(
  883. const Slice& raw_value,
  884. Slice* file_bytes,
  885. std::string* scratch,
  886. LargeValueRef* ref) {
  887. switch (options_.compression) {
  888. case kSnappyCompression: {
  889. if (port::Snappy_Compress(raw_value.data(), raw_value.size(), scratch) &&
  890. (scratch->size() < (raw_value.size() / 8) * 7)) {
  891. *file_bytes = *scratch;
  892. *ref = LargeValueRef::Make(raw_value, kSnappyCompression);
  893. return;
  894. }
  895. // Less than 12.5% compression: just leave as uncompressed data
  896. break;
  897. }
  898. case kNoCompression:
  899. // Use default code outside of switch
  900. break;
  901. }
  902. // Store as uncompressed data
  903. *file_bytes = raw_value;
  904. *ref = LargeValueRef::Make(raw_value, kNoCompression);
  905. }
  906. Status DBImpl::HandleLargeValues(SequenceNumber assigned_seq,
  907. WriteBatch* updates,
  908. WriteBatch** final) {
  909. if (!HasLargeValues(*updates)) {
  910. // Fast path: no large values found
  911. *final = updates;
  912. } else {
  913. // Copy *updates to a new WriteBatch, replacing the references to
  914. *final = new WriteBatch;
  915. SequenceNumber seq = assigned_seq;
  916. for (WriteBatchInternal::Iterator it(*updates); !it.Done(); it.Next()) {
  917. switch (it.op()) {
  918. case kTypeValue:
  919. if (it.value().size() < options_.large_value_threshold) {
  920. (*final)->Put(it.key(), it.value());
  921. } else {
  922. std::string scratch;
  923. Slice file_bytes;
  924. LargeValueRef large_ref;
  925. MaybeCompressLargeValue(
  926. it.value(), &file_bytes, &scratch, &large_ref);
  927. InternalKey ikey(it.key(), seq, kTypeLargeValueRef);
  928. if (versions_->RegisterLargeValueRef(large_ref, log_number_,ikey)) {
  929. // TODO(opt): avoid holding the lock here (but be careful about
  930. // another thread doing a Write and changing log_number_ or
  931. // having us get a different "assigned_seq" value).
  932. uint64_t tmp_number = versions_->NewFileNumber();
  933. pending_outputs_.insert(tmp_number);
  934. std::string tmp = TempFileName(dbname_, tmp_number);
  935. WritableFile* file;
  936. Status s = env_->NewWritableFile(tmp, &file);
  937. if (!s.ok()) {
  938. return s; // Caller will delete *final
  939. }
  940. file->Append(file_bytes);
  941. s = file->Close();
  942. delete file;
  943. if (s.ok()) {
  944. const std::string fname =
  945. LargeValueFileName(dbname_, large_ref);
  946. s = env_->RenameFile(tmp, fname);
  947. } else {
  948. Log(env_, options_.info_log, "Write large value: %s",
  949. s.ToString().c_str());
  950. }
  951. pending_outputs_.erase(tmp_number);
  952. if (!s.ok()) {
  953. env_->DeleteFile(tmp); // Cleanup; intentionally ignoring error
  954. return s; // Caller will delete *final
  955. }
  956. }
  957. // Put an indirect reference in the write batch in place
  958. // of large value
  959. WriteBatchInternal::PutLargeValueRef(*final, it.key(), large_ref);
  960. }
  961. break;
  962. case kTypeLargeValueRef:
  963. return Status::Corruption("Corrupted write batch");
  964. break;
  965. case kTypeDeletion:
  966. (*final)->Delete(it.key());
  967. break;
  968. }
  969. seq = seq + 1;
  970. }
  971. }
  972. return Status::OK();
  973. }
  974. bool DBImpl::GetProperty(const Slice& property, uint64_t* value) {
  975. MutexLock l(&mutex_);
  976. Slice in = property;
  977. Slice prefix("leveldb.");
  978. if (!in.starts_with(prefix)) return false;
  979. in.remove_prefix(prefix.size());
  980. if (in.starts_with("num-files-at-level")) {
  981. in.remove_prefix(strlen("num-files-at-level"));
  982. uint64_t level;
  983. bool ok = ConsumeDecimalNumber(&in, &level) && in.empty();
  984. if (!ok || level < 0 || level >= config::kNumLevels) {
  985. return false;
  986. } else {
  987. *value = versions_->NumLevelFiles(level);
  988. return true;
  989. }
  990. }
  991. return false;
  992. }
  993. void DBImpl::GetApproximateSizes(
  994. const Range* range, int n,
  995. uint64_t* sizes) {
  996. // TODO(opt): better implementation
  997. Version* v;
  998. {
  999. MutexLock l(&mutex_);
  1000. versions_->current()->Ref();
  1001. v = versions_->current();
  1002. }
  1003. for (int i = 0; i < n; i++) {
  1004. // Convert user_key into a corresponding internal key.
  1005. InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek);
  1006. InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek);
  1007. uint64_t start = versions_->ApproximateOffsetOf(v, k1);
  1008. uint64_t limit = versions_->ApproximateOffsetOf(v, k2);
  1009. sizes[i] = (limit >= start ? limit - start : 0);
  1010. }
  1011. {
  1012. MutexLock l(&mutex_);
  1013. v->Unref();
  1014. }
  1015. }
  1016. // Default implementations of convenience methods that subclasses of DB
  1017. // can call if they wish
  1018. Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
  1019. WriteBatch batch;
  1020. batch.Put(key, value);
  1021. return Write(opt, &batch);
  1022. }
  1023. Status DB::Delete(const WriteOptions& opt, const Slice& key) {
  1024. WriteBatch batch;
  1025. batch.Delete(key);
  1026. return Write(opt, &batch);
  1027. }
  1028. DB::~DB() { }
  1029. Status DB::Open(const Options& options, const std::string& dbname,
  1030. DB** dbptr) {
  1031. *dbptr = NULL;
  1032. DBImpl* impl = new DBImpl(options, dbname);
  1033. impl->mutex_.Lock();
  1034. VersionEdit edit;
  1035. Status s = impl->Recover(&edit); // Handles create_if_missing, error_if_exists
  1036. if (s.ok()) {
  1037. impl->log_number_ = impl->versions_->NewFileNumber();
  1038. WritableFile* lfile;
  1039. s = options.env->NewWritableFile(LogFileName(dbname, impl->log_number_),
  1040. &lfile);
  1041. if (s.ok()) {
  1042. impl->logfile_ = lfile;
  1043. impl->log_ = new log::Writer(lfile);
  1044. s = impl->Install(&edit, impl->log_number_, NULL);
  1045. }
  1046. if (s.ok()) {
  1047. impl->DeleteObsoleteFiles();
  1048. }
  1049. }
  1050. impl->mutex_.Unlock();
  1051. if (s.ok()) {
  1052. *dbptr = impl;
  1053. } else {
  1054. delete impl;
  1055. }
  1056. return s;
  1057. }
  1058. Status DestroyDB(const std::string& dbname, const Options& options) {
  1059. Env* env = options.env;
  1060. std::vector<std::string> filenames;
  1061. // Ignore error in case directory does not exist
  1062. env->GetChildren(dbname, &filenames);
  1063. if (filenames.empty()) {
  1064. return Status::OK();
  1065. }
  1066. FileLock* lock;
  1067. Status result = env->LockFile(LockFileName(dbname), &lock);
  1068. if (result.ok()) {
  1069. uint64_t number;
  1070. LargeValueRef large_ref;
  1071. FileType type;
  1072. for (int i = 0; i < filenames.size(); i++) {
  1073. if (ParseFileName(filenames[i], &number, &large_ref, &type)) {
  1074. Status del = env->DeleteFile(dbname + "/" + filenames[i]);
  1075. if (result.ok() && !del.ok()) {
  1076. result = del;
  1077. }
  1078. }
  1079. }
  1080. env->UnlockFile(lock); // Ignore error since state is already gone
  1081. env->DeleteFile(LockFileName(dbname));
  1082. env->DeleteDir(dbname); // Ignore error in case dir contains other files
  1083. }
  1084. return result;
  1085. }
  1086. }