小组成员:10215300402-朱维清 & 10222140408 谷杰
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.

1463 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. // Wait a little bit before retrying background compaction in
  549. // case this is an environmental problem and we do not want to
  550. // chew up resources for failed compactions for the duration of
  551. // the problem.
  552. bg_cv_.SignalAll(); // In case a waiter can proceed despite the error
  553. Log(options_.info_log, "Waiting after background compaction error: %s",
  554. s.ToString().c_str());
  555. mutex_.Unlock();
  556. env_->SleepForMicroseconds(1000000);
  557. mutex_.Lock();
  558. }
  559. }
  560. bg_compaction_scheduled_ = false;
  561. // Previous compaction may have produced too many files in a level,
  562. // so reschedule another compaction if needed.
  563. MaybeScheduleCompaction();
  564. bg_cv_.SignalAll();
  565. }
  566. Status DBImpl::BackgroundCompaction() {
  567. mutex_.AssertHeld();
  568. if (imm_ != NULL) {
  569. return CompactMemTable();
  570. }
  571. Compaction* c;
  572. bool is_manual = (manual_compaction_ != NULL);
  573. InternalKey manual_end;
  574. if (is_manual) {
  575. ManualCompaction* m = manual_compaction_;
  576. c = versions_->CompactRange(m->level, m->begin, m->end);
  577. m->done = (c == NULL);
  578. if (c != NULL) {
  579. manual_end = c->input(0, c->num_input_files(0) - 1)->largest;
  580. }
  581. Log(options_.info_log,
  582. "Manual compaction at level-%d from %s .. %s; will stop at %s\n",
  583. m->level,
  584. (m->begin ? m->begin->DebugString().c_str() : "(begin)"),
  585. (m->end ? m->end->DebugString().c_str() : "(end)"),
  586. (m->done ? "(end)" : manual_end.DebugString().c_str()));
  587. } else {
  588. c = versions_->PickCompaction();
  589. }
  590. Status status;
  591. if (c == NULL) {
  592. // Nothing to do
  593. } else if (!is_manual && c->IsTrivialMove()) {
  594. // Move file to next level
  595. assert(c->num_input_files(0) == 1);
  596. FileMetaData* f = c->input(0, 0);
  597. c->edit()->DeleteFile(c->level(), f->number);
  598. c->edit()->AddFile(c->level() + 1, f->number, f->file_size,
  599. f->smallest, f->largest);
  600. status = versions_->LogAndApply(c->edit(), &mutex_);
  601. VersionSet::LevelSummaryStorage tmp;
  602. Log(options_.info_log, "Moved #%lld to level-%d %lld bytes %s: %s\n",
  603. static_cast<unsigned long long>(f->number),
  604. c->level() + 1,
  605. static_cast<unsigned long long>(f->file_size),
  606. status.ToString().c_str(),
  607. versions_->LevelSummary(&tmp));
  608. } else {
  609. CompactionState* compact = new CompactionState(c);
  610. status = DoCompactionWork(compact);
  611. CleanupCompaction(compact);
  612. c->ReleaseInputs();
  613. DeleteObsoleteFiles();
  614. }
  615. delete c;
  616. if (status.ok()) {
  617. // Done
  618. } else if (shutting_down_.Acquire_Load()) {
  619. // Ignore compaction errors found during shutting down
  620. } else {
  621. Log(options_.info_log,
  622. "Compaction error: %s", status.ToString().c_str());
  623. if (options_.paranoid_checks && bg_error_.ok()) {
  624. bg_error_ = status;
  625. }
  626. }
  627. if (is_manual) {
  628. ManualCompaction* m = manual_compaction_;
  629. if (!status.ok()) {
  630. m->done = true;
  631. }
  632. if (!m->done) {
  633. // We only compacted part of the requested range. Update *m
  634. // to the range that is left to be compacted.
  635. m->tmp_storage = manual_end;
  636. m->begin = &m->tmp_storage;
  637. }
  638. manual_compaction_ = NULL;
  639. }
  640. return status;
  641. }
  642. void DBImpl::CleanupCompaction(CompactionState* compact) {
  643. mutex_.AssertHeld();
  644. if (compact->builder != NULL) {
  645. // May happen if we get a shutdown call in the middle of compaction
  646. compact->builder->Abandon();
  647. delete compact->builder;
  648. } else {
  649. assert(compact->outfile == NULL);
  650. }
  651. delete compact->outfile;
  652. for (size_t i = 0; i < compact->outputs.size(); i++) {
  653. const CompactionState::Output& out = compact->outputs[i];
  654. pending_outputs_.erase(out.number);
  655. }
  656. delete compact;
  657. }
  658. Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) {
  659. assert(compact != NULL);
  660. assert(compact->builder == NULL);
  661. uint64_t file_number;
  662. {
  663. mutex_.Lock();
  664. file_number = versions_->NewFileNumber();
  665. pending_outputs_.insert(file_number);
  666. CompactionState::Output out;
  667. out.number = file_number;
  668. out.smallest.Clear();
  669. out.largest.Clear();
  670. compact->outputs.push_back(out);
  671. mutex_.Unlock();
  672. }
  673. // Make the output file
  674. std::string fname = TableFileName(dbname_, file_number);
  675. Status s = env_->NewWritableFile(fname, &compact->outfile);
  676. if (s.ok()) {
  677. compact->builder = new TableBuilder(options_, compact->outfile);
  678. }
  679. return s;
  680. }
  681. Status DBImpl::FinishCompactionOutputFile(CompactionState* compact,
  682. Iterator* input) {
  683. assert(compact != NULL);
  684. assert(compact->outfile != NULL);
  685. assert(compact->builder != NULL);
  686. const uint64_t output_number = compact->current_output()->number;
  687. assert(output_number != 0);
  688. // Check for iterator errors
  689. Status s = input->status();
  690. const uint64_t current_entries = compact->builder->NumEntries();
  691. if (s.ok()) {
  692. s = compact->builder->Finish();
  693. } else {
  694. compact->builder->Abandon();
  695. }
  696. const uint64_t current_bytes = compact->builder->FileSize();
  697. compact->current_output()->file_size = current_bytes;
  698. compact->total_bytes += current_bytes;
  699. delete compact->builder;
  700. compact->builder = NULL;
  701. // Finish and check for file errors
  702. if (s.ok()) {
  703. s = compact->outfile->Sync();
  704. }
  705. if (s.ok()) {
  706. s = compact->outfile->Close();
  707. }
  708. delete compact->outfile;
  709. compact->outfile = NULL;
  710. if (s.ok() && current_entries > 0) {
  711. // Verify that the table is usable
  712. Iterator* iter = table_cache_->NewIterator(ReadOptions(),
  713. output_number,
  714. current_bytes);
  715. s = iter->status();
  716. delete iter;
  717. if (s.ok()) {
  718. Log(options_.info_log,
  719. "Generated table #%llu: %lld keys, %lld bytes",
  720. (unsigned long long) output_number,
  721. (unsigned long long) current_entries,
  722. (unsigned long long) current_bytes);
  723. }
  724. }
  725. return s;
  726. }
  727. Status DBImpl::InstallCompactionResults(CompactionState* compact) {
  728. mutex_.AssertHeld();
  729. Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes",
  730. compact->compaction->num_input_files(0),
  731. compact->compaction->level(),
  732. compact->compaction->num_input_files(1),
  733. compact->compaction->level() + 1,
  734. static_cast<long long>(compact->total_bytes));
  735. // Add compaction outputs
  736. compact->compaction->AddInputDeletions(compact->compaction->edit());
  737. const int level = compact->compaction->level();
  738. for (size_t i = 0; i < compact->outputs.size(); i++) {
  739. const CompactionState::Output& out = compact->outputs[i];
  740. compact->compaction->edit()->AddFile(
  741. level + 1,
  742. out.number, out.file_size, out.smallest, out.largest);
  743. }
  744. return versions_->LogAndApply(compact->compaction->edit(), &mutex_);
  745. }
  746. Status DBImpl::DoCompactionWork(CompactionState* compact) {
  747. const uint64_t start_micros = env_->NowMicros();
  748. int64_t imm_micros = 0; // Micros spent doing imm_ compactions
  749. Log(options_.info_log, "Compacting %d@%d + %d@%d files",
  750. compact->compaction->num_input_files(0),
  751. compact->compaction->level(),
  752. compact->compaction->num_input_files(1),
  753. compact->compaction->level() + 1);
  754. assert(versions_->NumLevelFiles(compact->compaction->level()) > 0);
  755. assert(compact->builder == NULL);
  756. assert(compact->outfile == NULL);
  757. if (snapshots_.empty()) {
  758. compact->smallest_snapshot = versions_->LastSequence();
  759. } else {
  760. compact->smallest_snapshot = snapshots_.oldest()->number_;
  761. }
  762. // Release mutex while we're actually doing the compaction work
  763. mutex_.Unlock();
  764. Iterator* input = versions_->MakeInputIterator(compact->compaction);
  765. input->SeekToFirst();
  766. Status status;
  767. ParsedInternalKey ikey;
  768. std::string current_user_key;
  769. bool has_current_user_key = false;
  770. SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
  771. for (; input->Valid() && !shutting_down_.Acquire_Load(); ) {
  772. // Prioritize immutable compaction work
  773. if (has_imm_.NoBarrier_Load() != NULL) {
  774. const uint64_t imm_start = env_->NowMicros();
  775. mutex_.Lock();
  776. if (imm_ != NULL) {
  777. CompactMemTable();
  778. bg_cv_.SignalAll(); // Wakeup MakeRoomForWrite() if necessary
  779. }
  780. mutex_.Unlock();
  781. imm_micros += (env_->NowMicros() - imm_start);
  782. }
  783. Slice key = input->key();
  784. if (compact->compaction->ShouldStopBefore(key) &&
  785. compact->builder != NULL) {
  786. status = FinishCompactionOutputFile(compact, input);
  787. if (!status.ok()) {
  788. break;
  789. }
  790. }
  791. // Handle key/value, add to state, etc.
  792. bool drop = false;
  793. if (!ParseInternalKey(key, &ikey)) {
  794. // Do not hide error keys
  795. current_user_key.clear();
  796. has_current_user_key = false;
  797. last_sequence_for_key = kMaxSequenceNumber;
  798. } else {
  799. if (!has_current_user_key ||
  800. user_comparator()->Compare(ikey.user_key,
  801. Slice(current_user_key)) != 0) {
  802. // First occurrence of this user key
  803. current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
  804. has_current_user_key = true;
  805. last_sequence_for_key = kMaxSequenceNumber;
  806. }
  807. if (last_sequence_for_key <= compact->smallest_snapshot) {
  808. // Hidden by an newer entry for same user key
  809. drop = true; // (A)
  810. } else if (ikey.type == kTypeDeletion &&
  811. ikey.sequence <= compact->smallest_snapshot &&
  812. compact->compaction->IsBaseLevelForKey(ikey.user_key)) {
  813. // For this user key:
  814. // (1) there is no data in higher levels
  815. // (2) data in lower levels will have larger sequence numbers
  816. // (3) data in layers that are being compacted here and have
  817. // smaller sequence numbers will be dropped in the next
  818. // few iterations of this loop (by rule (A) above).
  819. // Therefore this deletion marker is obsolete and can be dropped.
  820. drop = true;
  821. }
  822. last_sequence_for_key = ikey.sequence;
  823. }
  824. #if 0
  825. Log(options_.info_log,
  826. " Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
  827. "%d smallest_snapshot: %d",
  828. ikey.user_key.ToString().c_str(),
  829. (int)ikey.sequence, ikey.type, kTypeValue, drop,
  830. compact->compaction->IsBaseLevelForKey(ikey.user_key),
  831. (int)last_sequence_for_key, (int)compact->smallest_snapshot);
  832. #endif
  833. if (!drop) {
  834. // Open output file if necessary
  835. if (compact->builder == NULL) {
  836. status = OpenCompactionOutputFile(compact);
  837. if (!status.ok()) {
  838. break;
  839. }
  840. }
  841. if (compact->builder->NumEntries() == 0) {
  842. compact->current_output()->smallest.DecodeFrom(key);
  843. }
  844. compact->current_output()->largest.DecodeFrom(key);
  845. compact->builder->Add(key, input->value());
  846. // Close output file if it is big enough
  847. if (compact->builder->FileSize() >=
  848. compact->compaction->MaxOutputFileSize()) {
  849. status = FinishCompactionOutputFile(compact, input);
  850. if (!status.ok()) {
  851. break;
  852. }
  853. }
  854. }
  855. input->Next();
  856. }
  857. if (status.ok() && shutting_down_.Acquire_Load()) {
  858. status = Status::IOError("Deleting DB during compaction");
  859. }
  860. if (status.ok() && compact->builder != NULL) {
  861. status = FinishCompactionOutputFile(compact, input);
  862. }
  863. if (status.ok()) {
  864. status = input->status();
  865. }
  866. delete input;
  867. input = NULL;
  868. CompactionStats stats;
  869. stats.micros = env_->NowMicros() - start_micros - imm_micros;
  870. for (int which = 0; which < 2; which++) {
  871. for (int i = 0; i < compact->compaction->num_input_files(which); i++) {
  872. stats.bytes_read += compact->compaction->input(which, i)->file_size;
  873. }
  874. }
  875. for (size_t i = 0; i < compact->outputs.size(); i++) {
  876. stats.bytes_written += compact->outputs[i].file_size;
  877. }
  878. mutex_.Lock();
  879. stats_[compact->compaction->level() + 1].Add(stats);
  880. if (status.ok()) {
  881. status = InstallCompactionResults(compact);
  882. }
  883. VersionSet::LevelSummaryStorage tmp;
  884. Log(options_.info_log,
  885. "compacted to: %s", versions_->LevelSummary(&tmp));
  886. return status;
  887. }
  888. namespace {
  889. struct IterState {
  890. port::Mutex* mu;
  891. Version* version;
  892. MemTable* mem;
  893. MemTable* imm;
  894. };
  895. static void CleanupIteratorState(void* arg1, void* arg2) {
  896. IterState* state = reinterpret_cast<IterState*>(arg1);
  897. state->mu->Lock();
  898. state->mem->Unref();
  899. if (state->imm != NULL) state->imm->Unref();
  900. state->version->Unref();
  901. state->mu->Unlock();
  902. delete state;
  903. }
  904. } // namespace
  905. Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
  906. SequenceNumber* latest_snapshot) {
  907. IterState* cleanup = new IterState;
  908. mutex_.Lock();
  909. *latest_snapshot = versions_->LastSequence();
  910. // Collect together all needed child iterators
  911. std::vector<Iterator*> list;
  912. list.push_back(mem_->NewIterator());
  913. mem_->Ref();
  914. if (imm_ != NULL) {
  915. list.push_back(imm_->NewIterator());
  916. imm_->Ref();
  917. }
  918. versions_->current()->AddIterators(options, &list);
  919. Iterator* internal_iter =
  920. NewMergingIterator(&internal_comparator_, &list[0], list.size());
  921. versions_->current()->Ref();
  922. cleanup->mu = &mutex_;
  923. cleanup->mem = mem_;
  924. cleanup->imm = imm_;
  925. cleanup->version = versions_->current();
  926. internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, NULL);
  927. mutex_.Unlock();
  928. return internal_iter;
  929. }
  930. Iterator* DBImpl::TEST_NewInternalIterator() {
  931. SequenceNumber ignored;
  932. return NewInternalIterator(ReadOptions(), &ignored);
  933. }
  934. int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {
  935. MutexLock l(&mutex_);
  936. return versions_->MaxNextLevelOverlappingBytes();
  937. }
  938. Status DBImpl::Get(const ReadOptions& options,
  939. const Slice& key,
  940. std::string* value) {
  941. Status s;
  942. MutexLock l(&mutex_);
  943. SequenceNumber snapshot;
  944. if (options.snapshot != NULL) {
  945. snapshot = reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_;
  946. } else {
  947. snapshot = versions_->LastSequence();
  948. }
  949. MemTable* mem = mem_;
  950. MemTable* imm = imm_;
  951. Version* current = versions_->current();
  952. mem->Ref();
  953. if (imm != NULL) imm->Ref();
  954. current->Ref();
  955. bool have_stat_update = false;
  956. Version::GetStats stats;
  957. // Unlock while reading from files and memtables
  958. {
  959. mutex_.Unlock();
  960. // First look in the memtable, then in the immutable memtable (if any).
  961. LookupKey lkey(key, snapshot);
  962. if (mem->Get(lkey, value, &s)) {
  963. // Done
  964. } else if (imm != NULL && imm->Get(lkey, value, &s)) {
  965. // Done
  966. } else {
  967. s = current->Get(options, lkey, value, &stats);
  968. have_stat_update = true;
  969. }
  970. mutex_.Lock();
  971. }
  972. if (have_stat_update && current->UpdateStats(stats)) {
  973. MaybeScheduleCompaction();
  974. }
  975. mem->Unref();
  976. if (imm != NULL) imm->Unref();
  977. current->Unref();
  978. return s;
  979. }
  980. Iterator* DBImpl::NewIterator(const ReadOptions& options) {
  981. SequenceNumber latest_snapshot;
  982. Iterator* internal_iter = NewInternalIterator(options, &latest_snapshot);
  983. return NewDBIterator(
  984. &dbname_, env_, user_comparator(), internal_iter,
  985. (options.snapshot != NULL
  986. ? reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_
  987. : latest_snapshot));
  988. }
  989. const Snapshot* DBImpl::GetSnapshot() {
  990. MutexLock l(&mutex_);
  991. return snapshots_.New(versions_->LastSequence());
  992. }
  993. void DBImpl::ReleaseSnapshot(const Snapshot* s) {
  994. MutexLock l(&mutex_);
  995. snapshots_.Delete(reinterpret_cast<const SnapshotImpl*>(s));
  996. }
  997. // Convenience methods
  998. Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
  999. return DB::Put(o, key, val);
  1000. }
  1001. Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
  1002. return DB::Delete(options, key);
  1003. }
  1004. Status DBImpl::Write(const WriteOptions& options, WriteBatch* my_batch) {
  1005. Writer w(&mutex_);
  1006. w.batch = my_batch;
  1007. w.sync = options.sync;
  1008. w.done = false;
  1009. MutexLock l(&mutex_);
  1010. writers_.push_back(&w);
  1011. while (!w.done && &w != writers_.front()) {
  1012. w.cv.Wait();
  1013. }
  1014. if (w.done) {
  1015. return w.status;
  1016. }
  1017. // May temporarily unlock and wait.
  1018. Status status = MakeRoomForWrite(my_batch == NULL);
  1019. uint64_t last_sequence = versions_->LastSequence();
  1020. Writer* last_writer = &w;
  1021. if (status.ok() && my_batch != NULL) { // NULL batch is for compactions
  1022. WriteBatch* updates = BuildBatchGroup(&last_writer);
  1023. WriteBatchInternal::SetSequence(updates, last_sequence + 1);
  1024. last_sequence += WriteBatchInternal::Count(updates);
  1025. // Add to log and apply to memtable. We can release the lock
  1026. // during this phase since &w is currently responsible for logging
  1027. // and protects against concurrent loggers and concurrent writes
  1028. // into mem_.
  1029. {
  1030. mutex_.Unlock();
  1031. status = log_->AddRecord(WriteBatchInternal::Contents(updates));
  1032. if (status.ok() && options.sync) {
  1033. status = logfile_->Sync();
  1034. }
  1035. if (status.ok()) {
  1036. status = WriteBatchInternal::InsertInto(updates, mem_);
  1037. }
  1038. mutex_.Lock();
  1039. }
  1040. if (updates == tmp_batch_) tmp_batch_->Clear();
  1041. versions_->SetLastSequence(last_sequence);
  1042. }
  1043. while (true) {
  1044. Writer* ready = writers_.front();
  1045. writers_.pop_front();
  1046. if (ready != &w) {
  1047. ready->status = status;
  1048. ready->done = true;
  1049. ready->cv.Signal();
  1050. }
  1051. if (ready == last_writer) break;
  1052. }
  1053. // Notify new head of write queue
  1054. if (!writers_.empty()) {
  1055. writers_.front()->cv.Signal();
  1056. }
  1057. return status;
  1058. }
  1059. // REQUIRES: Writer list must be non-empty
  1060. // REQUIRES: First writer must have a non-NULL batch
  1061. WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) {
  1062. assert(!writers_.empty());
  1063. Writer* first = writers_.front();
  1064. WriteBatch* result = first->batch;
  1065. assert(result != NULL);
  1066. size_t size = WriteBatchInternal::ByteSize(first->batch);
  1067. // Allow the group to grow up to a maximum size, but if the
  1068. // original write is small, limit the growth so we do not slow
  1069. // down the small write too much.
  1070. size_t max_size = 1 << 20;
  1071. if (size <= (128<<10)) {
  1072. max_size = size + (128<<10);
  1073. }
  1074. *last_writer = first;
  1075. std::deque<Writer*>::iterator iter = writers_.begin();
  1076. ++iter; // Advance past "first"
  1077. for (; iter != writers_.end(); ++iter) {
  1078. Writer* w = *iter;
  1079. if (w->sync && !first->sync) {
  1080. // Do not include a sync write into a batch handled by a non-sync write.
  1081. break;
  1082. }
  1083. if (w->batch != NULL) {
  1084. size += WriteBatchInternal::ByteSize(w->batch);
  1085. if (size > max_size) {
  1086. // Do not make batch too big
  1087. break;
  1088. }
  1089. // Append to *reuslt
  1090. if (result == first->batch) {
  1091. // Switch to temporary batch instead of disturbing caller's batch
  1092. result = tmp_batch_;
  1093. assert(WriteBatchInternal::Count(result) == 0);
  1094. WriteBatchInternal::Append(result, first->batch);
  1095. }
  1096. WriteBatchInternal::Append(result, w->batch);
  1097. }
  1098. *last_writer = w;
  1099. }
  1100. return result;
  1101. }
  1102. // REQUIRES: mutex_ is held
  1103. // REQUIRES: this thread is currently at the front of the writer queue
  1104. Status DBImpl::MakeRoomForWrite(bool force) {
  1105. mutex_.AssertHeld();
  1106. assert(!writers_.empty());
  1107. bool allow_delay = !force;
  1108. Status s;
  1109. while (true) {
  1110. if (!bg_error_.ok()) {
  1111. // Yield previous error
  1112. s = bg_error_;
  1113. break;
  1114. } else if (
  1115. allow_delay &&
  1116. versions_->NumLevelFiles(0) >= config::kL0_SlowdownWritesTrigger) {
  1117. // We are getting close to hitting a hard limit on the number of
  1118. // L0 files. Rather than delaying a single write by several
  1119. // seconds when we hit the hard limit, start delaying each
  1120. // individual write by 1ms to reduce latency variance. Also,
  1121. // this delay hands over some CPU to the compaction thread in
  1122. // case it is sharing the same core as the writer.
  1123. mutex_.Unlock();
  1124. env_->SleepForMicroseconds(1000);
  1125. allow_delay = false; // Do not delay a single write more than once
  1126. mutex_.Lock();
  1127. } else if (!force &&
  1128. (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) {
  1129. // There is room in current memtable
  1130. break;
  1131. } else if (imm_ != NULL) {
  1132. // We have filled up the current memtable, but the previous
  1133. // one is still being compacted, so we wait.
  1134. bg_cv_.Wait();
  1135. } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) {
  1136. // There are too many level-0 files.
  1137. Log(options_.info_log, "waiting...\n");
  1138. bg_cv_.Wait();
  1139. } else {
  1140. // Attempt to switch to a new memtable and trigger compaction of old
  1141. assert(versions_->PrevLogNumber() == 0);
  1142. uint64_t new_log_number = versions_->NewFileNumber();
  1143. WritableFile* lfile = NULL;
  1144. s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile);
  1145. if (!s.ok()) {
  1146. // Avoid chewing through file number space in a tight loop.
  1147. versions_->ReuseFileNumber(new_log_number);
  1148. break;
  1149. }
  1150. delete log_;
  1151. delete logfile_;
  1152. logfile_ = lfile;
  1153. logfile_number_ = new_log_number;
  1154. log_ = new log::Writer(lfile);
  1155. imm_ = mem_;
  1156. has_imm_.Release_Store(imm_);
  1157. mem_ = new MemTable(internal_comparator_);
  1158. mem_->Ref();
  1159. force = false; // Do not force another compaction if have room
  1160. MaybeScheduleCompaction();
  1161. }
  1162. }
  1163. return s;
  1164. }
  1165. bool DBImpl::GetProperty(const Slice& property, std::string* value) {
  1166. value->clear();
  1167. MutexLock l(&mutex_);
  1168. Slice in = property;
  1169. Slice prefix("leveldb.");
  1170. if (!in.starts_with(prefix)) return false;
  1171. in.remove_prefix(prefix.size());
  1172. if (in.starts_with("num-files-at-level")) {
  1173. in.remove_prefix(strlen("num-files-at-level"));
  1174. uint64_t level;
  1175. bool ok = ConsumeDecimalNumber(&in, &level) && in.empty();
  1176. if (!ok || level >= config::kNumLevels) {
  1177. return false;
  1178. } else {
  1179. char buf[100];
  1180. snprintf(buf, sizeof(buf), "%d",
  1181. versions_->NumLevelFiles(static_cast<int>(level)));
  1182. *value = buf;
  1183. return true;
  1184. }
  1185. } else if (in == "stats") {
  1186. char buf[200];
  1187. snprintf(buf, sizeof(buf),
  1188. " Compactions\n"
  1189. "Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n"
  1190. "--------------------------------------------------\n"
  1191. );
  1192. value->append(buf);
  1193. for (int level = 0; level < config::kNumLevels; level++) {
  1194. int files = versions_->NumLevelFiles(level);
  1195. if (stats_[level].micros > 0 || files > 0) {
  1196. snprintf(
  1197. buf, sizeof(buf),
  1198. "%3d %8d %8.0f %9.0f %8.0f %9.0f\n",
  1199. level,
  1200. files,
  1201. versions_->NumLevelBytes(level) / 1048576.0,
  1202. stats_[level].micros / 1e6,
  1203. stats_[level].bytes_read / 1048576.0,
  1204. stats_[level].bytes_written / 1048576.0);
  1205. value->append(buf);
  1206. }
  1207. }
  1208. return true;
  1209. } else if (in == "sstables") {
  1210. *value = versions_->current()->DebugString();
  1211. return true;
  1212. }
  1213. return false;
  1214. }
  1215. void DBImpl::GetApproximateSizes(
  1216. const Range* range, int n,
  1217. uint64_t* sizes) {
  1218. // TODO(opt): better implementation
  1219. Version* v;
  1220. {
  1221. MutexLock l(&mutex_);
  1222. versions_->current()->Ref();
  1223. v = versions_->current();
  1224. }
  1225. for (int i = 0; i < n; i++) {
  1226. // Convert user_key into a corresponding internal key.
  1227. InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek);
  1228. InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek);
  1229. uint64_t start = versions_->ApproximateOffsetOf(v, k1);
  1230. uint64_t limit = versions_->ApproximateOffsetOf(v, k2);
  1231. sizes[i] = (limit >= start ? limit - start : 0);
  1232. }
  1233. {
  1234. MutexLock l(&mutex_);
  1235. v->Unref();
  1236. }
  1237. }
  1238. // Default implementations of convenience methods that subclasses of DB
  1239. // can call if they wish
  1240. Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
  1241. WriteBatch batch;
  1242. batch.Put(key, value);
  1243. return Write(opt, &batch);
  1244. }
  1245. Status DB::Delete(const WriteOptions& opt, const Slice& key) {
  1246. WriteBatch batch;
  1247. batch.Delete(key);
  1248. return Write(opt, &batch);
  1249. }
  1250. DB::~DB() { }
  1251. Status DB::Open(const Options& options, const std::string& dbname,
  1252. DB** dbptr) {
  1253. *dbptr = NULL;
  1254. DBImpl* impl = new DBImpl(options, dbname);
  1255. impl->mutex_.Lock();
  1256. VersionEdit edit;
  1257. Status s = impl->Recover(&edit); // Handles create_if_missing, error_if_exists
  1258. if (s.ok()) {
  1259. uint64_t new_log_number = impl->versions_->NewFileNumber();
  1260. WritableFile* lfile;
  1261. s = options.env->NewWritableFile(LogFileName(dbname, new_log_number),
  1262. &lfile);
  1263. if (s.ok()) {
  1264. edit.SetLogNumber(new_log_number);
  1265. impl->logfile_ = lfile;
  1266. impl->logfile_number_ = new_log_number;
  1267. impl->log_ = new log::Writer(lfile);
  1268. s = impl->versions_->LogAndApply(&edit, &impl->mutex_);
  1269. }
  1270. if (s.ok()) {
  1271. impl->DeleteObsoleteFiles();
  1272. impl->MaybeScheduleCompaction();
  1273. }
  1274. }
  1275. impl->mutex_.Unlock();
  1276. if (s.ok()) {
  1277. *dbptr = impl;
  1278. } else {
  1279. delete impl;
  1280. }
  1281. return s;
  1282. }
  1283. Snapshot::~Snapshot() {
  1284. }
  1285. Status DestroyDB(const std::string& dbname, const Options& options) {
  1286. Env* env = options.env;
  1287. std::vector<std::string> filenames;
  1288. // Ignore error in case directory does not exist
  1289. env->GetChildren(dbname, &filenames);
  1290. if (filenames.empty()) {
  1291. return Status::OK();
  1292. }
  1293. FileLock* lock;
  1294. const std::string lockname = LockFileName(dbname);
  1295. Status result = env->LockFile(lockname, &lock);
  1296. if (result.ok()) {
  1297. uint64_t number;
  1298. FileType type;
  1299. for (size_t i = 0; i < filenames.size(); i++) {
  1300. if (ParseFileName(filenames[i], &number, &type) &&
  1301. type != kDBLockFile) { // Lock file will be deleted at end
  1302. Status del = env->DeleteFile(dbname + "/" + filenames[i]);
  1303. if (result.ok() && !del.ok()) {
  1304. result = del;
  1305. }
  1306. }
  1307. }
  1308. env->UnlockFile(lock); // Ignore error since state is already gone
  1309. env->DeleteFile(lockname);
  1310. env->DeleteDir(dbname); // Ignore error in case dir contains other files
  1311. }
  1312. return result;
  1313. }
  1314. } // namespace leveldb