LevelDB project 1 10225501460 林子骥 10211900416 郭夏辉
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.

1702 lines
53 KiB

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