作者: 谢瑞阳 10225101483 徐翔宇 10225101535
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.

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