提供基本的ttl测试用例
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1292 lines
38 KiB

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