提供基本的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.

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