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.

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