作者: 韩晨旭@ArcueidType(Arcueid) 10225101440 李畅@wesley 10225102463 设计文档为PLAN.md,md版本报告为README.md,pdf版本报告为Report.pdf
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.

322 lines
8.9 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_iter.h"
  5. #include "db/db_impl.h"
  6. #include "db/dbformat.h"
  7. #include "db/filename.h"
  8. #include "leveldb/env.h"
  9. #include "leveldb/iterator.h"
  10. #include "port/port.h"
  11. #include "util/logging.h"
  12. #include "util/mutexlock.h"
  13. #include "util/random.h"
  14. namespace leveldb {
  15. #if 0
  16. static void DumpInternalIter(Iterator* iter) {
  17. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  18. ParsedInternalKey k;
  19. if (!ParseInternalKey(iter->key(), &k)) {
  20. std::fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
  21. } else {
  22. std::fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
  23. }
  24. }
  25. }
  26. #endif
  27. namespace {
  28. // Memtables and sstables that make the DB representation contain
  29. // (userkey,seq,type) => uservalue entries. DBIter
  30. // combines multiple entries for the same userkey found in the DB
  31. // representation into a single entry while accounting for sequence
  32. // numbers, deletion markers, overwrites, etc.
  33. class DBIter : public Iterator {
  34. public:
  35. // Which direction is the iterator currently moving?
  36. // (1) When moving forward, the internal iterator is positioned at
  37. // the exact entry that yields this->key(), this->value()
  38. // (2) When moving backwards, the internal iterator is positioned
  39. // just before all entries whose user key == this->key().
  40. enum Direction { kForward, kReverse };
  41. DBIter(DBImpl* db, const Comparator* cmp, Iterator* iter, SequenceNumber s,
  42. uint32_t seed)
  43. : db_(db),
  44. user_comparator_(cmp),
  45. iter_(iter),
  46. sequence_(s),
  47. direction_(kForward),
  48. valid_(false),
  49. rnd_(seed),
  50. bytes_until_read_sampling_(RandomCompactionPeriod()) {}
  51. DBIter(const DBIter&) = delete;
  52. DBIter& operator=(const DBIter&) = delete;
  53. ~DBIter() override { delete iter_; }
  54. bool Valid() const override { return valid_; }
  55. Slice key() const override {
  56. assert(valid_);
  57. return (direction_ == kForward) ? ExtractUserKey(iter_->key()) : saved_key_;
  58. }
  59. Slice value() const override {
  60. assert(valid_);
  61. return (direction_ == kForward) ? iter_->value() : saved_value_;
  62. }
  63. Fields fields() const override {
  64. assert(valid_);
  65. return (direction_ == kForward) ? Fields(iter_->value()) : Fields(saved_value_);
  66. }
  67. Status status() const override {
  68. if (status_.ok()) {
  69. return iter_->status();
  70. } else {
  71. return status_;
  72. }
  73. }
  74. void Next() override;
  75. void Prev() override;
  76. void Seek(const Slice& target) override;
  77. void SeekToFirst() override;
  78. void SeekToLast() override;
  79. private:
  80. void FindNextUserEntry(bool skipping, std::string* skip);
  81. void FindPrevUserEntry();
  82. bool ParseKey(ParsedInternalKey* key);
  83. inline void SaveKey(const Slice& k, std::string* dst) {
  84. dst->assign(k.data(), k.size());
  85. }
  86. inline void ClearSavedValue() {
  87. if (saved_value_.capacity() > 1048576) {
  88. std::string empty;
  89. swap(empty, saved_value_);
  90. } else {
  91. saved_value_.clear();
  92. }
  93. }
  94. // Picks the number of bytes that can be read until a compaction is scheduled.
  95. size_t RandomCompactionPeriod() {
  96. return rnd_.Uniform(2 * config::kReadBytesPeriod);
  97. }
  98. DBImpl* db_;
  99. const Comparator* const user_comparator_;
  100. Iterator* const iter_;
  101. SequenceNumber const sequence_;
  102. Status status_;
  103. std::string saved_key_; // == current key when direction_==kReverse
  104. std::string saved_value_; // == current raw value when direction_==kReverse
  105. Direction direction_;
  106. bool valid_;
  107. Random rnd_;
  108. size_t bytes_until_read_sampling_;
  109. };
  110. inline bool DBIter::ParseKey(ParsedInternalKey* ikey) {
  111. Slice k = iter_->key();
  112. size_t bytes_read = k.size() + iter_->value().size();
  113. while (bytes_until_read_sampling_ < bytes_read) {
  114. bytes_until_read_sampling_ += RandomCompactionPeriod();
  115. db_->RecordReadSample(k);
  116. }
  117. assert(bytes_until_read_sampling_ >= bytes_read);
  118. bytes_until_read_sampling_ -= bytes_read;
  119. if (!ParseInternalKey(k, ikey)) {
  120. status_ = Status::Corruption("corrupted internal key in DBIter");
  121. return false;
  122. } else {
  123. return true;
  124. }
  125. }
  126. void DBIter::Next() {
  127. assert(valid_);
  128. if (direction_ == kReverse) { // Switch directions?
  129. direction_ = kForward;
  130. // iter_ is pointing just before the entries for this->key(),
  131. // so advance into the range of entries for this->key() and then
  132. // use the normal skipping code below.
  133. if (!iter_->Valid()) {
  134. iter_->SeekToFirst();
  135. } else {
  136. iter_->Next();
  137. }
  138. if (!iter_->Valid()) {
  139. valid_ = false;
  140. saved_key_.clear();
  141. return;
  142. }
  143. // saved_key_ already contains the key to skip past.
  144. } else {
  145. // Store in saved_key_ the current key so we skip it below.
  146. SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
  147. // iter_ is pointing to current key. We can now safely move to the next to
  148. // avoid checking current key.
  149. iter_->Next();
  150. if (!iter_->Valid()) {
  151. valid_ = false;
  152. saved_key_.clear();
  153. return;
  154. }
  155. }
  156. FindNextUserEntry(true, &saved_key_);
  157. }
  158. void DBIter::FindNextUserEntry(bool skipping, std::string* skip) {
  159. // Loop until we hit an acceptable entry to yield
  160. assert(iter_->Valid());
  161. assert(direction_ == kForward);
  162. do {
  163. ParsedInternalKey ikey;
  164. if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
  165. switch (ikey.type) {
  166. case kTypeDeletion:
  167. // Arrange to skip all upcoming entries for this key since
  168. // they are hidden by this deletion.
  169. SaveKey(ikey.user_key, skip);
  170. skipping = true;
  171. break;
  172. case kTypeValue:
  173. if (skipping &&
  174. user_comparator_->Compare(ikey.user_key, *skip) <= 0) {
  175. // Entry hidden
  176. } else {
  177. valid_ = true;
  178. saved_key_.clear();
  179. return;
  180. }
  181. break;
  182. }
  183. }
  184. iter_->Next();
  185. } while (iter_->Valid());
  186. saved_key_.clear();
  187. valid_ = false;
  188. }
  189. void DBIter::Prev() {
  190. assert(valid_);
  191. if (direction_ == kForward) { // Switch directions?
  192. // iter_ is pointing at the current entry. Scan backwards until
  193. // the key changes so we can use the normal reverse scanning code.
  194. assert(iter_->Valid()); // Otherwise valid_ would have been false
  195. SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
  196. while (true) {
  197. iter_->Prev();
  198. if (!iter_->Valid()) {
  199. valid_ = false;
  200. saved_key_.clear();
  201. ClearSavedValue();
  202. return;
  203. }
  204. if (user_comparator_->Compare(ExtractUserKey(iter_->key()), saved_key_) <
  205. 0) {
  206. break;
  207. }
  208. }
  209. direction_ = kReverse;
  210. }
  211. FindPrevUserEntry();
  212. }
  213. void DBIter::FindPrevUserEntry() {
  214. assert(direction_ == kReverse);
  215. ValueType value_type = kTypeDeletion;
  216. if (iter_->Valid()) {
  217. do {
  218. ParsedInternalKey ikey;
  219. if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
  220. if ((value_type != kTypeDeletion) &&
  221. user_comparator_->Compare(ikey.user_key, saved_key_) < 0) {
  222. // We encountered a non-deleted value in entries for previous keys,
  223. break;
  224. }
  225. value_type = ikey.type;
  226. if (value_type == kTypeDeletion) {
  227. saved_key_.clear();
  228. ClearSavedValue();
  229. } else {
  230. Slice raw_value = iter_->value();
  231. if (saved_value_.capacity() > raw_value.size() + 1048576) {
  232. std::string empty;
  233. swap(empty, saved_value_);
  234. }
  235. SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
  236. saved_value_.assign(raw_value.data(), raw_value.size());
  237. }
  238. }
  239. iter_->Prev();
  240. } while (iter_->Valid());
  241. }
  242. if (value_type == kTypeDeletion) {
  243. // End
  244. valid_ = false;
  245. saved_key_.clear();
  246. ClearSavedValue();
  247. direction_ = kForward;
  248. } else {
  249. valid_ = true;
  250. }
  251. }
  252. void DBIter::Seek(const Slice& target) {
  253. direction_ = kForward;
  254. ClearSavedValue();
  255. saved_key_.clear();
  256. AppendInternalKey(&saved_key_,
  257. ParsedInternalKey(target, sequence_, kValueTypeForSeek));
  258. iter_->Seek(saved_key_);
  259. if (iter_->Valid()) {
  260. FindNextUserEntry(false, &saved_key_ /* temporary storage */);
  261. } else {
  262. valid_ = false;
  263. }
  264. }
  265. void DBIter::SeekToFirst() {
  266. direction_ = kForward;
  267. ClearSavedValue();
  268. iter_->SeekToFirst();
  269. if (iter_->Valid()) {
  270. FindNextUserEntry(false, &saved_key_ /* temporary storage */);
  271. } else {
  272. valid_ = false;
  273. }
  274. }
  275. void DBIter::SeekToLast() {
  276. direction_ = kReverse;
  277. ClearSavedValue();
  278. iter_->SeekToLast();
  279. FindPrevUserEntry();
  280. }
  281. } // anonymous namespace
  282. Iterator* NewDBIterator(DBImpl* db, const Comparator* user_key_comparator,
  283. Iterator* internal_iter, SequenceNumber sequence,
  284. uint32_t seed) {
  285. return new DBIter(db, user_key_comparator, internal_iter, sequence, seed);
  286. }
  287. } // namespace leveldb