LevelDB二级索引实现 姚凯文(kevinyao0901) 姜嘉祺
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.

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