db_iter.cc 14.6 KB
Newer Older
J
jorlow@chromium.org 已提交
1 2 3 4 5
// 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"
6
#include <stdexcept>
7
#include <deque>
J
jorlow@chromium.org 已提交
8 9 10

#include "db/filename.h"
#include "db/dbformat.h"
11 12 13 14
#include "rocksdb/env.h"
#include "rocksdb/options.h"
#include "rocksdb/iterator.h"
#include "rocksdb/merge_operator.h"
J
jorlow@chromium.org 已提交
15 16 17
#include "port/port.h"
#include "util/logging.h"
#include "util/mutexlock.h"
18
#include "util/perf_context_imp.h"
J
jorlow@chromium.org 已提交
19

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

#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 {

// 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:
44
  // The following is grossly complicated. TODO: clean it up
J
jorlow@chromium.org 已提交
45 46 47 48 49 50 51 52 53 54
  // 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
  };

55
  DBIter(const std::string* dbname, Env* env, const Options& options,
J
jorlow@chromium.org 已提交
56 57 58
         const Comparator* cmp, Iterator* iter, SequenceNumber s)
      : dbname_(dbname),
        env_(env),
59
        logger_(options.info_log),
J
jorlow@chromium.org 已提交
60
        user_comparator_(cmp),
61
        user_merge_operator_(options.merge_operator.get()),
J
jorlow@chromium.org 已提交
62 63
        iter_(iter),
        sequence_(s),
J
jorlow@chromium.org 已提交
64
        direction_(kForward),
65
        valid_(false),
66 67 68
        current_entry_is_merged_(false),
        statistics_(options.statistics) {
    RecordTick(statistics_, NO_ITERATORS, 1);
69
    max_skip_ = options.max_sequential_skip_in_iterations;
J
jorlow@chromium.org 已提交
70 71
  }
  virtual ~DBIter() {
72
    RecordTick(statistics_, NO_ITERATORS, -1);
J
jorlow@chromium.org 已提交
73 74 75 76 77
    delete iter_;
  }
  virtual bool Valid() const { return valid_; }
  virtual Slice key() const {
    assert(valid_);
78
    return saved_key_;
J
jorlow@chromium.org 已提交
79 80 81
  }
  virtual Slice value() const {
    assert(valid_);
82 83
    return (direction_ == kForward && !current_entry_is_merged_) ?
      iter_->value() : saved_value_;
J
jorlow@chromium.org 已提交
84 85 86 87 88 89 90 91 92
  }
  virtual Status status() const {
    if (status_.ok()) {
      return iter_->status();
    } else {
      return status_;
    }
  }

J
jorlow@chromium.org 已提交
93 94 95 96 97
  virtual void Next();
  virtual void Prev();
  virtual void Seek(const Slice& target);
  virtual void SeekToFirst();
  virtual void SeekToLast();
J
jorlow@chromium.org 已提交
98

J
jorlow@chromium.org 已提交
99
 private:
100
  void FindNextUserEntry(bool skipping);
J
jorlow@chromium.org 已提交
101 102
  void FindPrevUserEntry();
  bool ParseKey(ParsedInternalKey* key);
103
  void MergeValuesNewToOld();
J
jorlow@chromium.org 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117

  inline void SaveKey(const Slice& k, std::string* dst) {
    dst->assign(k.data(), k.size());
  }

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

J
jorlow@chromium.org 已提交
118 119
  const std::string* const dbname_;
  Env* const env_;
120
  shared_ptr<Logger> logger_;
J
jorlow@chromium.org 已提交
121
  const Comparator* const user_comparator_;
122
  const MergeOperator* const user_merge_operator_;
J
jorlow@chromium.org 已提交
123 124
  Iterator* const iter_;
  SequenceNumber const sequence_;
J
jorlow@chromium.org 已提交
125

J
jorlow@chromium.org 已提交
126
  Status status_;
J
jorlow@chromium.org 已提交
127 128
  std::string saved_key_;     // == current key when direction_==kReverse
  std::string saved_value_;   // == current raw value when direction_==kReverse
129
  std::string skip_key_;
J
jorlow@chromium.org 已提交
130
  Direction direction_;
J
jorlow@chromium.org 已提交
131
  bool valid_;
132
  bool current_entry_is_merged_;
133
  std::shared_ptr<Statistics> statistics_;
134
  uint64_t max_skip_;
J
jorlow@chromium.org 已提交
135 136 137 138 139 140 141 142 143

  // 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");
144 145
    Log(logger_, "corrupted internal key in DBIter: %s",
        iter_->key().ToString(true).c_str());
J
jorlow@chromium.org 已提交
146 147 148 149 150 151
    return false;
  } else {
    return true;
  }
}

J
jorlow@chromium.org 已提交
152 153 154 155 156 157 158 159 160 161 162
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 已提交
163 164
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
165 166 167 168
    if (!iter_->Valid()) {
      valid_ = false;
      saved_key_.clear();
      return;
J
jorlow@chromium.org 已提交
169 170
    }
  }
J
jorlow@chromium.org 已提交
171

172 173 174 175 176 177
  // 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 已提交
178 179
}

180 181 182 183 184 185 186 187 188 189

// 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
void DBIter::FindNextUserEntry(bool skipping) {
J
jorlow@chromium.org 已提交
190 191 192
  // Loop until we hit an acceptable entry to yield
  assert(iter_->Valid());
  assert(direction_ == kForward);
193
  current_entry_is_merged_ = false;
194
  uint64_t num_skipped = 0;
J
jorlow@chromium.org 已提交
195
  do {
J
jorlow@chromium.org 已提交
196
    ParsedInternalKey ikey;
J
jorlow@chromium.org 已提交
197
    if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
198 199
      if (skipping &&
          user_comparator_->Compare(ikey.user_key, saved_key_) <= 0) {
200
        num_skipped++; // skip this entry
201
        BumpPerfCount(&perf_context.internal_key_skipped_count);
202 203 204 205 206 207 208 209
      } else {
        skipping = false;
        switch (ikey.type) {
          case kTypeDeletion:
            // Arrange to skip all upcoming entries for this key since
            // they are hidden by this deletion.
            SaveKey(ikey.user_key, &saved_key_);
            skipping = true;
210
            num_skipped = 0;
211
            BumpPerfCount(&perf_context.internal_delete_skipped_count);
212 213
            break;
          case kTypeValue:
J
jorlow@chromium.org 已提交
214
            valid_ = true;
215
            SaveKey(ikey.user_key, &saved_key_);
J
jorlow@chromium.org 已提交
216
            return;
217 218 219 220 221
          case kTypeMerge:
            // By now, we are sure the current ikey is going to yield a value
            SaveKey(ikey.user_key, &saved_key_);
            current_entry_is_merged_ = true;
            valid_ = true;
D
Deon Nicholas 已提交
222
            MergeValuesNewToOld();  // Go to a different state machine
223
            return;
J
Jim Paton 已提交
224 225 226
          case kTypeLogData:
            assert(false);
            break;
227
        }
J
jorlow@chromium.org 已提交
228
      }
J
jorlow@chromium.org 已提交
229
    }
230 231 232 233 234 235 236 237 238 239 240 241 242 243
    // 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;
      AppendInternalKey(&last_key,
        ParsedInternalKey(Slice(saved_key_), 0, kValueTypeForSeek));
      iter_->Seek(last_key);
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    } else {
      iter_->Next();
    }
J
jorlow@chromium.org 已提交
244 245
  } while (iter_->Valid());
  valid_ = false;
J
jorlow@chromium.org 已提交
246 247
}

248 249 250 251 252 253 254
// 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 已提交
255 256 257 258 259
  if (!user_merge_operator_) {
    Log(logger_, "Options::merge_operator is null.");
    throw std::logic_error("DBIter::MergeValuesNewToOld() with"
                           " Options::merge_operator null");
  }
260

261 262 263
  // Start the merge process by pushing the first operand
  std::deque<std::string> operands;
  operands.push_front(iter_->value().ToString());
264

265
  std::string merge_result;   // Temporary string to hold merge result later
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
  ParsedInternalKey ikey;
  for (iter_->Next(); iter_->Valid(); iter_->Next()) {
    if (!ParseKey(&ikey)) {
      // skip corrupted key
      continue;
    }

    if (user_comparator_->Compare(ikey.user_key, saved_key_) != 0) {
      // 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) {
286 287 288
      // 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.
289
      const Slice value = iter_->value();
D
Deon Nicholas 已提交
290 291
      user_merge_operator_->FullMerge(ikey.user_key, &value, operands,
                                      &saved_value_, logger_.get());
292 293 294 295 296 297
      // iter_ is positioned after put
      iter_->Next();
      return;
    }

    if (kTypeMerge == ikey.type) {
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
      // 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());
      while(operands.size() >= 2) {
        // Call user associative-merge until it returns false
        if (user_merge_operator_->PartialMerge(ikey.user_key,
                                               Slice(operands[0]),
                                               Slice(operands[1]),
                                               &merge_result,
                                               logger_.get())) {
          operands.pop_front();
          swap(operands.front(), merge_result);
        } else {
          // Associative merge returns false ==> stack the operands
          break;
        }
      }

317 318 319 320 321
    }
  }

  // we either exhausted all internal keys under this user key, or hit
  // a deletion marker.
322
  // feed null as the existing value to the merge operator, such that
323
  // client can differentiate this scenario and do things accordingly.
D
Deon Nicholas 已提交
324 325
  user_merge_operator_->FullMerge(saved_key_, nullptr, operands,
                                  &saved_value_, logger_.get());
326 327
}

J
jorlow@chromium.org 已提交
328 329
void DBIter::Prev() {
  assert(valid_);
J
jorlow@chromium.org 已提交
330

331
  // Throw an exception now if merge_operator is provided
332
  // TODO: support backward iteration
333 334 335 336 337 338
  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 已提交
339 340 341 342 343 344 345
  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
    SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
    while (true) {
      iter_->Prev();
J
jorlow@chromium.org 已提交
346
      if (!iter_->Valid()) {
J
jorlow@chromium.org 已提交
347 348 349
        valid_ = false;
        saved_key_.clear();
        ClearSavedValue();
J
jorlow@chromium.org 已提交
350 351
        return;
      }
J
jorlow@chromium.org 已提交
352 353 354 355
      if (user_comparator_->Compare(ExtractUserKey(iter_->key()),
                                    saved_key_) < 0) {
        break;
      }
J
jorlow@chromium.org 已提交
356
    }
J
jorlow@chromium.org 已提交
357
    direction_ = kReverse;
J
jorlow@chromium.org 已提交
358
  }
J
jorlow@chromium.org 已提交
359 360

  FindPrevUserEntry();
J
jorlow@chromium.org 已提交
361 362
}

J
jorlow@chromium.org 已提交
363 364
void DBIter::FindPrevUserEntry() {
  assert(direction_ == kReverse);
365
  uint64_t num_skipped = 0;
J
jorlow@chromium.org 已提交
366

J
jorlow@chromium.org 已提交
367 368 369 370 371 372 373 374 375 376 377 378
  ValueType value_type = kTypeDeletion;
  if (iter_->Valid()) {
    do {
      ParsedInternalKey ikey;
      if (ParseKey(&ikey) && ikey.sequence <= sequence_) {
        if ((value_type != kTypeDeletion) &&
            user_comparator_->Compare(ikey.user_key, saved_key_) < 0) {
          // We encountered a non-deleted value in entries for previous keys,
          break;
        }
        value_type = ikey.type;
        if (value_type == kTypeDeletion) {
379
          saved_key_.clear();
J
jorlow@chromium.org 已提交
380 381 382 383 384 385 386
          ClearSavedValue();
        } else {
          Slice raw_value = iter_->value();
          if (saved_value_.capacity() > raw_value.size() + 1048576) {
            std::string empty;
            swap(empty, saved_value_);
          }
387
          SaveKey(ExtractUserKey(iter_->key()), &saved_key_);
J
jorlow@chromium.org 已提交
388 389 390
          saved_value_.assign(raw_value.data(), raw_value.size());
        }
      }
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
      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.
      if (num_skipped > max_skip_) {
        num_skipped = 0;
        std::string last_key;
        AppendInternalKey(&last_key,
          ParsedInternalKey(Slice(saved_key_), kMaxSequenceNumber,
                            kValueTypeForSeek));
        iter_->Seek(last_key);
        RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
      } else {
        iter_->Prev();
      }
J
jorlow@chromium.org 已提交
407 408
    } while (iter_->Valid());
  }
J
jorlow@chromium.org 已提交
409

J
jorlow@chromium.org 已提交
410 411 412 413 414 415 416 417 418 419
  if (value_type == kTypeDeletion) {
    // End
    valid_ = false;
    saved_key_.clear();
    ClearSavedValue();
    direction_ = kForward;
  } else {
    valid_ = true;
  }
}
J
jorlow@chromium.org 已提交
420

J
jorlow@chromium.org 已提交
421 422 423 424 425 426 427 428
void DBIter::Seek(const Slice& target) {
  direction_ = kForward;
  ClearSavedValue();
  saved_key_.clear();
  AppendInternalKey(
      &saved_key_, ParsedInternalKey(target, sequence_, kValueTypeForSeek));
  iter_->Seek(saved_key_);
  if (iter_->Valid()) {
429
    FindNextUserEntry(false /*not skipping */);
J
jorlow@chromium.org 已提交
430 431 432 433
  } else {
    valid_ = false;
  }
}
J
jorlow@chromium.org 已提交
434

J
jorlow@chromium.org 已提交
435 436 437 438 439
void DBIter::SeekToFirst() {
  direction_ = kForward;
  ClearSavedValue();
  iter_->SeekToFirst();
  if (iter_->Valid()) {
440
    FindNextUserEntry(false /* not skipping */);
J
jorlow@chromium.org 已提交
441 442
  } else {
    valid_ = false;
J
jorlow@chromium.org 已提交
443 444 445
  }
}

J
jorlow@chromium.org 已提交
446
void DBIter::SeekToLast() {
447
  // Throw an exception for now if merge_operator is provided
448 449 450 451 452 453 454
  // 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 已提交
455 456 457 458 459 460
  direction_ = kReverse;
  ClearSavedValue();
  iter_->SeekToLast();
  FindPrevUserEntry();
}

J
jorlow@chromium.org 已提交
461 462 463 464 465
}  // anonymous namespace

Iterator* NewDBIterator(
    const std::string* dbname,
    Env* env,
466 467
    const Options& options,
    const Comparator *user_key_comparator,
J
jorlow@chromium.org 已提交
468 469
    Iterator* internal_iter,
    const SequenceNumber& sequence) {
470 471
  return new DBIter(dbname, env, options, user_key_comparator,
                    internal_iter, sequence);
J
jorlow@chromium.org 已提交
472 473
}

474
}  // namespace rocksdb