小组成员:谢瑞阳、徐翔宇
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.

329 lines
8.7 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/filename.h"
  6. #include "db/db_impl.h"
  7. #include "db/dbformat.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. fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
  21. } else {
  22. 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 {
  41. kForward,
  42. kReverse
  43. };
  44. DBIter(DBImpl* db, const Comparator* cmp, Iterator* iter, SequenceNumber s,
  45. uint32_t seed)
  46. : db_(db),
  47. user_comparator_(cmp),
  48. iter_(iter),
  49. sequence_(s),
  50. direction_(kForward),
  51. valid_(false),
  52. rnd_(seed),
  53. bytes_until_read_sampling_(RandomCompactionPeriod()) {
  54. }
  55. virtual ~DBIter() {
  56. delete iter_;
  57. }
  58. virtual bool Valid() const { return valid_; }
  59. virtual Slice key() const {
  60. assert(valid_);
  61. return (direction_ == kForward) ? ExtractUserKey(iter_->key()) : saved_key_;
  62. }
  63. virtual Slice value() const {
  64. assert(valid_);
  65. return (direction_ == kForward) ? iter_->value() : saved_value_;
  66. }
  67. virtual Status status() const {
  68. if (status_.ok()) {
  69. return iter_->status();
  70. } else {
  71. return status_;
  72. }
  73. }
  74. virtual void Next();
  75. virtual void Prev();
  76. virtual void Seek(const Slice& target);
  77. virtual void SeekToFirst();
  78. virtual void SeekToLast();
  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. // No copying allowed
  110. DBIter(const DBIter&);
  111. void operator=(const DBIter&);
  112. };
  113. inline bool DBIter::ParseKey(ParsedInternalKey* ikey) {
  114. Slice k = iter_->key();
  115. size_t bytes_read = k.size() + iter_->value().size();
  116. while (bytes_until_read_sampling_ < bytes_read) {
  117. bytes_until_read_sampling_ += RandomCompactionPeriod();
  118. db_->RecordReadSample(k);
  119. }
  120. assert(bytes_until_read_sampling_ >= bytes_read);
  121. bytes_until_read_sampling_ -= bytes_read;
  122. if (!ParseInternalKey(k, ikey)) {
  123. status_ = Status::Corruption("corrupted internal key in DBIter");
  124. return false;
  125. } else {
  126. return true;
  127. }
  128. }
  129. void DBIter::Next() {
  130. assert(valid_);
  131. if (direction_ == kReverse) { // Switch directions?
  132. direction_ = kForward;
  133. // iter_ is pointing just before the entries for this->key(),
  134. // so advance into the range of entries for this->key() and then
  135. // use the normal skipping code below.
  136. if (!iter_->Valid()) {
  137. iter_->SeekToFirst();
  138. } else {
  139. iter_->Next();
  140. }
  141. if (!iter_->Valid()) {
  142. valid_ = false;
  143. saved_key_.clear();
  144. return;
  145. }
  146. // saved_key_ already contains the key to skip past.
  147. } else {
  148. // Store in saved_key_ the current key so we skip it below.
  149. SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
  150. // iter_ is pointing to current key. We can now safely move to the next to
  151. // avoid checking current key.
  152. iter_->Next();
  153. if (!iter_->Valid()) {
  154. valid_ = false;
  155. saved_key_.clear();
  156. return;
  157. }
  158. }
  159. FindNextUserEntry(true, &saved_key_);
  160. }
  161. void DBIter::FindNextUserEntry(bool skipping, std::string* skip) {
  162. // Loop until we hit an acceptable entry to yield
  163. assert(iter_->Valid());
  164. assert(direction_ == kForward);
  165. do {
  166. ParsedInternalKey ikey;
  167. if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
  168. switch (ikey.type) {
  169. case kTypeDeletion:
  170. // Arrange to skip all upcoming entries for this key since
  171. // they are hidden by this deletion.
  172. SaveKey(ikey.user_key, skip);
  173. skipping = true;
  174. break;
  175. case kTypeValue:
  176. if (skipping &&
  177. user_comparator_->Compare(ikey.user_key, *skip) <= 0) {
  178. // Entry hidden
  179. } else {
  180. valid_ = true;
  181. saved_key_.clear();
  182. return;
  183. }
  184. break;
  185. }
  186. }
  187. iter_->Next();
  188. } while (iter_->Valid());
  189. saved_key_.clear();
  190. valid_ = false;
  191. }
  192. void DBIter::Prev() {
  193. assert(valid_);
  194. if (direction_ == kForward) { // Switch directions?
  195. // iter_ is pointing at the current entry. Scan backwards until
  196. // the key changes so we can use the normal reverse scanning code.
  197. assert(iter_->Valid()); // Otherwise valid_ would have been false
  198. SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
  199. while (true) {
  200. iter_->Prev();
  201. if (!iter_->Valid()) {
  202. valid_ = false;
  203. saved_key_.clear();
  204. ClearSavedValue();
  205. return;
  206. }
  207. if (user_comparator_->Compare(ExtractUserKey(iter_->key()),
  208. saved_key_) < 0) {
  209. break;
  210. }
  211. }
  212. direction_ = kReverse;
  213. }
  214. FindPrevUserEntry();
  215. }
  216. void DBIter::FindPrevUserEntry() {
  217. assert(direction_ == kReverse);
  218. ValueType value_type = kTypeDeletion;
  219. if (iter_->Valid()) {
  220. do {
  221. ParsedInternalKey ikey;
  222. if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
  223. if ((value_type != kTypeDeletion) &&
  224. user_comparator_->Compare(ikey.user_key, saved_key_) < 0) {
  225. // We encountered a non-deleted value in entries for previous keys,
  226. break;
  227. }
  228. value_type = ikey.type;
  229. if (value_type == kTypeDeletion) {
  230. saved_key_.clear();
  231. ClearSavedValue();
  232. } else {
  233. Slice raw_value = iter_->value();
  234. if (saved_value_.capacity() > raw_value.size() + 1048576) {
  235. std::string empty;
  236. swap(empty, saved_value_);
  237. }
  238. SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
  239. saved_value_.assign(raw_value.data(), raw_value.size());
  240. }
  241. }
  242. iter_->Prev();
  243. } while (iter_->Valid());
  244. }
  245. if (value_type == kTypeDeletion) {
  246. // End
  247. valid_ = false;
  248. saved_key_.clear();
  249. ClearSavedValue();
  250. direction_ = kForward;
  251. } else {
  252. valid_ = true;
  253. }
  254. }
  255. void DBIter::Seek(const Slice& target) {
  256. direction_ = kForward;
  257. ClearSavedValue();
  258. saved_key_.clear();
  259. AppendInternalKey(
  260. &saved_key_, ParsedInternalKey(target, sequence_, kValueTypeForSeek));
  261. iter_->Seek(saved_key_);
  262. if (iter_->Valid()) {
  263. FindNextUserEntry(false, &saved_key_ /* temporary storage */);
  264. } else {
  265. valid_ = false;
  266. }
  267. }
  268. void DBIter::SeekToFirst() {
  269. direction_ = kForward;
  270. ClearSavedValue();
  271. iter_->SeekToFirst();
  272. if (iter_->Valid()) {
  273. FindNextUserEntry(false, &saved_key_ /* temporary storage */);
  274. } else {
  275. valid_ = false;
  276. }
  277. }
  278. void DBIter::SeekToLast() {
  279. direction_ = kReverse;
  280. ClearSavedValue();
  281. iter_->SeekToLast();
  282. FindPrevUserEntry();
  283. }
  284. } // anonymous namespace
  285. Iterator* NewDBIterator(
  286. DBImpl* db,
  287. const Comparator* user_key_comparator,
  288. Iterator* internal_iter,
  289. SequenceNumber sequence,
  290. uint32_t seed) {
  291. return new DBIter(db, user_key_comparator, internal_iter, sequence, seed);
  292. }
  293. } // namespace leveldb