10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
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.

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