db_iter.cc 49.9 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
5
//
J
jorlow@chromium.org 已提交
6 7 8 9 10
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/db_iter.h"
S
Stanislau Hlebik 已提交
11
#include <string>
12
#include <iostream>
S
Stanislau Hlebik 已提交
13
#include <limits>
J
jorlow@chromium.org 已提交
14 15

#include "db/dbformat.h"
16
#include "db/merge_context.h"
17
#include "db/merge_helper.h"
18
#include "db/pinned_iterators_manager.h"
19
#include "monitoring/perf_context_imp.h"
20 21 22
#include "rocksdb/env.h"
#include "rocksdb/iterator.h"
#include "rocksdb/merge_operator.h"
23
#include "rocksdb/options.h"
S
sdong 已提交
24
#include "table/internal_iterator.h"
25
#include "util/arena.h"
26
#include "util/filename.h"
J
jorlow@chromium.org 已提交
27 28
#include "util/logging.h"
#include "util/mutexlock.h"
29
#include "util/string_util.h"
J
jorlow@chromium.org 已提交
30

31
namespace rocksdb {
J
jorlow@chromium.org 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

#if 0
static void DumpInternalIter(Iterator* iter) {
  for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
    ParsedInternalKey k;
    if (!ParseInternalKey(iter->key(), &k)) {
      fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
    } else {
      fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
    }
  }
}
#endif

// Memtables and sstables that make the DB representation contain
// (userkey,seq,type) => uservalue entries.  DBIter
// combines multiple entries for the same userkey found in the DB
// representation into a single entry while accounting for sequence
// numbers, deletion markers, overwrites, etc.
S
Siying Dong 已提交
51
class DBIter final: public Iterator {
J
jorlow@chromium.org 已提交
52
 public:
53
  // The following is grossly complicated. TODO: clean it up
J
jorlow@chromium.org 已提交
54 55 56 57 58 59 60 61 62 63
  // Which direction is the iterator currently moving?
  // (1) When moving forward, the internal iterator is positioned at
  //     the exact entry that yields this->key(), this->value()
  // (2) When moving backwards, the internal iterator is positioned
  //     just before all entries whose user key == this->key().
  enum Direction {
    kForward,
    kReverse
  };

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  // LocalStatistics contain Statistics counters that will be aggregated per
  // each iterator instance and then will be sent to the global statistics when
  // the iterator is destroyed.
  //
  // The purpose of this approach is to avoid perf regression happening
  // when multiple threads bump the atomic counters from a DBIter::Next().
  struct LocalStatistics {
    explicit LocalStatistics() { ResetCounters(); }

    void ResetCounters() {
      next_count_ = 0;
      next_found_count_ = 0;
      prev_count_ = 0;
      prev_found_count_ = 0;
      bytes_read_ = 0;
79
      skip_count_ = 0;
80 81 82 83 84 85 86 87
    }

    void BumpGlobalStatistics(Statistics* global_statistics) {
      RecordTick(global_statistics, NUMBER_DB_NEXT, next_count_);
      RecordTick(global_statistics, NUMBER_DB_NEXT_FOUND, next_found_count_);
      RecordTick(global_statistics, NUMBER_DB_PREV, prev_count_);
      RecordTick(global_statistics, NUMBER_DB_PREV_FOUND, prev_found_count_);
      RecordTick(global_statistics, ITER_BYTES_READ, bytes_read_);
88
      RecordTick(global_statistics, NUMBER_ITER_SKIP, skip_count_);
89
      PERF_COUNTER_ADD(iter_read_bytes, bytes_read_);
90 91 92 93 94 95 96 97 98 99 100 101 102
      ResetCounters();
    }

    // Map to Tickers::NUMBER_DB_NEXT
    uint64_t next_count_;
    // Map to Tickers::NUMBER_DB_NEXT_FOUND
    uint64_t next_found_count_;
    // Map to Tickers::NUMBER_DB_PREV
    uint64_t prev_count_;
    // Map to Tickers::NUMBER_DB_PREV_FOUND
    uint64_t prev_found_count_;
    // Map to Tickers::ITER_BYTES_READ
    uint64_t bytes_read_;
103 104
    // Map to Tickers::NUMBER_ITER_SKIP
    uint64_t skip_count_;
105 106
  };

S
Siying Dong 已提交
107
  DBIter(Env* _env, const ReadOptions& read_options,
108
         const ImmutableCFOptions& cf_options, const Comparator* cmp,
S
sdong 已提交
109
         InternalIterator* iter, SequenceNumber s, bool arena_mode,
Y
Yi Wu 已提交
110 111
         uint64_t max_sequential_skip_in_iterations,
         ReadCallback* read_callback, bool allow_blob)
112
      : arena_mode_(arena_mode),
S
Siying Dong 已提交
113
        env_(_env),
114
        logger_(cf_options.info_log),
J
jorlow@chromium.org 已提交
115
        user_comparator_(cmp),
116
        merge_operator_(cf_options.merge_operator),
J
jorlow@chromium.org 已提交
117 118
        iter_(iter),
        sequence_(s),
J
jorlow@chromium.org 已提交
119
        direction_(kForward),
120
        valid_(false),
121
        current_entry_is_merged_(false),
122
        statistics_(cf_options.statistics),
123
        num_internal_keys_skipped_(0),
124
        iterate_lower_bound_(read_options.iterate_lower_bound),
125 126 127 128 129
        iterate_upper_bound_(read_options.iterate_upper_bound),
        prefix_same_as_start_(read_options.prefix_same_as_start),
        pin_thru_lifetime_(read_options.pin_data),
        total_order_seek_(read_options.total_order_seek),
        range_del_agg_(cf_options.internal_comparator, s,
Y
Yi Wu 已提交
130
                       true /* collapse_deletions */),
Y
Yi Wu 已提交
131
        read_callback_(read_callback),
132
        allow_blob_(allow_blob),
133 134
        is_blob_(false),
        start_seqnum_(read_options.iter_start_seqnum) {
L
Lei Jin 已提交
135
    RecordTick(statistics_, NO_ITERATORS);
136
    prefix_extractor_ = cf_options.prefix_extractor;
137
    max_skip_ = max_sequential_skip_in_iterations;
138
    max_skippable_internal_keys_ = read_options.max_skippable_internal_keys;
139 140 141 142 143 144
    if (pin_thru_lifetime_) {
      pinned_iters_mgr_.StartPinning();
    }
    if (iter_) {
      iter_->SetPinnedItersMgr(&pinned_iters_mgr_);
    }
J
jorlow@chromium.org 已提交
145 146
  }
  virtual ~DBIter() {
147
    // Release pinned data if any
148 149 150
    if (pinned_iters_mgr_.PinningEnabled()) {
      pinned_iters_mgr_.ReleasePinnedData();
    }
151 152 153
    // Compiler warning issue filed:
    // https://github.com/facebook/rocksdb/issues/3013
    RecordTick(statistics_, NO_ITERATORS, uint64_t(-1));
154
    ResetInternalKeysSkippedCounter();
155
    local_stats_.BumpGlobalStatistics(statistics_);
156 157 158
    if (!arena_mode_) {
      delete iter_;
    } else {
S
sdong 已提交
159
      iter_->~InternalIterator();
160 161
    }
  }
S
sdong 已提交
162
  virtual void SetIter(InternalIterator* iter) {
163 164
    assert(iter_ == nullptr);
    iter_ = iter;
165
    iter_->SetPinnedItersMgr(&pinned_iters_mgr_);
J
jorlow@chromium.org 已提交
166
  }
A
Andrew Kryczka 已提交
167 168 169 170
  virtual RangeDelAggregator* GetRangeDelAggregator() {
    return &range_del_agg_;
  }

I
Igor Sugak 已提交
171 172
  virtual bool Valid() const override { return valid_; }
  virtual Slice key() const override {
J
jorlow@chromium.org 已提交
173
    assert(valid_);
174 175 176 177 178 179
    if(start_seqnum_ > 0) {
      return saved_key_.GetInternalKey();
    } else {
      return saved_key_.GetUserKey();
    }

J
jorlow@chromium.org 已提交
180
  }
I
Igor Sugak 已提交
181
  virtual Slice value() const override {
J
jorlow@chromium.org 已提交
182
    assert(valid_);
183
    if (current_entry_is_merged_) {
184 185 186
      // If pinned_value_ is set then the result of merge operator is one of
      // the merge operands and we should return it.
      return pinned_value_.data() ? pinned_value_ : saved_value_;
187 188 189 190 191
    } else if (direction_ == kReverse) {
      return pinned_value_;
    } else {
      return iter_->value();
    }
J
jorlow@chromium.org 已提交
192
  }
I
Igor Sugak 已提交
193
  virtual Status status() const override {
J
jorlow@chromium.org 已提交
194 195 196 197 198 199
    if (status_.ok()) {
      return iter_->status();
    } else {
      return status_;
    }
  }
Y
Yi Wu 已提交
200 201 202 203
  bool IsBlob() const {
    assert(valid_ && (allow_blob_ || !is_blob_));
    return is_blob_;
  }
204 205 206 207 208 209

  virtual Status GetProperty(std::string prop_name,
                             std::string* prop) override {
    if (prop == nullptr) {
      return Status::InvalidArgument("prop is nullptr");
    }
210
    if (prop_name == "rocksdb.iterator.super-version-number") {
211
      // First try to pass the value returned from inner iterator.
S
Siying Dong 已提交
212
      return iter_->GetProperty(prop_name, prop);
213
    } else if (prop_name == "rocksdb.iterator.is-key-pinned") {
214
      if (valid_) {
215
        *prop = (pin_thru_lifetime_ && saved_key_.IsKeyPinned()) ? "1" : "0";
216 217 218 219 220 221
      } else {
        *prop = "Iterator is not valid.";
      }
      return Status::OK();
    }
    return Status::InvalidArgument("Undentified property.");
222
  }
J
jorlow@chromium.org 已提交
223

I
Igor Sugak 已提交
224 225 226
  virtual void Next() override;
  virtual void Prev() override;
  virtual void Seek(const Slice& target) override;
A
Aaron Gao 已提交
227
  virtual void SeekForPrev(const Slice& target) override;
I
Igor Sugak 已提交
228 229
  virtual void SeekToFirst() override;
  virtual void SeekToLast() override;
S
Siying Dong 已提交
230 231 232
  Env* env() { return env_; }
  void set_sequence(uint64_t s) { sequence_ = s; }
  void set_valid(bool v) { valid_ = v; }
J
jorlow@chromium.org 已提交
233

J
jorlow@chromium.org 已提交
234
 private:
235
  void ReverseToForward();
236
  void ReverseToBackward();
S
Stanislau Hlebik 已提交
237 238 239 240 241 242
  void PrevInternal();
  void FindParseableKey(ParsedInternalKey* ikey, Direction direction);
  bool FindValueForCurrentKey();
  bool FindValueForCurrentKeyUsingSeek();
  void FindPrevUserKey();
  void FindNextUserKey();
243 244
  inline void FindNextUserEntry(bool skipping, bool prefix_check);
  void FindNextUserEntryInternal(bool skipping, bool prefix_check);
J
jorlow@chromium.org 已提交
245
  bool ParseKey(ParsedInternalKey* key);
246
  void MergeValuesNewToOld();
247
  bool TooManyInternalKeysSkipped(bool increment = true);
Y
Yi Wu 已提交
248
  bool IsVisible(SequenceNumber sequence);
J
jorlow@chromium.org 已提交
249

250 251 252 253 254 255 256 257 258 259
  // Temporarily pin the blocks that we encounter until ReleaseTempPinnedData()
  // is called
  void TempPinData() {
    if (!pin_thru_lifetime_) {
      pinned_iters_mgr_.StartPinning();
    }
  }

  // Release blocks pinned by TempPinData()
  void ReleaseTempPinnedData() {
260 261
    if (!pin_thru_lifetime_ && pinned_iters_mgr_.PinningEnabled()) {
      pinned_iters_mgr_.ReleasePinnedData();
262 263 264
    }
  }

J
jorlow@chromium.org 已提交
265 266 267 268 269 270 271 272 273
  inline void ClearSavedValue() {
    if (saved_value_.capacity() > 1048576) {
      std::string empty;
      swap(empty, saved_value_);
    } else {
      saved_value_.clear();
    }
  }

274
  inline void ResetInternalKeysSkippedCounter() {
275 276 277 278
    local_stats_.skip_count_ += num_internal_keys_skipped_;
    if (valid_) {
      local_stats_.skip_count_--;
    }
279 280 281
    num_internal_keys_skipped_ = 0;
  }

282
  const SliceTransform* prefix_extractor_;
283
  bool arena_mode_;
J
jorlow@chromium.org 已提交
284
  Env* const env_;
I
Igor Canadi 已提交
285
  Logger* logger_;
J
jorlow@chromium.org 已提交
286
  const Comparator* const user_comparator_;
287
  const MergeOperator* const merge_operator_;
S
sdong 已提交
288
  InternalIterator* iter_;
S
Siying Dong 已提交
289
  SequenceNumber sequence_;
J
jorlow@chromium.org 已提交
290

J
jorlow@chromium.org 已提交
291
  Status status_;
S
Stanislau Hlebik 已提交
292
  IterKey saved_key_;
293 294 295 296
  // Reusable internal key data structure. This is only used inside one function
  // and should not be used across functions. Reusing this object can reduce
  // overhead of calling construction of the function if creating it each time.
  ParsedInternalKey ikey_;
S
Stanislau Hlebik 已提交
297
  std::string saved_value_;
298
  Slice pinned_value_;
J
jorlow@chromium.org 已提交
299
  Direction direction_;
J
jorlow@chromium.org 已提交
300
  bool valid_;
301
  bool current_entry_is_merged_;
302
  // for prefix seek mode to support prev()
303
  Statistics* statistics_;
304
  uint64_t max_skip_;
305 306
  uint64_t max_skippable_internal_keys_;
  uint64_t num_internal_keys_skipped_;
307
  const Slice* iterate_lower_bound_;
308
  const Slice* iterate_upper_bound_;
309 310 311
  IterKey prefix_start_buf_;
  Slice prefix_start_key_;
  const bool prefix_same_as_start_;
312 313 314
  // Means that we will pin all data blocks we read as long the Iterator
  // is not deleted, will be true if ReadOptions::pin_data is true
  const bool pin_thru_lifetime_;
315
  const bool total_order_seek_;
316
  // List of operands for merge operator.
317
  MergeContext merge_context_;
A
Andrew Kryczka 已提交
318
  RangeDelAggregator range_del_agg_;
319
  LocalStatistics local_stats_;
320
  PinnedIteratorsManager pinned_iters_mgr_;
Y
Yi Wu 已提交
321
  ReadCallback* read_callback_;
Y
Yi Wu 已提交
322 323
  bool allow_blob_;
  bool is_blob_;
324 325 326
  // for diff snapshots we want the lower bound on the seqnum;
  // if this value > 0 iterator will return internal keys
  SequenceNumber start_seqnum_;
J
jorlow@chromium.org 已提交
327 328 329 330 331 332 333 334 335

  // No copying allowed
  DBIter(const DBIter&);
  void operator=(const DBIter&);
};

inline bool DBIter::ParseKey(ParsedInternalKey* ikey) {
  if (!ParseInternalKey(iter_->key(), ikey)) {
    status_ = Status::Corruption("corrupted internal key in DBIter");
336 337
    ROCKS_LOG_ERROR(logger_, "corrupted internal key in DBIter: %s",
                    iter_->key().ToString(true).c_str());
J
jorlow@chromium.org 已提交
338 339 340 341 342 343
    return false;
  } else {
    return true;
  }
}

J
jorlow@chromium.org 已提交
344 345 346
void DBIter::Next() {
  assert(valid_);

347 348
  // Release temporarily pinned blocks from last operation
  ReleaseTempPinnedData();
349
  ResetInternalKeysSkippedCounter();
S
Stanislau Hlebik 已提交
350
  if (direction_ == kReverse) {
351
    ReverseToForward();
352 353 354 355 356 357 358
  } else if (iter_->Valid() && !current_entry_is_merged_) {
    // If the current value is not a merge, the iter position is the
    // current key, which is already returned. We can safely issue a
    // Next() without checking the current key.
    // If the current key is a merge, very likely iter already points
    // to the next internal position.
    iter_->Next();
359
    PERF_COUNTER_ADD(internal_key_skipped_count, 1);
J
jorlow@chromium.org 已提交
360
  }
J
jorlow@chromium.org 已提交
361

362 363 364
  if (statistics_ != nullptr) {
    local_stats_.next_count_++;
  }
365 366
  // Now we point to the next internal position, for both of merge and
  // not merge cases.
367 368 369 370
  if (!iter_->Valid()) {
    valid_ = false;
    return;
  }
371
  FindNextUserEntry(true /* skipping the current user key */, prefix_same_as_start_);
372 373 374 375
  if (statistics_ != nullptr && valid_) {
    local_stats_.next_found_count_++;
    local_stats_.bytes_read_ += (key().size() + value().size());
  }
J
jorlow@chromium.org 已提交
376 377
}

378 379 380 381 382 383 384
// PRE: saved_key_ has the current user key if skipping
// POST: saved_key_ should have the next user key if valid_,
//       if the current entry is a result of merge
//           current_entry_is_merged_ => true
//           saved_value_             => the merged value
//
// NOTE: In between, saved_key_ can point to a user key that has
385
//       a delete marker or a sequence number higher than sequence_
386
//       saved_key_ MUST have a proper user_key before calling this function
387 388 389 390 391 392
//
// The prefix_check parameter controls whether we check the iterated
// keys against the prefix of the seeked key. Set to false when
// performing a seek without a key (e.g. SeekToFirst). Set to
// prefix_same_as_start_ for other iterations.
inline void DBIter::FindNextUserEntry(bool skipping, bool prefix_check) {
393
  PERF_TIMER_GUARD(find_next_user_entry_time);
394
  FindNextUserEntryInternal(skipping, prefix_check);
395 396 397
}

// Actual implementation of DBIter::FindNextUserEntry()
398
void DBIter::FindNextUserEntryInternal(bool skipping, bool prefix_check) {
J
jorlow@chromium.org 已提交
399 400 401
  // Loop until we hit an acceptable entry to yield
  assert(iter_->Valid());
  assert(direction_ == kForward);
402
  current_entry_is_merged_ = false;
403 404 405 406 407 408 409 410 411 412 413

  // How many times in a row we have skipped an entry with user key less than
  // or equal to saved_key_. We could skip these entries either because
  // sequence numbers were too high or because skipping = true.
  // What saved_key_ contains throughout this method:
  //  - if skipping        : saved_key_ contains the key that we need to skip,
  //                         and we haven't seen any keys greater than that,
  //  - if num_skipped > 0 : saved_key_ contains the key that we have skipped
  //                         num_skipped times, and we haven't seen any keys
  //                         greater than that,
  //  - none of the above  : saved_key_ can contain anything, it doesn't matter.
414
  uint64_t num_skipped = 0;
415

Y
Yi Wu 已提交
416 417
  is_blob_ = false;

J
jorlow@chromium.org 已提交
418
  do {
419
    if (!ParseKey(&ikey_)) {
420 421 422 423
      // Skip corrupted keys.
      iter_->Next();
      continue;
    }
424

425
    if (iterate_upper_bound_ != nullptr &&
426
        user_comparator_->Compare(ikey_.user_key, *iterate_upper_bound_) >= 0) {
427 428
      break;
    }
429

430
    if (prefix_extractor_ && prefix_check &&
431 432
        prefix_extractor_->Transform(ikey_.user_key)
                .compare(prefix_start_key_) != 0) {
433 434 435
      break;
    }

436 437 438 439
    if (TooManyInternalKeysSkipped()) {
      return;
    }

Y
Yi Wu 已提交
440
    if (IsVisible(ikey_.sequence)) {
441 442
      if (skipping && user_comparator_->Compare(ikey_.user_key,
                                                saved_key_.GetUserKey()) <= 0) {
443 444 445 446
        num_skipped++;  // skip this entry
        PERF_COUNTER_ADD(internal_key_skipped_count, 1);
      } else {
        num_skipped = 0;
447
        switch (ikey_.type) {
448 449 450 451
          case kTypeDeletion:
          case kTypeSingleDeletion:
            // Arrange to skip all upcoming entries for this key since
            // they are hidden by this deletion.
452 453 454 455 456 457 458 459 460 461 462
            // if iterartor specified start_seqnum we
            // 1) return internal key, including the type
            // 2) return ikey only if ikey.seqnum >= start_seqnum_
            // not that if deletion seqnum is < start_seqnum_ we
            // just skip it like in normal iterator.
            if (start_seqnum_ > 0 && ikey_.sequence >= start_seqnum_)  {
              saved_key_.SetInternalKey(ikey_);
              valid_=true;
              return;
            } else {
              saved_key_.SetUserKey(
463 464
                ikey_.user_key,
                !pin_thru_lifetime_ || !iter_->IsKeyPinned() /* copy */);
465 466 467
                skipping = true;
                PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
            }
468 469
            break;
          case kTypeValue:
Y
Yi Wu 已提交
470
          case kTypeBlobIndex:
471 472 473 474 475 476 477 478
            if (start_seqnum_ > 0) {
              // we are taking incremental snapshot here
              // incremental snapshots aren't supported on DB with range deletes
              assert(!(
                (ikey_.type == kTypeBlobIndex) && (start_seqnum_ > 0)
              ));
              if (ikey_.sequence >= start_seqnum_) {
                saved_key_.SetInternalKey(ikey_);
Y
Yi Wu 已提交
479
                valid_ = true;
480 481 482 483 484 485 486
                return;
              } else {
                // this key and all previous versions shouldn't be included,
                // skipping
                saved_key_.SetUserKey(ikey_.user_key,
                  !pin_thru_lifetime_ || !iter_->IsKeyPinned() /* copy */);
                skipping = true;
Y
Yi Wu 已提交
487
              }
488
            } else {
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
              saved_key_.SetUserKey(
                  ikey_.user_key,
                  !pin_thru_lifetime_ || !iter_->IsKeyPinned() /* copy */);
              if (range_del_agg_.ShouldDelete(
                      ikey_, RangeDelAggregator::RangePositioningMode::
                                 kForwardTraversal)) {
                // Arrange to skip all upcoming entries for this key since
                // they are hidden by this deletion.
                skipping = true;
                num_skipped = 0;
                PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
              } else if (ikey_.type == kTypeBlobIndex) {
                if (!allow_blob_) {
                  ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
                  status_ = Status::NotSupported(
                      "Encounter unexpected blob index. Please open DB with "
                      "rocksdb::blob_db::BlobDB instead.");
                  valid_ = false;
                } else {
                  is_blob_ = true;
                  valid_ = true;
                }
                return;
              } else {
                valid_ = true;
                return;
              }
516 517 518
            }
            break;
          case kTypeMerge:
519
            saved_key_.SetUserKey(
520 521
                ikey_.user_key,
                !pin_thru_lifetime_ || !iter_->IsKeyPinned() /* copy */);
522
            if (range_del_agg_.ShouldDelete(
523 524
                    ikey_, RangeDelAggregator::RangePositioningMode::
                               kForwardTraversal)) {
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
              // Arrange to skip all upcoming entries for this key since
              // they are hidden by this deletion.
              skipping = true;
              num_skipped = 0;
              PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
            } else {
              // By now, we are sure the current ikey is going to yield a
              // value
              current_entry_is_merged_ = true;
              valid_ = true;
              MergeValuesNewToOld();  // Go to a different state machine
              return;
            }
            break;
          default:
            assert(false);
            break;
542
        }
J
jorlow@chromium.org 已提交
543
      }
544 545 546 547 548 549
    } else {
      // This key was inserted after our snapshot was taken.
      PERF_COUNTER_ADD(internal_recent_skipped_count, 1);

      // Here saved_key_ may contain some old key, or the default empty key, or
      // key assigned by some random other method. We don't care.
550
      if (user_comparator_->Compare(ikey_.user_key, saved_key_.GetUserKey()) <=
551
          0) {
552 553
        num_skipped++;
      } else {
554
        saved_key_.SetUserKey(
555
            ikey_.user_key,
556
            !iter_->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
557 558 559
        skipping = false;
        num_skipped = 0;
      }
J
jorlow@chromium.org 已提交
560
    }
561 562 563 564

    // If we have sequentially iterated via numerous equal keys, then it's
    // better to seek so that we can avoid too many key comparisons.
    if (num_skipped > max_skip_) {
565 566
      num_skipped = 0;
      std::string last_key;
567 568 569 570
      if (skipping) {
        // We're looking for the next user-key but all we see are the same
        // user-key with decreasing sequence numbers. Fast forward to
        // sequence number 0 and type deletion (the smallest type).
571 572
        AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetUserKey(),
                                                       0, kTypeDeletion));
573 574 575 576 577 578 579 580 581
        // Don't set skipping = false because we may still see more user-keys
        // equal to saved_key_.
      } else {
        // We saw multiple entries with this user key and sequence numbers
        // higher than sequence_. Fast forward to sequence_.
        // Note that this only covers a case when a higher key was overwritten
        // many times since our snapshot was taken, not the case when a lot of
        // different keys were inserted after our snapshot was taken.
        AppendInternalKey(&last_key,
582
                          ParsedInternalKey(saved_key_.GetUserKey(), sequence_,
583 584
                                            kValueTypeForSeek));
      }
585 586 587 588 589
      iter_->Seek(last_key);
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    } else {
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
590 591
  } while (iter_->Valid());
  valid_ = false;
J
jorlow@chromium.org 已提交
592 593
}

594 595 596 597 598 599 600
// Merge values of the same user key starting from the current iter_ position
// Scan from the newer entries to older entries.
// PRE: iter_->key() points to the first merge type entry
//      saved_key_ stores the user key
// POST: saved_value_ has the merged value for the user key
//       iter_ points to the next entry (or invalid)
void DBIter::MergeValuesNewToOld() {
601
  if (!merge_operator_) {
602
    ROCKS_LOG_ERROR(logger_, "Options::merge_operator is null.");
603
    status_ = Status::InvalidArgument("merge_operator_ must be set.");
604 605
    valid_ = false;
    return;
D
Deon Nicholas 已提交
606
  }
607

608 609
  // Temporarily pin the blocks that hold merge operands
  TempPinData();
610
  merge_context_.Clear();
611
  // Start the merge process by pushing the first operand
612 613
  merge_context_.PushOperand(iter_->value(),
                             iter_->IsValuePinned() /* operand_pinned */);
614
  TEST_SYNC_POINT("DBIter::MergeValuesNewToOld:PushedFirstOperand");
615 616

  ParsedInternalKey ikey;
617
  Status s;
618
  for (iter_->Next(); iter_->Valid(); iter_->Next()) {
619
    TEST_SYNC_POINT("DBIter::MergeValuesNewToOld:SteppedToNextOperand");
620 621 622 623 624
    if (!ParseKey(&ikey)) {
      // skip corrupted key
      continue;
    }

625
    if (!user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
626 627
      // hit the next user key, stop right here
      break;
A
Andrew Kryczka 已提交
628
    } else if (kTypeDeletion == ikey.type || kTypeSingleDeletion == ikey.type ||
629 630 631
               range_del_agg_.ShouldDelete(
                   ikey, RangeDelAggregator::RangePositioningMode::
                             kForwardTraversal)) {
632 633 634 635
      // hit a delete with the same user key, stop right here
      // iter_ is positioned after delete
      iter_->Next();
      break;
A
Andres Noetzli 已提交
636
    } else if (kTypeValue == ikey.type) {
637 638 639
      // hit a put, merge the put value with operands and store the
      // final result in saved_value_. We are done!
      // ignore corruption if there is any.
I
Igor Canadi 已提交
640
      const Slice val = iter_->value();
641 642
      s = MergeHelper::TimedFullMerge(
          merge_operator_, ikey.user_key, &val, merge_context_.GetOperands(),
643
          &saved_value_, logger_, statistics_, env_, &pinned_value_, true);
644
      if (!s.ok()) {
Y
Yi Wu 已提交
645
        valid_ = false;
646 647
        status_ = s;
      }
648 649 650
      // iter_ is positioned after put
      iter_->Next();
      return;
A
Andres Noetzli 已提交
651
    } else if (kTypeMerge == ikey.type) {
652 653
      // hit a merge, add the value as an operand and run associative merge.
      // when complete, add result to operands and continue.
654 655
      merge_context_.PushOperand(iter_->value(),
                                 iter_->IsValuePinned() /* operand_pinned */);
656
      PERF_COUNTER_ADD(internal_merge_count, 1);
Y
Yi Wu 已提交
657 658 659 660 661 662 663 664 665 666 667 668
    } else if (kTypeBlobIndex == ikey.type) {
      if (!allow_blob_) {
        ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
        status_ = Status::NotSupported(
            "Encounter unexpected blob index. Please open DB with "
            "rocksdb::blob_db::BlobDB instead.");
      } else {
        status_ =
            Status::NotSupported("Blob DB does not support merge operator.");
      }
      valid_ = false;
      return;
A
Andres Noetzli 已提交
669 670
    } else {
      assert(false);
671 672 673
    }
  }

674 675 676 677
  // we either exhausted all internal keys under this user key, or hit
  // a deletion marker.
  // feed null as the existing value to the merge operator, such that
  // client can differentiate this scenario and do things accordingly.
678 679 680
  s = MergeHelper::TimedFullMerge(merge_operator_, saved_key_.GetUserKey(),
                                  nullptr, merge_context_.GetOperands(),
                                  &saved_value_, logger_, statistics_, env_,
681
                                  &pinned_value_, true);
682
  if (!s.ok()) {
Y
Yi Wu 已提交
683
    valid_ = false;
684 685
    status_ = s;
  }
686 687
}

J
jorlow@chromium.org 已提交
688 689
void DBIter::Prev() {
  assert(valid_);
690
  ReleaseTempPinnedData();
691
  ResetInternalKeysSkippedCounter();
S
Stanislau Hlebik 已提交
692
  if (direction_ == kForward) {
693
    ReverseToBackward();
S
Stanislau Hlebik 已提交
694 695
  }
  PrevInternal();
M
Manuel Ung 已提交
696
  if (statistics_ != nullptr) {
697
    local_stats_.prev_count_++;
M
Manuel Ung 已提交
698
    if (valid_) {
699 700
      local_stats_.prev_found_count_++;
      local_stats_.bytes_read_ += (key().size() + value().size());
M
Manuel Ung 已提交
701 702
    }
  }
S
Stanislau Hlebik 已提交
703
}
J
jorlow@chromium.org 已提交
704

705 706 707 708
void DBIter::ReverseToForward() {
  if (prefix_extractor_ != nullptr && !total_order_seek_) {
    IterKey last_key;
    last_key.SetInternalKey(ParsedInternalKey(
709 710
        saved_key_.GetUserKey(), kMaxSequenceNumber, kValueTypeForSeek));
    iter_->Seek(last_key.GetInternalKey());
711 712 713 714 715
  }
  FindNextUserKey();
  direction_ = kForward;
  if (!iter_->Valid()) {
    iter_->SeekToFirst();
716
    range_del_agg_.InvalidateTombstoneMapPositions();
717 718 719
  }
}

720
void DBIter::ReverseToBackward() {
721 722
  if (prefix_extractor_ != nullptr && !total_order_seek_) {
    IterKey last_key;
723 724 725
    last_key.SetInternalKey(ParsedInternalKey(saved_key_.GetUserKey(), 0,
                                              kValueTypeForSeekForPrev));
    iter_->SeekForPrev(last_key.GetInternalKey());
726
  }
727 728 729 730 731
  if (current_entry_is_merged_) {
    // Not placed in the same key. Need to call Prev() until finding the
    // previous key.
    if (!iter_->Valid()) {
      iter_->SeekToLast();
732
      range_del_agg_.InvalidateTombstoneMapPositions();
733 734 735 736
    }
    ParsedInternalKey ikey;
    FindParseableKey(&ikey, kReverse);
    while (iter_->Valid() &&
737 738
           user_comparator_->Compare(ikey.user_key, saved_key_.GetUserKey()) >
               0) {
S
Siying Dong 已提交
739
      assert(ikey.sequence != kMaxSequenceNumber);
Y
Yi Wu 已提交
740
      if (!IsVisible(ikey.sequence)) {
741 742 743 744
        PERF_COUNTER_ADD(internal_recent_skipped_count, 1);
      } else {
        PERF_COUNTER_ADD(internal_key_skipped_count, 1);
      }
745 746 747 748 749 750 751 752
      iter_->Prev();
      FindParseableKey(&ikey, kReverse);
    }
  }
#ifndef NDEBUG
  if (iter_->Valid()) {
    ParsedInternalKey ikey;
    assert(ParseKey(&ikey));
753 754
    assert(user_comparator_->Compare(ikey.user_key, saved_key_.GetUserKey()) <=
           0);
755 756 757 758 759 760 761
  }
#endif

  FindPrevUserKey();
  direction_ = kReverse;
}

S
Stanislau Hlebik 已提交
762 763 764 765
void DBIter::PrevInternal() {
  if (!iter_->Valid()) {
    valid_ = false;
    return;
766 767
  }

S
Stanislau Hlebik 已提交
768 769 770
  ParsedInternalKey ikey;

  while (iter_->Valid()) {
771 772 773
    saved_key_.SetUserKey(
        ExtractUserKey(iter_->key()),
        !iter_->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
774

775 776 777 778 779 780 781 782
    if (prefix_extractor_ && prefix_same_as_start_ &&
        prefix_extractor_->Transform(saved_key_.GetUserKey())
                .compare(prefix_start_key_) != 0) {
      // Current key does not have the same prefix as start
      valid_ = false;
      return;
    }

783 784 785 786 787 788 789 790
    if (iterate_lower_bound_ != nullptr &&
        user_comparator_->Compare(saved_key_.GetUserKey(),
                                  *iterate_lower_bound_) < 0) {
      // We've iterated earlier than the user-specified lower bound.
      valid_ = false;
      return;
    }

S
Stanislau Hlebik 已提交
791
    if (FindValueForCurrentKey()) {
J
jorlow@chromium.org 已提交
792 793 794
      if (!iter_->Valid()) {
        return;
      }
S
Stanislau Hlebik 已提交
795
      FindParseableKey(&ikey, kReverse);
796
      if (user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
S
Stanislau Hlebik 已提交
797
        FindPrevUserKey();
J
jorlow@chromium.org 已提交
798
      }
S
Stanislau Hlebik 已提交
799
      return;
J
jorlow@chromium.org 已提交
800
    }
801 802 803 804 805

    if (TooManyInternalKeysSkipped(false)) {
      return;
    }

S
Stanislau Hlebik 已提交
806 807 808 809
    if (!iter_->Valid()) {
      break;
    }
    FindParseableKey(&ikey, kReverse);
810
    if (user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
S
Stanislau Hlebik 已提交
811 812 813 814
      FindPrevUserKey();
    }
  }
  // We haven't found any key - iterator is not valid
A
Aaron Gao 已提交
815
  // Or the prefix is different than start prefix
816
  assert(!iter_->Valid());
S
Stanislau Hlebik 已提交
817
  valid_ = false;
J
jorlow@chromium.org 已提交
818 819
}

S
Stanislau Hlebik 已提交
820
// This function checks, if the entry with biggest sequence_number <= sequence_
A
Andres Noetzli 已提交
821 822
// is non kTypeDeletion or kTypeSingleDeletion. If it's not, we save value in
// saved_value_
S
Stanislau Hlebik 已提交
823 824
bool DBIter::FindValueForCurrentKey() {
  assert(iter_->Valid());
825
  merge_context_.Clear();
826
  current_entry_is_merged_ = false;
A
Andres Noetzli 已提交
827 828
  // last entry before merge (could be kTypeDeletion, kTypeSingleDeletion or
  // kTypeValue)
S
Stanislau Hlebik 已提交
829 830
  ValueType last_not_merge_type = kTypeDeletion;
  ValueType last_key_entry_type = kTypeDeletion;
J
jorlow@chromium.org 已提交
831

S
Stanislau Hlebik 已提交
832 833 834
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kReverse);

835 836 837
  // Temporarily pin blocks that hold (merge operands / the value)
  ReleaseTempPinnedData();
  TempPinData();
S
Stanislau Hlebik 已提交
838
  size_t num_skipped = 0;
Y
Yi Wu 已提交
839
  while (iter_->Valid() && IsVisible(ikey.sequence) &&
840
         user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
841 842 843 844
    if (TooManyInternalKeysSkipped()) {
      return false;
    }

S
Stanislau Hlebik 已提交
845 846 847 848 849 850 851 852
    // We iterate too much: let's use Seek() to avoid too much key comparisons
    if (num_skipped >= max_skip_) {
      return FindValueForCurrentKeyUsingSeek();
    }

    last_key_entry_type = ikey.type;
    switch (last_key_entry_type) {
      case kTypeValue:
Y
Yi Wu 已提交
853
      case kTypeBlobIndex:
854 855 856
        if (range_del_agg_.ShouldDelete(
                ikey,
                RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
A
Andrew Kryczka 已提交
857 858 859 860 861 862
          last_key_entry_type = kTypeRangeDeletion;
          PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
        } else {
          assert(iter_->IsValuePinned());
          pinned_value_ = iter_->value();
        }
863
        merge_context_.Clear();
A
Andrew Kryczka 已提交
864
        last_not_merge_type = last_key_entry_type;
S
Stanislau Hlebik 已提交
865 866
        break;
      case kTypeDeletion:
A
Andres Noetzli 已提交
867
      case kTypeSingleDeletion:
868
        merge_context_.Clear();
A
Andres Noetzli 已提交
869
        last_not_merge_type = last_key_entry_type;
870
        PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
S
Stanislau Hlebik 已提交
871 872
        break;
      case kTypeMerge:
873 874 875
        if (range_del_agg_.ShouldDelete(
                ikey,
                RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
A
Andrew Kryczka 已提交
876 877 878 879 880 881 882 883
          merge_context_.Clear();
          last_key_entry_type = kTypeRangeDeletion;
          last_not_merge_type = last_key_entry_type;
          PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
        } else {
          assert(merge_operator_ != nullptr);
          merge_context_.PushOperandBack(
              iter_->value(), iter_->IsValuePinned() /* operand_pinned */);
884
          PERF_COUNTER_ADD(internal_merge_count, 1);
A
Andrew Kryczka 已提交
885
        }
S
Stanislau Hlebik 已提交
886 887 888 889 890
        break;
      default:
        assert(false);
    }

891
    PERF_COUNTER_ADD(internal_key_skipped_count, 1);
892
    assert(user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey()));
S
Stanislau Hlebik 已提交
893 894 895 896 897
    iter_->Prev();
    ++num_skipped;
    FindParseableKey(&ikey, kReverse);
  }

898
  Status s;
Y
Yi Wu 已提交
899
  is_blob_ = false;
S
Stanislau Hlebik 已提交
900 901
  switch (last_key_entry_type) {
    case kTypeDeletion:
A
Andres Noetzli 已提交
902
    case kTypeSingleDeletion:
A
Andrew Kryczka 已提交
903
    case kTypeRangeDeletion:
S
Stanislau Hlebik 已提交
904 905 906
      valid_ = false;
      return false;
    case kTypeMerge:
907
      current_entry_is_merged_ = true;
A
Aaron Gao 已提交
908
      if (last_not_merge_type == kTypeDeletion ||
A
Andrew Kryczka 已提交
909 910
          last_not_merge_type == kTypeSingleDeletion ||
          last_not_merge_type == kTypeRangeDeletion) {
911 912 913
        s = MergeHelper::TimedFullMerge(
            merge_operator_, saved_key_.GetUserKey(), nullptr,
            merge_context_.GetOperands(), &saved_value_, logger_, statistics_,
914
            env_, &pinned_value_, true);
Y
Yi Wu 已提交
915 916 917 918 919 920 921 922 923 924 925 926
      } else if (last_not_merge_type == kTypeBlobIndex) {
        if (!allow_blob_) {
          ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
          status_ = Status::NotSupported(
              "Encounter unexpected blob index. Please open DB with "
              "rocksdb::blob_db::BlobDB instead.");
        } else {
          status_ =
              Status::NotSupported("Blob DB does not support merge operator.");
        }
        valid_ = false;
        return true;
927
      } else {
S
Stanislau Hlebik 已提交
928
        assert(last_not_merge_type == kTypeValue);
929
        s = MergeHelper::TimedFullMerge(
930
            merge_operator_, saved_key_.GetUserKey(), &pinned_value_,
931
            merge_context_.GetOperands(), &saved_value_, logger_, statistics_,
932
            env_, &pinned_value_, true);
933
      }
S
Stanislau Hlebik 已提交
934 935 936 937
      break;
    case kTypeValue:
      // do nothing - we've already has value in saved_value_
      break;
Y
Yi Wu 已提交
938 939 940 941 942 943 944 945 946 947 948
    case kTypeBlobIndex:
      if (!allow_blob_) {
        ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
        status_ = Status::NotSupported(
            "Encounter unexpected blob index. Please open DB with "
            "rocksdb::blob_db::BlobDB instead.");
        valid_ = false;
        return true;
      }
      is_blob_ = true;
      break;
S
Stanislau Hlebik 已提交
949 950 951
    default:
      assert(false);
      break;
J
jorlow@chromium.org 已提交
952
  }
Y
Yi Wu 已提交
953 954 955 956
  if (s.ok()) {
    valid_ = true;
  } else {
    valid_ = false;
957 958
    status_ = s;
  }
S
Stanislau Hlebik 已提交
959 960
  return true;
}
J
jorlow@chromium.org 已提交
961

S
Stanislau Hlebik 已提交
962 963 964
// This function is used in FindValueForCurrentKey.
// We use Seek() function instead of Prev() to find necessary value
bool DBIter::FindValueForCurrentKeyUsingSeek() {
965 966 967
  // FindValueForCurrentKey will enable pinning before calling
  // FindValueForCurrentKeyUsingSeek()
  assert(pinned_iters_mgr_.PinningEnabled());
S
Stanislau Hlebik 已提交
968
  std::string last_key;
969 970
  AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetUserKey(),
                                                 sequence_, kValueTypeForSeek));
S
Stanislau Hlebik 已提交
971 972 973 974 975 976
  iter_->Seek(last_key);
  RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);

  // assume there is at least one parseable key for this user key
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kForward);
977 978 979 980 981 982 983 984 985 986 987
  assert(iter_->Valid());
  assert(user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey()));

  // In case read_callback presents, the value we seek to may not be visible.
  // Seek for the next value that's visible.
  while (!IsVisible(ikey.sequence)) {
    iter_->Next();
    FindParseableKey(&ikey, kForward);
    assert(iter_->Valid());
    assert(user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey()));
  }
S
Stanislau Hlebik 已提交
988

A
Andrew Kryczka 已提交
989
  if (ikey.type == kTypeDeletion || ikey.type == kTypeSingleDeletion ||
990 991
      range_del_agg_.ShouldDelete(
          ikey, RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
J
jorlow@chromium.org 已提交
992
    valid_ = false;
S
Stanislau Hlebik 已提交
993 994
    return false;
  }
Y
Yi Wu 已提交
995 996 997 998 999 1000 1001 1002 1003
  if (ikey.type == kTypeBlobIndex && !allow_blob_) {
    ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
    status_ = Status::NotSupported(
        "Encounter unexpected blob index. Please open DB with "
        "rocksdb::blob_db::BlobDB instead.");
    valid_ = false;
    return true;
  }
  if (ikey.type == kTypeValue || ikey.type == kTypeBlobIndex) {
A
Andrew Kryczka 已提交
1004 1005 1006 1007 1008
    assert(iter_->IsValuePinned());
    pinned_value_ = iter_->value();
    valid_ = true;
    return true;
  }
S
Stanislau Hlebik 已提交
1009 1010 1011

  // kTypeMerge. We need to collect all kTypeMerge values and save them
  // in operands
1012
  current_entry_is_merged_ = true;
1013
  merge_context_.Clear();
1014 1015
  while (
      iter_->Valid() &&
1016
      user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey()) &&
1017 1018 1019
      ikey.type == kTypeMerge &&
      !range_del_agg_.ShouldDelete(
          ikey, RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
1020 1021
    merge_context_.PushOperand(iter_->value(),
                               iter_->IsValuePinned() /* operand_pinned */);
1022
    PERF_COUNTER_ADD(internal_merge_count, 1);
S
Stanislau Hlebik 已提交
1023 1024 1025 1026
    iter_->Next();
    FindParseableKey(&ikey, kForward);
  }

1027
  Status s;
S
Stanislau Hlebik 已提交
1028
  if (!iter_->Valid() ||
1029
      !user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey()) ||
A
Andrew Kryczka 已提交
1030
      ikey.type == kTypeDeletion || ikey.type == kTypeSingleDeletion ||
1031 1032
      range_del_agg_.ShouldDelete(
          ikey, RangeDelAggregator::RangePositioningMode::kBackwardTraversal)) {
1033
    s = MergeHelper::TimedFullMerge(merge_operator_, saved_key_.GetUserKey(),
1034 1035
                                    nullptr, merge_context_.GetOperands(),
                                    &saved_value_, logger_, statistics_, env_,
1036
                                    &pinned_value_, true);
S
Stanislau Hlebik 已提交
1037 1038
    // Make iter_ valid and point to saved_key_
    if (!iter_->Valid() ||
1039
        !user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
S
Stanislau Hlebik 已提交
1040 1041 1042
      iter_->Seek(last_key);
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    }
Y
Yi Wu 已提交
1043 1044 1045 1046
    if (s.ok()) {
      valid_ = true;
    } else {
      valid_ = false;
1047 1048
      status_ = s;
    }
S
Stanislau Hlebik 已提交
1049 1050 1051
    return true;
  }

I
Igor Canadi 已提交
1052
  const Slice& val = iter_->value();
1053 1054 1055
  s = MergeHelper::TimedFullMerge(merge_operator_, saved_key_.GetUserKey(),
                                  &val, merge_context_.GetOperands(),
                                  &saved_value_, logger_, statistics_, env_,
1056
                                  &pinned_value_, true);
Y
Yi Wu 已提交
1057 1058 1059 1060
  if (s.ok()) {
    valid_ = true;
  } else {
    valid_ = false;
1061 1062
    status_ = s;
  }
S
Stanislau Hlebik 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
  return true;
}

// Used in Next to change directions
// Go to next user key
// Don't use Seek(),
// because next user key will be very close
void DBIter::FindNextUserKey() {
  if (!iter_->Valid()) {
    return;
  }
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kForward);
  while (iter_->Valid() &&
1077
         !user_comparator_->Equal(ikey.user_key, saved_key_.GetUserKey())) {
S
Stanislau Hlebik 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    iter_->Next();
    FindParseableKey(&ikey, kForward);
  }
}

// Go to previous user_key
void DBIter::FindPrevUserKey() {
  if (!iter_->Valid()) {
    return;
  }
  size_t num_skipped = 0;
  ParsedInternalKey ikey;
  FindParseableKey(&ikey, kReverse);
1091
  int cmp;
1092 1093 1094
  while (iter_->Valid() &&
         ((cmp = user_comparator_->Compare(ikey.user_key,
                                           saved_key_.GetUserKey())) == 0 ||
Y
Yi Wu 已提交
1095
          (cmp > 0 && !IsVisible(ikey.sequence)))) {
1096 1097 1098 1099
    if (TooManyInternalKeysSkipped()) {
      return;
    }

1100 1101 1102 1103 1104
    if (cmp == 0) {
      if (num_skipped >= max_skip_) {
        num_skipped = 0;
        IterKey last_key;
        last_key.SetInternalKey(ParsedInternalKey(
1105 1106
            saved_key_.GetUserKey(), kMaxSequenceNumber, kValueTypeForSeek));
        iter_->Seek(last_key.GetInternalKey());
1107 1108 1109 1110
        RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
      } else {
        ++num_skipped;
      }
S
Stanislau Hlebik 已提交
1111
    }
S
Siying Dong 已提交
1112
    assert(ikey.sequence != kMaxSequenceNumber);
Y
Yi Wu 已提交
1113
    if (!IsVisible(ikey.sequence)) {
1114 1115 1116 1117
      PERF_COUNTER_ADD(internal_recent_skipped_count, 1);
    } else {
      PERF_COUNTER_ADD(internal_key_skipped_count, 1);
    }
S
Stanislau Hlebik 已提交
1118 1119 1120 1121 1122
    iter_->Prev();
    FindParseableKey(&ikey, kReverse);
  }
}

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
bool DBIter::TooManyInternalKeysSkipped(bool increment) {
  if ((max_skippable_internal_keys_ > 0) &&
      (num_internal_keys_skipped_ > max_skippable_internal_keys_)) {
    valid_ = false;
    status_ = Status::Incomplete("Too many internal keys skipped.");
    return true;
  } else if (increment) {
    num_internal_keys_skipped_++;
  }
  return false;
}

Y
Yi Wu 已提交
1135 1136 1137 1138 1139
bool DBIter::IsVisible(SequenceNumber sequence) {
  return sequence <= sequence_ &&
         (read_callback_ == nullptr || read_callback_->IsCommitted(sequence));
}

S
Stanislau Hlebik 已提交
1140 1141 1142 1143 1144 1145 1146 1147
// Skip all unparseable keys
void DBIter::FindParseableKey(ParsedInternalKey* ikey, Direction direction) {
  while (iter_->Valid() && !ParseKey(ikey)) {
    if (direction == kReverse) {
      iter_->Prev();
    } else {
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
1148 1149
  }
}
J
jorlow@chromium.org 已提交
1150

J
jorlow@chromium.org 已提交
1151
void DBIter::Seek(const Slice& target) {
L
Lei Jin 已提交
1152
  StopWatch sw(env_, statistics_, DB_SEEK);
1153
  ReleaseTempPinnedData();
1154
  ResetInternalKeysSkippedCounter();
1155 1156
  saved_key_.Clear();
  saved_key_.SetInternalKey(target, sequence_);
1157

Z
zhangjinpeng1987 已提交
1158 1159 1160 1161 1162 1163 1164
  if (iterate_lower_bound_ != nullptr &&
      user_comparator_->Compare(saved_key_.GetUserKey(),
                                *iterate_lower_bound_) < 0) {
    saved_key_.Clear();
    saved_key_.SetInternalKey(*iterate_lower_bound_, sequence_);
  }

1165 1166
  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
1167
    iter_->Seek(saved_key_.GetInternalKey());
1168
    range_del_agg_.InvalidateTombstoneMapPositions();
1169
  }
M
Manuel Ung 已提交
1170
  RecordTick(statistics_, NUMBER_DB_SEEK);
J
jorlow@chromium.org 已提交
1171
  if (iter_->Valid()) {
1172 1173 1174
    if (prefix_extractor_ && prefix_same_as_start_) {
      prefix_start_key_ = prefix_extractor_->Transform(target);
    }
1175 1176
    direction_ = kForward;
    ClearSavedValue();
1177 1178 1179 1180
    FindNextUserEntry(false /* not skipping */, prefix_same_as_start_);
    if (!valid_) {
      prefix_start_key_.clear();
    }
M
Manuel Ung 已提交
1181 1182
    if (statistics_ != nullptr) {
      if (valid_) {
1183
        // Decrement since we don't want to count this key as skipped
M
Manuel Ung 已提交
1184 1185
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1186
        PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
M
Manuel Ung 已提交
1187 1188
      }
    }
J
jorlow@chromium.org 已提交
1189 1190 1191
  } else {
    valid_ = false;
  }
1192

1193
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
1194 1195
    prefix_start_buf_.SetUserKey(prefix_start_key_);
    prefix_start_key_ = prefix_start_buf_.GetUserKey();
1196
  }
J
jorlow@chromium.org 已提交
1197
}
J
jorlow@chromium.org 已提交
1198

A
Aaron Gao 已提交
1199 1200 1201
void DBIter::SeekForPrev(const Slice& target) {
  StopWatch sw(env_, statistics_, DB_SEEK);
  ReleaseTempPinnedData();
1202
  ResetInternalKeysSkippedCounter();
A
Aaron Gao 已提交
1203 1204 1205 1206 1207
  saved_key_.Clear();
  // now saved_key is used to store internal key.
  saved_key_.SetInternalKey(target, 0 /* sequence_number */,
                            kValueTypeForSeekForPrev);

Z
zhangjinpeng1987 已提交
1208 1209 1210 1211 1212 1213 1214
  if (iterate_upper_bound_ != nullptr &&
      user_comparator_->Compare(saved_key_.GetUserKey(),
                                *iterate_upper_bound_) >= 0) {
    saved_key_.Clear();
    saved_key_.SetInternalKey(*iterate_upper_bound_, kMaxSequenceNumber);
  }

A
Aaron Gao 已提交
1215 1216
  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
1217
    iter_->SeekForPrev(saved_key_.GetInternalKey());
1218
    range_del_agg_.InvalidateTombstoneMapPositions();
A
Aaron Gao 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
  }

  RecordTick(statistics_, NUMBER_DB_SEEK);
  if (iter_->Valid()) {
    if (prefix_extractor_ && prefix_same_as_start_) {
      prefix_start_key_ = prefix_extractor_->Transform(target);
    }
    direction_ = kReverse;
    ClearSavedValue();
    PrevInternal();
    if (!valid_) {
      prefix_start_key_.clear();
    }
    if (statistics_ != nullptr) {
      if (valid_) {
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1236
        PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
A
Aaron Gao 已提交
1237 1238 1239 1240 1241 1242
      }
    }
  } else {
    valid_ = false;
  }
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
1243 1244
    prefix_start_buf_.SetUserKey(prefix_start_key_);
    prefix_start_key_ = prefix_start_buf_.GetUserKey();
A
Aaron Gao 已提交
1245 1246 1247
  }
}

J
jorlow@chromium.org 已提交
1248
void DBIter::SeekToFirst() {
S
Stanislau Hlebik 已提交
1249
  // Don't use iter_::Seek() if we set a prefix extractor
1250
  // because prefix seek will be used.
1251
  if (prefix_extractor_ != nullptr) {
S
Stanislau Hlebik 已提交
1252 1253
    max_skip_ = std::numeric_limits<uint64_t>::max();
  }
1254 1255 1256 1257
  if (iterate_lower_bound_ != nullptr) {
    Seek(*iterate_lower_bound_);
    return;
  }
J
jorlow@chromium.org 已提交
1258
  direction_ = kForward;
1259
  ReleaseTempPinnedData();
1260
  ResetInternalKeysSkippedCounter();
J
jorlow@chromium.org 已提交
1261
  ClearSavedValue();
1262 1263 1264 1265

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
    iter_->SeekToFirst();
1266
    range_del_agg_.InvalidateTombstoneMapPositions();
1267 1268
  }

M
Manuel Ung 已提交
1269
  RecordTick(statistics_, NUMBER_DB_SEEK);
J
jorlow@chromium.org 已提交
1270
  if (iter_->Valid()) {
1271 1272 1273
    saved_key_.SetUserKey(
        ExtractUserKey(iter_->key()),
        !iter_->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
1274
    FindNextUserEntry(false /* not skipping */, false /* no prefix check */);
M
Manuel Ung 已提交
1275 1276 1277 1278
    if (statistics_ != nullptr) {
      if (valid_) {
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1279
        PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
M
Manuel Ung 已提交
1280 1281
      }
    }
J
jorlow@chromium.org 已提交
1282 1283
  } else {
    valid_ = false;
J
jorlow@chromium.org 已提交
1284
  }
1285
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
1286 1287 1288
    prefix_start_buf_.SetUserKey(
        prefix_extractor_->Transform(saved_key_.GetUserKey()));
    prefix_start_key_ = prefix_start_buf_.GetUserKey();
1289
  }
J
jorlow@chromium.org 已提交
1290 1291
}

J
jorlow@chromium.org 已提交
1292
void DBIter::SeekToLast() {
S
Stanislau Hlebik 已提交
1293
  // Don't use iter_::Seek() if we set a prefix extractor
1294
  // because prefix seek will be used.
1295
  if (prefix_extractor_ != nullptr) {
S
Stanislau Hlebik 已提交
1296 1297
    max_skip_ = std::numeric_limits<uint64_t>::max();
  }
J
jorlow@chromium.org 已提交
1298
  direction_ = kReverse;
1299
  ReleaseTempPinnedData();
1300
  ResetInternalKeysSkippedCounter();
J
jorlow@chromium.org 已提交
1301
  ClearSavedValue();
1302 1303 1304 1305

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
    iter_->SeekToLast();
1306
    range_del_agg_.InvalidateTombstoneMapPositions();
1307
  }
1308 1309 1310 1311
  // When the iterate_upper_bound is set to a value,
  // it will seek to the last key before the
  // ReadOptions.iterate_upper_bound
  if (iter_->Valid() && iterate_upper_bound_ != nullptr) {
1312
    SeekForPrev(*iterate_upper_bound_);
1313
    range_del_agg_.InvalidateTombstoneMapPositions();
1314 1315 1316
    if (!Valid()) {
      return;
    } else if (user_comparator_->Equal(*iterate_upper_bound_, key())) {
1317 1318
      ReleaseTempPinnedData();
      PrevInternal();
1319
    }
1320 1321
  } else {
    PrevInternal();
1322
  }
M
Manuel Ung 已提交
1323 1324 1325 1326 1327
  if (statistics_ != nullptr) {
    RecordTick(statistics_, NUMBER_DB_SEEK);
    if (valid_) {
      RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
      RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1328
      PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
M
Manuel Ung 已提交
1329 1330
    }
  }
1331
  if (valid_ && prefix_extractor_ && prefix_same_as_start_) {
1332 1333 1334
    prefix_start_buf_.SetUserKey(
        prefix_extractor_->Transform(saved_key_.GetUserKey()));
    prefix_start_key_ = prefix_start_buf_.GetUserKey();
1335
  }
J
jorlow@chromium.org 已提交
1336 1337
}

1338 1339 1340 1341 1342
Iterator* NewDBIterator(Env* env, const ReadOptions& read_options,
                        const ImmutableCFOptions& cf_options,
                        const Comparator* user_key_comparator,
                        InternalIterator* internal_iter,
                        const SequenceNumber& sequence,
Y
Yi Wu 已提交
1343
                        uint64_t max_sequential_skip_in_iterations,
Y
Yi Wu 已提交
1344 1345 1346 1347 1348
                        ReadCallback* read_callback, bool allow_blob) {
  DBIter* db_iter =
      new DBIter(env, read_options, cf_options, user_key_comparator,
                 internal_iter, sequence, false,
                 max_sequential_skip_in_iterations, read_callback, allow_blob);
1349
  return db_iter;
1350 1351
}

I
Igor Canadi 已提交
1352
ArenaWrappedDBIter::~ArenaWrappedDBIter() { db_iter_->~DBIter(); }
1353

A
Andrew Kryczka 已提交
1354 1355 1356 1357
RangeDelAggregator* ArenaWrappedDBIter::GetRangeDelAggregator() {
  return db_iter_->GetRangeDelAggregator();
}

S
sdong 已提交
1358
void ArenaWrappedDBIter::SetIterUnderDBIter(InternalIterator* iter) {
1359 1360 1361 1362 1363 1364 1365 1366 1367
  static_cast<DBIter*>(db_iter_)->SetIter(iter);
}

inline bool ArenaWrappedDBIter::Valid() const { return db_iter_->Valid(); }
inline void ArenaWrappedDBIter::SeekToFirst() { db_iter_->SeekToFirst(); }
inline void ArenaWrappedDBIter::SeekToLast() { db_iter_->SeekToLast(); }
inline void ArenaWrappedDBIter::Seek(const Slice& target) {
  db_iter_->Seek(target);
}
A
Aaron Gao 已提交
1368 1369 1370
inline void ArenaWrappedDBIter::SeekForPrev(const Slice& target) {
  db_iter_->SeekForPrev(target);
}
1371 1372 1373 1374 1375
inline void ArenaWrappedDBIter::Next() { db_iter_->Next(); }
inline void ArenaWrappedDBIter::Prev() { db_iter_->Prev(); }
inline Slice ArenaWrappedDBIter::key() const { return db_iter_->key(); }
inline Slice ArenaWrappedDBIter::value() const { return db_iter_->value(); }
inline Status ArenaWrappedDBIter::status() const { return db_iter_->status(); }
Y
Yi Wu 已提交
1376
bool ArenaWrappedDBIter::IsBlob() const { return db_iter_->IsBlob(); }
1377 1378
inline Status ArenaWrappedDBIter::GetProperty(std::string prop_name,
                                              std::string* prop) {
S
Siying Dong 已提交
1379 1380 1381 1382 1383 1384 1385
  if (prop_name == "rocksdb.iterator.super-version-number") {
    // First try to pass the value returned from inner iterator.
    if (!db_iter_->GetProperty(prop_name, prop).ok()) {
      *prop = ToString(sv_number_);
    }
    return Status::OK();
  }
1386 1387
  return db_iter_->GetProperty(prop_name, prop);
}
S
Siying Dong 已提交
1388 1389 1390 1391 1392

void ArenaWrappedDBIter::Init(Env* env, const ReadOptions& read_options,
                              const ImmutableCFOptions& cf_options,
                              const SequenceNumber& sequence,
                              uint64_t max_sequential_skip_in_iteration,
Y
Yi Wu 已提交
1393
                              uint64_t version_number,
1394 1395
                              ReadCallback* read_callback, bool allow_blob,
                              bool allow_refresh) {
S
Siying Dong 已提交
1396 1397 1398
  auto mem = arena_.AllocateAligned(sizeof(DBIter));
  db_iter_ = new (mem)
      DBIter(env, read_options, cf_options, cf_options.user_comparator, nullptr,
Y
Yi Wu 已提交
1399 1400
             sequence, true, max_sequential_skip_in_iteration, read_callback,
             allow_blob);
S
Siying Dong 已提交
1401
  sv_number_ = version_number;
1402
  allow_refresh_ = allow_refresh;
S
Siying Dong 已提交
1403 1404 1405
}

Status ArenaWrappedDBIter::Refresh() {
1406
  if (cfd_ == nullptr || db_impl_ == nullptr || !allow_refresh_) {
S
Siying Dong 已提交
1407 1408 1409
    return Status::NotSupported("Creating renew iterator is not allowed.");
  }
  assert(db_iter_ != nullptr);
1410 1411 1412
  // TODO(yiwu): For last_seq_same_as_publish_seq_==false, this is not the
  // correct behavior. Will be corrected automatically when we take a snapshot
  // here for the case of WritePreparedTxnDB.
S
Siying Dong 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  SequenceNumber latest_seq = db_impl_->GetLatestSequenceNumber();
  uint64_t cur_sv_number = cfd_->GetSuperVersionNumber();
  if (sv_number_ != cur_sv_number) {
    Env* env = db_iter_->env();
    db_iter_->~DBIter();
    arena_.~Arena();
    new (&arena_) Arena();

    SuperVersion* sv = cfd_->GetReferencedSuperVersion(db_impl_->mutex());
    Init(env, read_options_, *(cfd_->ioptions()), latest_seq,
         sv->mutable_cf_options.max_sequential_skip_in_iterations,
1424
         cur_sv_number, read_callback_, allow_blob_, allow_refresh_);
S
Siying Dong 已提交
1425 1426 1427 1428 1429 1430 1431 1432 1433

    InternalIterator* internal_iter = db_impl_->NewInternalIterator(
        read_options_, cfd_, sv, &arena_, db_iter_->GetRangeDelAggregator());
    SetIterUnderDBIter(internal_iter);
  } else {
    db_iter_->set_sequence(latest_seq);
    db_iter_->set_valid(false);
  }
  return Status::OK();
1434
}
J
jorlow@chromium.org 已提交
1435

1436
ArenaWrappedDBIter* NewArenaWrappedDbIterator(
1437
    Env* env, const ReadOptions& read_options,
S
Siying Dong 已提交
1438 1439
    const ImmutableCFOptions& cf_options, const SequenceNumber& sequence,
    uint64_t max_sequential_skip_in_iterations, uint64_t version_number,
Y
Yi Wu 已提交
1440
    ReadCallback* read_callback, DBImpl* db_impl, ColumnFamilyData* cfd,
1441
    bool allow_blob, bool allow_refresh) {
1442
  ArenaWrappedDBIter* iter = new ArenaWrappedDBIter();
S
Siying Dong 已提交
1443
  iter->Init(env, read_options, cf_options, sequence,
Y
Yi Wu 已提交
1444
             max_sequential_skip_in_iterations, version_number, read_callback,
1445 1446
             allow_blob, allow_refresh);
  if (db_impl != nullptr && cfd != nullptr && allow_refresh) {
Y
Yi Wu 已提交
1447 1448
    iter->StoreRefreshInfo(read_options, db_impl, cfd, read_callback,
                           allow_blob);
S
Siying Dong 已提交
1449
  }
1450

1451
  return iter;
J
jorlow@chromium.org 已提交
1452 1453
}

1454
}  // namespace rocksdb