db_iter.cc 17.2 KB
Newer Older
1 2 3 4 5
//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
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"
11
#include <stdexcept>
12
#include <deque>
J
jorlow@chromium.org 已提交
13 14 15

#include "db/filename.h"
#include "db/dbformat.h"
16 17 18 19
#include "rocksdb/env.h"
#include "rocksdb/options.h"
#include "rocksdb/iterator.h"
#include "rocksdb/merge_operator.h"
J
jorlow@chromium.org 已提交
20 21 22
#include "port/port.h"
#include "util/logging.h"
#include "util/mutexlock.h"
23
#include "util/perf_context_imp.h"
J
jorlow@chromium.org 已提交
24

25
namespace rocksdb {
J
jorlow@chromium.org 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

#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

namespace {

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
class IterLookupKey {
 public:
  IterLookupKey() : key_(space_), buf_size_(sizeof(space_)), key_size_(0) {}

  ~IterLookupKey() { Clear(); }

  Slice GetKey() const {
    if (key_ != nullptr) {
      return Slice(key_, key_size_);
    } else {
      return Slice();
    }
  }

  bool Valid() const { return key_ != nullptr; }

  void Clear() {
    if (key_ != nullptr && key_ != space_) {
      delete[] key_;
    }
    key_ = space_;
    buf_size_ = sizeof(buf_size_);
  }

  // Enlarge the buffer size if needed based on key_size.
  // By default, static allocated buffer is used. Once there is a key
  // larger than the static allocated buffer, another buffer is dynamically
  // allocated, until a larger key buffer is requested. In that case, we
  // reallocate buffer and delete the old one.
  void EnlargeBufferIfNeeded(size_t key_size) {
    // If size is smaller than buffer size, continue using current buffer,
    // or the static allocated one, as default
    if (key_size > buf_size_) {
      // Need to enlarge the buffer.
      Clear();
      key_ = new char[key_size];
      buf_size_ = key_size;
    }
    key_size_ = key_size;
  }

  void SetUserKey(const Slice& user_key) {
    size_t size = user_key.size();
    EnlargeBufferIfNeeded(size);
    memcpy(key_, user_key.data(), size);
  }

  void SetInternalKey(const Slice& user_key, SequenceNumber s) {
    size_t usize = user_key.size();
    EnlargeBufferIfNeeded(usize + sizeof(uint64_t));
    memcpy(key_, user_key.data(), usize);
    EncodeFixed64(key_ + usize, PackSequenceAndType(s, kValueTypeForSeek));
  }

 private:
  char* key_;
  size_t buf_size_;
  size_t key_size_;
  char space_[32];  // Avoid allocation for short keys

  // No copying allowed
  IterLookupKey(const IterLookupKey&) = delete;
  void operator=(const LookupKey&) = delete;
};

J
jorlow@chromium.org 已提交
107 108 109 110 111 112 113
// 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.
class DBIter: public Iterator {
 public:
114
  // The following is grossly complicated. TODO: clean it up
J
jorlow@chromium.org 已提交
115 116 117 118 119 120 121 122 123 124
  // 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
  };

125
  DBIter(const std::string* dbname, Env* env, const Options& options,
J
jorlow@chromium.org 已提交
126 127 128
         const Comparator* cmp, Iterator* iter, SequenceNumber s)
      : dbname_(dbname),
        env_(env),
I
Igor Canadi 已提交
129
        logger_(options.info_log.get()),
J
jorlow@chromium.org 已提交
130
        user_comparator_(cmp),
131
        user_merge_operator_(options.merge_operator.get()),
J
jorlow@chromium.org 已提交
132 133
        iter_(iter),
        sequence_(s),
J
jorlow@chromium.org 已提交
134
        direction_(kForward),
135
        valid_(false),
136
        current_entry_is_merged_(false),
137
        statistics_(options.statistics.get()) {
138
    RecordTick(statistics_, NO_ITERATORS, 1);
139
    max_skip_ = options.max_sequential_skip_in_iterations;
J
jorlow@chromium.org 已提交
140 141
  }
  virtual ~DBIter() {
142
    RecordTick(statistics_, NO_ITERATORS, -1);
J
jorlow@chromium.org 已提交
143 144 145 146 147
    delete iter_;
  }
  virtual bool Valid() const { return valid_; }
  virtual Slice key() const {
    assert(valid_);
148
    return saved_key_.GetKey();
J
jorlow@chromium.org 已提交
149 150 151
  }
  virtual Slice value() const {
    assert(valid_);
152 153
    return (direction_ == kForward && !current_entry_is_merged_) ?
      iter_->value() : saved_value_;
J
jorlow@chromium.org 已提交
154 155 156 157 158 159 160 161 162
  }
  virtual Status status() const {
    if (status_.ok()) {
      return iter_->status();
    } else {
      return status_;
    }
  }

J
jorlow@chromium.org 已提交
163 164 165 166 167
  virtual void Next();
  virtual void Prev();
  virtual void Seek(const Slice& target);
  virtual void SeekToFirst();
  virtual void SeekToLast();
J
jorlow@chromium.org 已提交
168

J
jorlow@chromium.org 已提交
169
 private:
170 171
  inline void FindNextUserEntry(bool skipping);
  void FindNextUserEntryInternal(bool skipping);
J
jorlow@chromium.org 已提交
172 173
  void FindPrevUserEntry();
  bool ParseKey(ParsedInternalKey* key);
174
  void MergeValuesNewToOld();
J
jorlow@chromium.org 已提交
175 176 177 178 179 180 181 182 183 184

  inline void ClearSavedValue() {
    if (saved_value_.capacity() > 1048576) {
      std::string empty;
      swap(empty, saved_value_);
    } else {
      saved_value_.clear();
    }
  }

J
jorlow@chromium.org 已提交
185 186
  const std::string* const dbname_;
  Env* const env_;
I
Igor Canadi 已提交
187
  Logger* logger_;
J
jorlow@chromium.org 已提交
188
  const Comparator* const user_comparator_;
189
  const MergeOperator* const user_merge_operator_;
J
jorlow@chromium.org 已提交
190 191
  Iterator* const iter_;
  SequenceNumber const sequence_;
J
jorlow@chromium.org 已提交
192

J
jorlow@chromium.org 已提交
193
  Status status_;
194
  IterLookupKey saved_key_;   // == current key when direction_==kReverse
J
jorlow@chromium.org 已提交
195
  std::string saved_value_;   // == current raw value when direction_==kReverse
196
  std::string skip_key_;
J
jorlow@chromium.org 已提交
197
  Direction direction_;
J
jorlow@chromium.org 已提交
198
  bool valid_;
199
  bool current_entry_is_merged_;
200
  Statistics* statistics_;
201
  uint64_t max_skip_;
J
jorlow@chromium.org 已提交
202 203 204 205 206 207 208 209 210

  // 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");
211 212
    Log(logger_, "corrupted internal key in DBIter: %s",
        iter_->key().ToString(true).c_str());
J
jorlow@chromium.org 已提交
213 214 215 216 217 218
    return false;
  } else {
    return true;
  }
}

J
jorlow@chromium.org 已提交
219 220 221 222 223 224 225 226 227 228 229
void DBIter::Next() {
  assert(valid_);

  if (direction_ == kReverse) {  // Switch directions?
    direction_ = kForward;
    // iter_ is pointing just before the entries for this->key(),
    // so advance into the range of entries for this->key() and then
    // use the normal skipping code below.
    if (!iter_->Valid()) {
      iter_->SeekToFirst();
    } else {
J
jorlow@chromium.org 已提交
230 231
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
232 233
    if (!iter_->Valid()) {
      valid_ = false;
234
      saved_key_.Clear();
J
jorlow@chromium.org 已提交
235
      return;
J
jorlow@chromium.org 已提交
236 237
    }
  }
J
jorlow@chromium.org 已提交
238

239 240 241 242 243 244
  // If the current value is merged, we might already hit end of iter_
  if (!iter_->Valid()) {
    valid_ = false;
    return;
  }
  FindNextUserEntry(true /* skipping the current user key */);
J
jorlow@chromium.org 已提交
245 246
}

247 248 249 250 251 252 253 254 255

// 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
//       a delete marker
256 257 258 259 260 261 262 263 264
inline void DBIter::FindNextUserEntry(bool skipping) {
  StopWatchNano timer(env_, false);
  StartPerfTimer(&timer);
  FindNextUserEntryInternal(skipping);
  BumpPerfTime(&perf_context.find_next_user_entry_time, &timer);
}

// Actual implementation of DBIter::FindNextUserEntry()
void DBIter::FindNextUserEntryInternal(bool skipping) {
J
jorlow@chromium.org 已提交
265 266 267
  // Loop until we hit an acceptable entry to yield
  assert(iter_->Valid());
  assert(direction_ == kForward);
268
  current_entry_is_merged_ = false;
269
  uint64_t num_skipped = 0;
J
jorlow@chromium.org 已提交
270
  do {
J
jorlow@chromium.org 已提交
271
    ParsedInternalKey ikey;
J
jorlow@chromium.org 已提交
272
    if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
273
      if (skipping &&
274
          user_comparator_->Compare(ikey.user_key, saved_key_.GetKey()) <= 0) {
275
        num_skipped++; // skip this entry
276
        BumpPerfCount(&perf_context.internal_key_skipped_count);
277 278 279 280 281 282
      } else {
        skipping = false;
        switch (ikey.type) {
          case kTypeDeletion:
            // Arrange to skip all upcoming entries for this key since
            // they are hidden by this deletion.
283
            saved_key_.SetUserKey(ikey.user_key);
284
            skipping = true;
285
            num_skipped = 0;
286
            BumpPerfCount(&perf_context.internal_delete_skipped_count);
287 288
            break;
          case kTypeValue:
J
jorlow@chromium.org 已提交
289
            valid_ = true;
290
            saved_key_.SetUserKey(ikey.user_key);
J
jorlow@chromium.org 已提交
291
            return;
292 293
          case kTypeMerge:
            // By now, we are sure the current ikey is going to yield a value
294
            saved_key_.SetUserKey(ikey.user_key);
295 296
            current_entry_is_merged_ = true;
            valid_ = true;
D
Deon Nicholas 已提交
297
            MergeValuesNewToOld();  // Go to a different state machine
298
            return;
299
          default:
J
Jim Paton 已提交
300 301
            assert(false);
            break;
302
        }
J
jorlow@chromium.org 已提交
303
      }
J
jorlow@chromium.org 已提交
304
    }
305 306 307 308 309 310 311
    // If we have sequentially iterated via numerous keys and still not
    // found the next user-key, then it is better to seek so that we can
    // avoid too many key comparisons. We seek to the last occurence of
    // our current key by looking for sequence number 0.
    if (skipping && num_skipped > max_skip_) {
      num_skipped = 0;
      std::string last_key;
312 313
      AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetKey(), 0,
                                                     kValueTypeForSeek));
314 315 316 317 318
      iter_->Seek(last_key);
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    } else {
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
319 320
  } while (iter_->Valid());
  valid_ = false;
J
jorlow@chromium.org 已提交
321 322
}

323 324 325 326 327 328 329
// 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() {
D
Deon Nicholas 已提交
330 331 332 333 334
  if (!user_merge_operator_) {
    Log(logger_, "Options::merge_operator is null.");
    throw std::logic_error("DBIter::MergeValuesNewToOld() with"
                           " Options::merge_operator null");
  }
335

336 337 338
  // Start the merge process by pushing the first operand
  std::deque<std::string> operands;
  operands.push_front(iter_->value().ToString());
339

340
  std::string merge_result;   // Temporary string to hold merge result later
341 342 343 344 345 346 347
  ParsedInternalKey ikey;
  for (iter_->Next(); iter_->Valid(); iter_->Next()) {
    if (!ParseKey(&ikey)) {
      // skip corrupted key
      continue;
    }

348
    if (user_comparator_->Compare(ikey.user_key, saved_key_.GetKey()) != 0) {
349 350 351 352 353 354 355 356 357 358 359 360
      // hit the next user key, stop right here
      break;
    }

    if (kTypeDeletion == ikey.type) {
      // hit a delete with the same user key, stop right here
      // iter_ is positioned after delete
      iter_->Next();
      break;
    }

    if (kTypeValue == ikey.type) {
361 362 363
      // 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.
364
      const Slice value = iter_->value();
D
Deon Nicholas 已提交
365
      user_merge_operator_->FullMerge(ikey.user_key, &value, operands,
I
Igor Canadi 已提交
366
                                      &saved_value_, logger_);
367 368 369 370 371 372
      // iter_ is positioned after put
      iter_->Next();
      return;
    }

    if (kTypeMerge == ikey.type) {
373 374 375 376
      // hit a merge, add the value as an operand and run associative merge.
      // when complete, add result to operands and continue.
      const Slice& value = iter_->value();
      operands.push_front(value.ToString());
377 378 379 380 381
    }
  }

  // we either exhausted all internal keys under this user key, or hit
  // a deletion marker.
382
  // feed null as the existing value to the merge operator, such that
383
  // client can differentiate this scenario and do things accordingly.
384
  user_merge_operator_->FullMerge(saved_key_.GetKey(), nullptr, operands,
I
Igor Canadi 已提交
385
                                  &saved_value_, logger_);
386 387
}

J
jorlow@chromium.org 已提交
388 389
void DBIter::Prev() {
  assert(valid_);
J
jorlow@chromium.org 已提交
390

391
  // Throw an exception now if merge_operator is provided
392
  // TODO: support backward iteration
393 394 395 396 397 398
  if (user_merge_operator_) {
    Log(logger_, "Prev not supported yet if merge_operator is provided");
    throw std::logic_error("DBIter::Prev backward iteration not supported"
                           " if merge_operator is provided");
  }

J
jorlow@chromium.org 已提交
399 400 401 402
  if (direction_ == kForward) {  // Switch directions?
    // iter_ is pointing at the current entry.  Scan backwards until
    // the key changes so we can use the normal reverse scanning code.
    assert(iter_->Valid());  // Otherwise valid_ would have been false
403
    saved_key_.SetUserKey(ExtractUserKey(iter_->key()));
J
jorlow@chromium.org 已提交
404 405
    while (true) {
      iter_->Prev();
J
jorlow@chromium.org 已提交
406
      if (!iter_->Valid()) {
J
jorlow@chromium.org 已提交
407
        valid_ = false;
408
        saved_key_.Clear();
J
jorlow@chromium.org 已提交
409
        ClearSavedValue();
J
jorlow@chromium.org 已提交
410 411
        return;
      }
J
jorlow@chromium.org 已提交
412
      if (user_comparator_->Compare(ExtractUserKey(iter_->key()),
413
                                    saved_key_.GetKey()) < 0) {
J
jorlow@chromium.org 已提交
414 415
        break;
      }
J
jorlow@chromium.org 已提交
416
    }
J
jorlow@chromium.org 已提交
417
    direction_ = kReverse;
J
jorlow@chromium.org 已提交
418
  }
J
jorlow@chromium.org 已提交
419 420

  FindPrevUserEntry();
J
jorlow@chromium.org 已提交
421 422
}

J
jorlow@chromium.org 已提交
423 424
void DBIter::FindPrevUserEntry() {
  assert(direction_ == kReverse);
425
  uint64_t num_skipped = 0;
J
jorlow@chromium.org 已提交
426

J
jorlow@chromium.org 已提交
427
  ValueType value_type = kTypeDeletion;
S
sdong 已提交
428
  bool saved_key_valid = true;
J
jorlow@chromium.org 已提交
429 430 431 432 433
  if (iter_->Valid()) {
    do {
      ParsedInternalKey ikey;
      if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
        if ((value_type != kTypeDeletion) &&
434
            user_comparator_->Compare(ikey.user_key, saved_key_.GetKey()) < 0) {
J
jorlow@chromium.org 已提交
435 436 437 438 439
          // We encountered a non-deleted value in entries for previous keys,
          break;
        }
        value_type = ikey.type;
        if (value_type == kTypeDeletion) {
440
          saved_key_.Clear();
J
jorlow@chromium.org 已提交
441
          ClearSavedValue();
S
sdong 已提交
442
          saved_key_valid = false;
J
jorlow@chromium.org 已提交
443 444 445 446 447 448
        } else {
          Slice raw_value = iter_->value();
          if (saved_value_.capacity() > raw_value.size() + 1048576) {
            std::string empty;
            swap(empty, saved_value_);
          }
449
          saved_key_.SetUserKey(ExtractUserKey(iter_->key()));
J
jorlow@chromium.org 已提交
450 451
          saved_value_.assign(raw_value.data(), raw_value.size());
        }
S
sdong 已提交
452 453 454 455
      } else {
        // In the case of ikey.sequence > sequence_, we might have already
        // iterated to a different user key.
        saved_key_valid = false;
J
jorlow@chromium.org 已提交
456
      }
457 458 459 460 461
      num_skipped++;
      // If we have sequentially iterated via numerous keys and still not
      // found the prev user-key, then it is better to seek so that we can
      // avoid too many key comparisons. We seek to the first occurence of
      // our current key by looking for max sequence number.
S
sdong 已提交
462
      if (saved_key_valid && num_skipped > max_skip_) {
463 464
        num_skipped = 0;
        std::string last_key;
465 466 467
        AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetKey(),
                                                       kMaxSequenceNumber,
                                                       kValueTypeForSeek));
468 469 470 471 472
        iter_->Seek(last_key);
        RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
      } else {
        iter_->Prev();
      }
J
jorlow@chromium.org 已提交
473 474
    } while (iter_->Valid());
  }
J
jorlow@chromium.org 已提交
475

J
jorlow@chromium.org 已提交
476 477 478
  if (value_type == kTypeDeletion) {
    // End
    valid_ = false;
479
    saved_key_.Clear();
J
jorlow@chromium.org 已提交
480 481 482 483 484 485
    ClearSavedValue();
    direction_ = kForward;
  } else {
    valid_ = true;
  }
}
J
jorlow@chromium.org 已提交
486

J
jorlow@chromium.org 已提交
487
void DBIter::Seek(const Slice& target) {
488 489 490
  saved_key_.Clear();
  // now savved_key is used to store internal key.
  saved_key_.SetInternalKey(target, sequence_);
491 492
  StopWatchNano internal_seek_timer(env_, false);
  StartPerfTimer(&internal_seek_timer);
493
  iter_->Seek(saved_key_.GetKey());
494
  BumpPerfTime(&perf_context.seek_internal_seek_time, &internal_seek_timer);
J
jorlow@chromium.org 已提交
495
  if (iter_->Valid()) {
496 497
    direction_ = kForward;
    ClearSavedValue();
498
    FindNextUserEntry(false /*not skipping */);
J
jorlow@chromium.org 已提交
499 500 501 502
  } else {
    valid_ = false;
  }
}
J
jorlow@chromium.org 已提交
503

J
jorlow@chromium.org 已提交
504 505 506
void DBIter::SeekToFirst() {
  direction_ = kForward;
  ClearSavedValue();
507 508
  StopWatchNano internal_seek_timer(env_, false);
  StartPerfTimer(&internal_seek_timer);
J
jorlow@chromium.org 已提交
509
  iter_->SeekToFirst();
510
  BumpPerfTime(&perf_context.seek_internal_seek_time, &internal_seek_timer);
J
jorlow@chromium.org 已提交
511
  if (iter_->Valid()) {
512
    FindNextUserEntry(false /* not skipping */);
J
jorlow@chromium.org 已提交
513 514
  } else {
    valid_ = false;
J
jorlow@chromium.org 已提交
515 516 517
  }
}

J
jorlow@chromium.org 已提交
518
void DBIter::SeekToLast() {
519
  // Throw an exception for now if merge_operator is provided
520 521 522 523 524 525 526
  // TODO: support backward iteration
  if (user_merge_operator_) {
    Log(logger_, "SeekToLast not supported yet if merge_operator is provided");
    throw std::logic_error("DBIter::SeekToLast: backward iteration not"
                           " supported if merge_operator is provided");
  }

J
jorlow@chromium.org 已提交
527 528
  direction_ = kReverse;
  ClearSavedValue();
529 530
  StopWatchNano internal_seek_timer(env_, false);
  StartPerfTimer(&internal_seek_timer);
J
jorlow@chromium.org 已提交
531
  iter_->SeekToLast();
532
  BumpPerfTime(&perf_context.seek_internal_seek_time, &internal_seek_timer);
J
jorlow@chromium.org 已提交
533 534 535
  FindPrevUserEntry();
}

J
jorlow@chromium.org 已提交
536 537 538 539 540
}  // anonymous namespace

Iterator* NewDBIterator(
    const std::string* dbname,
    Env* env,
541 542
    const Options& options,
    const Comparator *user_key_comparator,
J
jorlow@chromium.org 已提交
543 544
    Iterator* internal_iter,
    const SequenceNumber& sequence) {
545 546
  return new DBIter(dbname, env, options, user_key_comparator,
                    internal_iter, sequence);
J
jorlow@chromium.org 已提交
547 548
}

549
}  // namespace rocksdb