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

1448 lines
42 KiB

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