小组成员:谢瑞阳、徐翔宇
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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