version_set.cc 39.5 KB
Newer Older
J
jorlow@chromium.org 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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/version_set.h"

#include <algorithm>
#include <stdio.h>
#include "db/filename.h"
#include "db/log_reader.h"
#include "db/log_writer.h"
#include "db/memtable.h"
#include "db/table_cache.h"
14 15
#include "leveldb/env.h"
#include "leveldb/table_builder.h"
J
jorlow@chromium.org 已提交
16 17 18 19 20 21 22
#include "table/merger.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
#include "util/logging.h"

namespace leveldb {

J
jorlow@chromium.org 已提交
23 24 25
static const int kTargetFileSize = 2 * 1048576;

// Maximum bytes of overlaps in grandparent (i.e., level+2) before we
26
// stop building a single file in a level->level+1 compaction.
J
jorlow@chromium.org 已提交
27
static const int64_t kMaxGrandParentOverlapBytes = 10 * kTargetFileSize;
28

J
jorlow@chromium.org 已提交
29
static double MaxBytesForLevel(int level) {
30 31 32 33 34 35
  // Note: the result for level zero is not really used since we set
  // the level-0 compaction threshold based on number of files.
  double result = 10 * 1048576.0;  // Result for both level-0 and level-1
  while (level > 1) {
    result *= 10;
    level--;
J
jorlow@chromium.org 已提交
36
  }
37
  return result;
J
jorlow@chromium.org 已提交
38 39 40
}

static uint64_t MaxFileSizeForLevel(int level) {
J
jorlow@chromium.org 已提交
41
  return kTargetFileSize;  // We could vary per level to reduce number of files?
J
jorlow@chromium.org 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
}

namespace {
std::string IntSetToString(const std::set<uint64_t>& s) {
  std::string result = "{";
  for (std::set<uint64_t>::const_iterator it = s.begin();
       it != s.end();
       ++it) {
    result += (result.size() > 1) ? "," : "";
    result += NumberToString(*it);
  }
  result += "}";
  return result;
}
}

Version::~Version() {
  assert(refs_ == 0);
60 61 62 63 64 65

  // Remove from linked list
  prev_->next_ = next_;
  next_->prev_ = prev_;

  // Drop references to files
J
jorlow@chromium.org 已提交
66
  for (int level = 0; level < config::kNumLevels; level++) {
D
dgrogan@chromium.org 已提交
67
    for (size_t i = 0; i < files_[level].size(); i++) {
J
jorlow@chromium.org 已提交
68
      FileMetaData* f = files_[level][i];
69
      assert(f->refs > 0);
J
jorlow@chromium.org 已提交
70 71 72 73 74 75 76 77
      f->refs--;
      if (f->refs <= 0) {
        delete f;
      }
    }
  }
}

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
int FindFile(const InternalKeyComparator& icmp,
             const std::vector<FileMetaData*>& files,
             const Slice& key) {
  uint32_t left = 0;
  uint32_t right = files.size();
  while (left < right) {
    uint32_t mid = (left + right) / 2;
    const FileMetaData* f = files[mid];
    if (icmp.InternalKeyComparator::Compare(f->largest.Encode(), key) < 0) {
      // Key at "mid.largest" is < "target".  Therefore all
      // files at or before "mid" are uninteresting.
      left = mid + 1;
    } else {
      // Key at "mid.largest" is >= "target".  Therefore all files
      // after "mid" are uninteresting.
      right = mid;
    }
  }
  return right;
}

bool SomeFileOverlapsRange(
    const InternalKeyComparator& icmp,
    const std::vector<FileMetaData*>& files,
102 103 104 105
    const Slice& smallest_user_key,
    const Slice& largest_user_key) {
  // Find the earliest possible internal key for smallest_user_key
  InternalKey small(smallest_user_key, kMaxSequenceNumber, kValueTypeForSeek);
D
dgrogan@chromium.org 已提交
106
  const uint32_t index = FindFile(icmp, files, small.Encode());
107
  return ((index < files.size()) &&
108 109
          icmp.user_comparator()->Compare(
              largest_user_key, files[index]->smallest.user_key()) >= 0);
110 111
}

J
jorlow@chromium.org 已提交
112 113 114
// An internal iterator.  For a given version/level pair, yields
// information about the files in the level.  For a given entry, key()
// is the largest key that occurs in the file, and value() is an
J
jorlow@chromium.org 已提交
115 116
// 16-byte value containing the file number and file size, both
// encoded using EncodeFixed64.
J
jorlow@chromium.org 已提交
117 118
class Version::LevelFileNumIterator : public Iterator {
 public:
119
  LevelFileNumIterator(const InternalKeyComparator& icmp,
J
jorlow@chromium.org 已提交
120
                       const std::vector<FileMetaData*>* flist)
121
      : icmp_(icmp),
J
jorlow@chromium.org 已提交
122 123 124 125 126 127 128
        flist_(flist),
        index_(flist->size()) {        // Marks as invalid
  }
  virtual bool Valid() const {
    return index_ < flist_->size();
  }
  virtual void Seek(const Slice& target) {
129
    index_ = FindFile(icmp_, *flist_, target);
J
jorlow@chromium.org 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  }
  virtual void SeekToFirst() { index_ = 0; }
  virtual void SeekToLast() {
    index_ = flist_->empty() ? 0 : flist_->size() - 1;
  }
  virtual void Next() {
    assert(Valid());
    index_++;
  }
  virtual void Prev() {
    assert(Valid());
    if (index_ == 0) {
      index_ = flist_->size();  // Marks as invalid
    } else {
      index_--;
    }
  }
  Slice key() const {
    assert(Valid());
    return (*flist_)[index_]->largest.Encode();
  }
  Slice value() const {
    assert(Valid());
    EncodeFixed64(value_buf_, (*flist_)[index_]->number);
J
jorlow@chromium.org 已提交
154
    EncodeFixed64(value_buf_+8, (*flist_)[index_]->file_size);
J
jorlow@chromium.org 已提交
155 156 157 158 159 160
    return Slice(value_buf_, sizeof(value_buf_));
  }
  virtual Status status() const { return Status::OK(); }
 private:
  const InternalKeyComparator icmp_;
  const std::vector<FileMetaData*>* const flist_;
D
dgrogan@chromium.org 已提交
161
  uint32_t index_;
J
jorlow@chromium.org 已提交
162

J
jorlow@chromium.org 已提交
163 164
  // Backing store for value().  Holds the file number and size.
  mutable char value_buf_[16];
J
jorlow@chromium.org 已提交
165 166 167 168 169 170
};

static Iterator* GetFileIterator(void* arg,
                                 const ReadOptions& options,
                                 const Slice& file_value) {
  TableCache* cache = reinterpret_cast<TableCache*>(arg);
J
jorlow@chromium.org 已提交
171
  if (file_value.size() != 16) {
J
jorlow@chromium.org 已提交
172 173 174
    return NewErrorIterator(
        Status::Corruption("FileReader invoked with unexpected value"));
  } else {
J
jorlow@chromium.org 已提交
175 176 177
    return cache->NewIterator(options,
                              DecodeFixed64(file_value.data()),
                              DecodeFixed64(file_value.data() + 8));
J
jorlow@chromium.org 已提交
178 179 180 181 182 183
  }
}

Iterator* Version::NewConcatenatingIterator(const ReadOptions& options,
                                            int level) const {
  return NewTwoLevelIterator(
184
      new LevelFileNumIterator(vset_->icmp_, &files_[level]),
J
jorlow@chromium.org 已提交
185 186 187 188 189 190
      &GetFileIterator, vset_->table_cache_, options);
}

void Version::AddIterators(const ReadOptions& options,
                           std::vector<Iterator*>* iters) {
  // Merge all level zero files together since they may overlap
D
dgrogan@chromium.org 已提交
191
  for (size_t i = 0; i < files_[0].size(); i++) {
J
jorlow@chromium.org 已提交
192
    iters->push_back(
J
jorlow@chromium.org 已提交
193 194
        vset_->table_cache_->NewIterator(
            options, files_[0][i]->number, files_[0][i]->file_size));
J
jorlow@chromium.org 已提交
195 196 197 198 199 200 201 202 203 204 205 206
  }

  // For levels > 0, we can use a concatenating iterator that sequentially
  // walks through the non-overlapping files in the level, opening them
  // lazily.
  for (int level = 1; level < config::kNumLevels; level++) {
    if (!files_[level].empty()) {
      iters->push_back(NewConcatenatingIterator(options, level));
    }
  }
}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
// If "*iter" points at a value or deletion for user_key, store
// either the value, or a NotFound error and return true.
// Else return false.
static bool GetValue(Iterator* iter, const Slice& user_key,
                     std::string* value,
                     Status* s) {
  if (!iter->Valid()) {
    return false;
  }
  ParsedInternalKey parsed_key;
  if (!ParseInternalKey(iter->key(), &parsed_key)) {
    *s = Status::Corruption("corrupted key for ", user_key);
    return true;
  }
  if (parsed_key.user_key != user_key) {
    return false;
  }
  switch (parsed_key.type) {
    case kTypeDeletion:
      *s = Status::NotFound(Slice());  // Use an empty error message for speed
      break;
    case kTypeValue: {
      Slice v = iter->value();
      value->assign(v.data(), v.size());
      break;
    }
  }
  return true;
}

static bool NewestFirst(FileMetaData* a, FileMetaData* b) {
  return a->number > b->number;
}

Status Version::Get(const ReadOptions& options,
                    const LookupKey& k,
                    std::string* value,
                    GetStats* stats) {
  Slice ikey = k.internal_key();
  Slice user_key = k.user_key();
  const Comparator* ucmp = vset_->icmp_.user_comparator();
  Status s;

  stats->seek_file = NULL;
  stats->seek_file_level = -1;
  FileMetaData* last_file_read = NULL;
253
  int last_file_read_level = -1;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

  // We can search level-by-level since entries never hop across
  // levels.  Therefore we are guaranteed that if we find data
  // in an smaller level, later levels are irrelevant.
  std::vector<FileMetaData*> tmp;
  FileMetaData* tmp2;
  for (int level = 0; level < config::kNumLevels; level++) {
    size_t num_files = files_[level].size();
    if (num_files == 0) continue;

    // Get the list of files to search in this level
    FileMetaData* const* files = &files_[level][0];
    if (level == 0) {
      // Level-0 files may overlap each other.  Find all files that
      // overlap user_key and process them in order from newest to oldest.
      tmp.reserve(num_files);
D
dgrogan@chromium.org 已提交
270
      for (uint32_t i = 0; i < num_files; i++) {
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        FileMetaData* f = files[i];
        if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 &&
            ucmp->Compare(user_key, f->largest.user_key()) <= 0) {
          tmp.push_back(f);
        }
      }
      if (tmp.empty()) continue;

      std::sort(tmp.begin(), tmp.end(), NewestFirst);
      files = &tmp[0];
      num_files = tmp.size();
    } else {
      // Binary search to find earliest index whose largest key >= ikey.
      uint32_t index = FindFile(vset_->icmp_, files_[level], ikey);
      if (index >= num_files) {
        files = NULL;
        num_files = 0;
      } else {
        tmp2 = files[index];
        if (ucmp->Compare(user_key, tmp2->smallest.user_key()) < 0) {
          // All of "tmp2" is past any data for user_key
          files = NULL;
          num_files = 0;
        } else {
          files = &tmp2;
          num_files = 1;
        }
      }
    }

D
dgrogan@chromium.org 已提交
301
    for (uint32_t i = 0; i < num_files; ++i) {
302 303 304
      if (last_file_read != NULL && stats->seek_file == NULL) {
        // We have had more than one seek for this read.  Charge the 1st file.
        stats->seek_file = last_file_read;
305
        stats->seek_file_level = last_file_read_level;
306 307 308 309
      }

      FileMetaData* f = files[i];
      last_file_read = f;
310
      last_file_read_level = level;
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

      Iterator* iter = vset_->table_cache_->NewIterator(
          options,
          f->number,
          f->file_size);
      iter->Seek(ikey);
      const bool done = GetValue(iter, user_key, value, &s);
      if (!iter->status().ok()) {
        s = iter->status();
        delete iter;
        return s;
      } else {
        delete iter;
        if (done) {
          return s;
        }
      }
    }
  }

  return Status::NotFound(Slice());  // Use an empty error message for speed
}

bool Version::UpdateStats(const GetStats& stats) {
  FileMetaData* f = stats.seek_file;
  if (f != NULL) {
    f->allowed_seeks--;
    if (f->allowed_seeks <= 0 && file_to_compact_ == NULL) {
      file_to_compact_ = f;
      file_to_compact_level_ = stats.seek_file_level;
      return true;
    }
  }
  return false;
}

J
jorlow@chromium.org 已提交
347 348 349 350 351
void Version::Ref() {
  ++refs_;
}

void Version::Unref() {
352
  assert(this != &vset_->dummy_versions_);
J
jorlow@chromium.org 已提交
353 354 355
  assert(refs_ >= 1);
  --refs_;
  if (refs_ == 0) {
356
    delete this;
J
jorlow@chromium.org 已提交
357 358 359
  }
}

360
bool Version::OverlapInLevel(int level,
361 362 363 364 365
                             const Slice& smallest_user_key,
                             const Slice& largest_user_key) {
  return SomeFileOverlapsRange(vset_->icmp_, files_[level],
                               smallest_user_key,
                               largest_user_key);
366 367
}

J
jorlow@chromium.org 已提交
368 369 370
std::string Version::DebugString() const {
  std::string r;
  for (int level = 0; level < config::kNumLevels; level++) {
371 372 373 374 375
    // E.g.,
    //   --- level 1 ---
    //   17:123['a' .. 'd']
    //   20:43['e' .. 'g']
    r.append("--- level ");
J
jorlow@chromium.org 已提交
376
    AppendNumberTo(&r, level);
377
    r.append(" ---\n");
J
jorlow@chromium.org 已提交
378
    const std::vector<FileMetaData*>& files = files_[level];
D
dgrogan@chromium.org 已提交
379
    for (size_t i = 0; i < files.size(); i++) {
J
jorlow@chromium.org 已提交
380 381 382 383 384 385 386 387
      r.push_back(' ');
      AppendNumberTo(&r, files[i]->number);
      r.push_back(':');
      AppendNumberTo(&r, files[i]->file_size);
      r.append("['");
      AppendEscapedStringTo(&r, files[i]->smallest.Encode());
      r.append("' .. '");
      AppendEscapedStringTo(&r, files[i]->largest.Encode());
388
      r.append("']\n");
J
jorlow@chromium.org 已提交
389 390 391 392 393 394 395 396 397 398
    }
  }
  return r;
}

// A helper class so we can efficiently apply a whole sequence
// of edits to a particular state without creating intermediate
// Versions that contain full copies of the intermediate state.
class VersionSet::Builder {
 private:
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
  // Helper to sort by v->files_[file_number].smallest
  struct BySmallestKey {
    const InternalKeyComparator* internal_comparator;

    bool operator()(FileMetaData* f1, FileMetaData* f2) const {
      int r = internal_comparator->Compare(f1->smallest, f2->smallest);
      if (r != 0) {
        return (r < 0);
      } else {
        // Break ties by file number
        return (f1->number < f2->number);
      }
    }
  };

  typedef std::set<FileMetaData*, BySmallestKey> FileSet;
  struct LevelState {
    std::set<uint64_t> deleted_files;
    FileSet* added_files;
  };

J
jorlow@chromium.org 已提交
420
  VersionSet* vset_;
421 422
  Version* base_;
  LevelState levels_[config::kNumLevels];
J
jorlow@chromium.org 已提交
423 424 425 426

 public:
  // Initialize a builder with the files from *base and other info from *vset
  Builder(VersionSet* vset, Version* base)
427 428 429 430 431
      : vset_(vset),
        base_(base) {
    base_->Ref();
    BySmallestKey cmp;
    cmp.internal_comparator = &vset_->icmp_;
J
jorlow@chromium.org 已提交
432
    for (int level = 0; level < config::kNumLevels; level++) {
433
      levels_[level].added_files = new FileSet(cmp);
J
jorlow@chromium.org 已提交
434 435 436 437 438
    }
  }

  ~Builder() {
    for (int level = 0; level < config::kNumLevels; level++) {
439 440 441 442 443 444 445 446
      const FileSet* added = levels_[level].added_files;
      std::vector<FileMetaData*> to_unref;
      to_unref.reserve(added->size());
      for (FileSet::const_iterator it = added->begin();
          it != added->end(); ++it) {
        to_unref.push_back(*it);
      }
      delete added;
D
dgrogan@chromium.org 已提交
447
      for (uint32_t i = 0; i < to_unref.size(); i++) {
448
        FileMetaData* f = to_unref[i];
J
jorlow@chromium.org 已提交
449 450 451 452 453 454
        f->refs--;
        if (f->refs <= 0) {
          delete f;
        }
      }
    }
455
    base_->Unref();
J
jorlow@chromium.org 已提交
456 457 458 459 460
  }

  // Apply all of the edits in *edit to the current state.
  void Apply(VersionEdit* edit) {
    // Update compaction pointers
D
dgrogan@chromium.org 已提交
461
    for (size_t i = 0; i < edit->compact_pointers_.size(); i++) {
J
jorlow@chromium.org 已提交
462 463 464 465 466 467 468 469 470 471 472 473
      const int level = edit->compact_pointers_[i].first;
      vset_->compact_pointer_[level] =
          edit->compact_pointers_[i].second.Encode().ToString();
    }

    // Delete files
    const VersionEdit::DeletedFileSet& del = edit->deleted_files_;
    for (VersionEdit::DeletedFileSet::const_iterator iter = del.begin();
         iter != del.end();
         ++iter) {
      const int level = iter->first;
      const uint64_t number = iter->second;
474
      levels_[level].deleted_files.insert(number);
J
jorlow@chromium.org 已提交
475 476 477
    }

    // Add new files
D
dgrogan@chromium.org 已提交
478
    for (size_t i = 0; i < edit->new_files_.size(); i++) {
J
jorlow@chromium.org 已提交
479 480 481
      const int level = edit->new_files_[i].first;
      FileMetaData* f = new FileMetaData(edit->new_files_[i].second);
      f->refs = 1;
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

      // We arrange to automatically compact this file after
      // a certain number of seeks.  Let's assume:
      //   (1) One seek costs 10ms
      //   (2) Writing or reading 1MB costs 10ms (100MB/s)
      //   (3) A compaction of 1MB does 25MB of IO:
      //         1MB read from this level
      //         10-12MB read from next level (boundaries may be misaligned)
      //         10-12MB written to next level
      // This implies that 25 seeks cost the same as the compaction
      // of 1MB of data.  I.e., one seek costs approximately the
      // same as the compaction of 40KB of data.  We are a little
      // conservative and allow approximately one seek for every 16KB
      // of data before triggering a compaction.
      f->allowed_seeks = (f->file_size / 16384);
      if (f->allowed_seeks < 100) f->allowed_seeks = 100;

499 500
      levels_[level].deleted_files.erase(f->number);
      levels_[level].added_files->insert(f);
J
jorlow@chromium.org 已提交
501 502 503 504 505
    }
  }

  // Save the current state in *v.
  void SaveTo(Version* v) {
506 507
    BySmallestKey cmp;
    cmp.internal_comparator = &vset_->icmp_;
J
jorlow@chromium.org 已提交
508
    for (int level = 0; level < config::kNumLevels; level++) {
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
      // Merge the set of added files with the set of pre-existing files.
      // Drop any deleted files.  Store the result in *v.
      const std::vector<FileMetaData*>& base_files = base_->files_[level];
      std::vector<FileMetaData*>::const_iterator base_iter = base_files.begin();
      std::vector<FileMetaData*>::const_iterator base_end = base_files.end();
      const FileSet* added = levels_[level].added_files;
      v->files_[level].reserve(base_files.size() + added->size());
      for (FileSet::const_iterator added_iter = added->begin();
           added_iter != added->end();
           ++added_iter) {
        // Add all smaller files listed in base_
        for (std::vector<FileMetaData*>::const_iterator bpos
                 = std::upper_bound(base_iter, base_end, *added_iter, cmp);
             base_iter != bpos;
             ++base_iter) {
          MaybeAddFile(v, level, *base_iter);
        }

        MaybeAddFile(v, level, *added_iter);
      }

      // Add remaining base files
      for (; base_iter != base_end; ++base_iter) {
        MaybeAddFile(v, level, *base_iter);
J
jorlow@chromium.org 已提交
533
      }
534 535 536 537

#ifndef NDEBUG
      // Make sure there is no overlap in levels > 0
      if (level > 0) {
D
dgrogan@chromium.org 已提交
538
        for (uint32_t i = 1; i < v->files_[level].size(); i++) {
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
          const InternalKey& prev_end = v->files_[level][i-1]->largest;
          const InternalKey& this_begin = v->files_[level][i]->smallest;
          if (vset_->icmp_.Compare(prev_end, this_begin) >= 0) {
            fprintf(stderr, "overlapping ranges in same level %s vs. %s\n",
                    EscapeString(prev_end.Encode()).c_str(),
                    EscapeString(this_begin.Encode()).c_str());
            abort();
          }
        }
      }
#endif
    }
  }

  void MaybeAddFile(Version* v, int level, FileMetaData* f) {
    if (levels_[level].deleted_files.count(f->number) > 0) {
      // File is deleted: do nothing
    } else {
557 558 559 560 561 562
      std::vector<FileMetaData*>* files = &v->files_[level];
      if (level > 0 && !files->empty()) {
        // Must not overlap
        assert(vset_->icmp_.Compare((*files)[files->size()-1]->largest,
                                    f->smallest) < 0);
      }
563
      f->refs++;
564
      files->push_back(f);
J
jorlow@chromium.org 已提交
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    }
  }
};

VersionSet::VersionSet(const std::string& dbname,
                       const Options* options,
                       TableCache* table_cache,
                       const InternalKeyComparator* cmp)
    : env_(options->env),
      dbname_(dbname),
      options_(options),
      table_cache_(table_cache),
      icmp_(*cmp),
      next_file_number_(2),
      manifest_file_number_(0),  // Filled by Recover()
580 581 582
      last_sequence_(0),
      log_number_(0),
      prev_log_number_(0),
J
jorlow@chromium.org 已提交
583 584
      descriptor_file_(NULL),
      descriptor_log_(NULL),
585 586 587
      dummy_versions_(this),
      current_(NULL) {
  AppendVersion(new Version(this));
J
jorlow@chromium.org 已提交
588 589 590
}

VersionSet::~VersionSet() {
591 592
  current_->Unref();
  assert(dummy_versions_.next_ == &dummy_versions_);  // List must be empty
J
jorlow@chromium.org 已提交
593 594 595 596
  delete descriptor_log_;
  delete descriptor_file_;
}

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
void VersionSet::AppendVersion(Version* v) {
  // Make "v" current
  assert(v->refs_ == 0);
  assert(v != current_);
  if (current_ != NULL) {
    current_->Unref();
  }
  current_ = v;
  v->Ref();

  // Append to linked list
  v->prev_ = dummy_versions_.prev_;
  v->next_ = &dummy_versions_;
  v->prev_->next_ = v;
  v->next_->prev_ = v;
}

614
Status VersionSet::LogAndApply(VersionEdit* edit, port::Mutex* mu) {
615 616 617 618 619 620 621 622 623 624 625
  if (edit->has_log_number_) {
    assert(edit->log_number_ >= log_number_);
    assert(edit->log_number_ < next_file_number_);
  } else {
    edit->SetLogNumber(log_number_);
  }

  if (!edit->has_prev_log_number_) {
    edit->SetPrevLogNumber(prev_log_number_);
  }

J
jorlow@chromium.org 已提交
626
  edit->SetNextFile(next_file_number_);
627
  edit->SetLastSequence(last_sequence_);
J
jorlow@chromium.org 已提交
628 629 630 631 632 633 634

  Version* v = new Version(this);
  {
    Builder builder(this, current_);
    builder.Apply(edit);
    builder.SaveTo(v);
  }
635
  Finalize(v);
J
jorlow@chromium.org 已提交
636 637 638

  // Initialize new descriptor log file if necessary by creating
  // a temporary file that contains a snapshot of the current version.
639 640 641
  std::string new_manifest_file;
  Status s;
  if (descriptor_log_ == NULL) {
642 643
    // No reason to unlock *mu here since we only hit this path in the
    // first call to LogAndApply (when opening the database).
644 645 646 647 648 649 650
    assert(descriptor_file_ == NULL);
    new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_);
    edit->SetNextFile(next_file_number_);
    s = env_->NewWritableFile(new_manifest_file, &descriptor_file_);
    if (s.ok()) {
      descriptor_log_ = new log::Writer(descriptor_file_);
      s = WriteSnapshot(descriptor_log_);
J
jorlow@chromium.org 已提交
651 652 653
    }
  }

654 655 656 657 658
  // Unlock during expensive MANIFEST log write
  {
    mu->Unlock();

    // Write new record to MANIFEST log
J
jorlow@chromium.org 已提交
659
    if (s.ok()) {
660 661 662 663 664 665
      std::string record;
      edit->EncodeTo(&record);
      s = descriptor_log_->AddRecord(record);
      if (s.ok()) {
        s = descriptor_file_->Sync();
      }
J
jorlow@chromium.org 已提交
666 667
    }

668 669 670 671 672 673 674
    // If we just created a new descriptor file, install it by writing a
    // new CURRENT file that points to it.
    if (s.ok() && !new_manifest_file.empty()) {
      s = SetCurrentFile(env_, dbname_, manifest_file_number_);
    }

    mu->Lock();
J
jorlow@chromium.org 已提交
675 676 677 678
  }

  // Install the new version
  if (s.ok()) {
679
    AppendVersion(v);
680 681
    log_number_ = edit->log_number_;
    prev_log_number_ = edit->prev_log_number_;
J
jorlow@chromium.org 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695
  } else {
    delete v;
    if (!new_manifest_file.empty()) {
      delete descriptor_log_;
      delete descriptor_file_;
      descriptor_log_ = NULL;
      descriptor_file_ = NULL;
      env_->DeleteFile(new_manifest_file);
    }
  }

  return s;
}

696
Status VersionSet::Recover() {
J
jorlow@chromium.org 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
  struct LogReporter : public log::Reader::Reporter {
    Status* status;
    virtual void Corruption(size_t bytes, const Status& s) {
      if (this->status->ok()) *this->status = s;
    }
  };

  // Read "CURRENT" file, which contains a pointer to the current manifest file
  std::string current;
  Status s = ReadFileToString(env_, CurrentFileName(dbname_), &current);
  if (!s.ok()) {
    return s;
  }
  if (current.empty() || current[current.size()-1] != '\n') {
    return Status::Corruption("CURRENT file does not end with newline");
  }
  current.resize(current.size() - 1);

  std::string dscname = dbname_ + "/" + current;
  SequentialFile* file;
  s = env_->NewSequentialFile(dscname, &file);
  if (!s.ok()) {
    return s;
  }

  bool have_log_number = false;
723
  bool have_prev_log_number = false;
J
jorlow@chromium.org 已提交
724 725 726
  bool have_next_file = false;
  bool have_last_sequence = false;
  uint64_t next_file = 0;
727 728 729
  uint64_t last_sequence = 0;
  uint64_t log_number = 0;
  uint64_t prev_log_number = 0;
J
jorlow@chromium.org 已提交
730 731 732 733 734
  Builder builder(this, current_);

  {
    LogReporter reporter;
    reporter.status = &s;
735
    log::Reader reader(file, &reporter, true/*checksum*/, 0/*initial_offset*/);
J
jorlow@chromium.org 已提交
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    Slice record;
    std::string scratch;
    while (reader.ReadRecord(&record, &scratch) && s.ok()) {
      VersionEdit edit;
      s = edit.DecodeFrom(record);
      if (s.ok()) {
        if (edit.has_comparator_ &&
            edit.comparator_ != icmp_.user_comparator()->Name()) {
          s = Status::InvalidArgument(
              edit.comparator_ + "does not match existing comparator ",
              icmp_.user_comparator()->Name());
        }
      }

      if (s.ok()) {
        builder.Apply(&edit);
      }

      if (edit.has_log_number_) {
755
        log_number = edit.log_number_;
J
jorlow@chromium.org 已提交
756 757 758
        have_log_number = true;
      }

759 760 761 762 763
      if (edit.has_prev_log_number_) {
        prev_log_number = edit.prev_log_number_;
        have_prev_log_number = true;
      }

J
jorlow@chromium.org 已提交
764 765 766 767 768 769
      if (edit.has_next_file_number_) {
        next_file = edit.next_file_number_;
        have_next_file = true;
      }

      if (edit.has_last_sequence_) {
770
        last_sequence = edit.last_sequence_;
J
jorlow@chromium.org 已提交
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
        have_last_sequence = true;
      }
    }
  }
  delete file;
  file = NULL;

  if (s.ok()) {
    if (!have_next_file) {
      s = Status::Corruption("no meta-nextfile entry in descriptor");
    } else if (!have_log_number) {
      s = Status::Corruption("no meta-lognumber entry in descriptor");
    } else if (!have_last_sequence) {
      s = Status::Corruption("no last-sequence-number entry in descriptor");
    }
786 787 788 789

    if (!have_prev_log_number) {
      prev_log_number = 0;
    }
790 791 792

    MarkFileNumberUsed(prev_log_number);
    MarkFileNumberUsed(log_number);
J
jorlow@chromium.org 已提交
793 794 795 796 797
  }

  if (s.ok()) {
    Version* v = new Version(this);
    builder.SaveTo(v);
798 799 800 801 802 803 804 805
    // Install recovered version
    Finalize(v);
    AppendVersion(v);
    manifest_file_number_ = next_file;
    next_file_number_ = next_file + 1;
    last_sequence_ = last_sequence;
    log_number_ = log_number;
    prev_log_number_ = prev_log_number;
J
jorlow@chromium.org 已提交
806 807 808 809 810
  }

  return s;
}

811 812 813 814 815 816
void VersionSet::MarkFileNumberUsed(uint64_t number) {
  if (next_file_number_ <= number) {
    next_file_number_ = number + 1;
  }
}

817 818
static int64_t TotalFileSize(const std::vector<FileMetaData*>& files) {
  int64_t sum = 0;
D
dgrogan@chromium.org 已提交
819
  for (size_t i = 0; i < files.size(); i++) {
820 821 822 823 824
    sum += files[i]->file_size;
  }
  return sum;
}

825
void VersionSet::Finalize(Version* v) {
J
jorlow@chromium.org 已提交
826 827 828 829
  // Precomputed best level for next compaction
  int best_level = -1;
  double best_score = -1;

830
  for (int level = 0; level < config::kNumLevels-1; level++) {
831
    double score;
J
jorlow@chromium.org 已提交
832
    if (level == 0) {
833 834 835 836 837 838 839 840 841 842 843
      // We treat level-0 specially by bounding the number of files
      // instead of number of bytes for two reasons:
      //
      // (1) With larger write-buffer sizes, it is nice not to do too
      // many level-0 compactions.
      //
      // (2) The files in level-0 are merged on every read and
      // therefore we wish to avoid too many files when the individual
      // file size is small (perhaps because of a small write-buffer
      // setting, or very high compression ratios, or lots of
      // overwrites/deletions).
844 845
      score = v->files_[level].size() /
          static_cast<double>(config::kL0_CompactionTrigger);
846 847 848 849
    } else {
      // Compute the ratio of current size to size limit.
      const uint64_t level_bytes = TotalFileSize(v->files_[level]);
      score = static_cast<double>(level_bytes) / MaxBytesForLevel(level);
J
jorlow@chromium.org 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
    }

    if (score > best_score) {
      best_level = level;
      best_score = score;
    }
  }

  v->compaction_level_ = best_level;
  v->compaction_score_ = best_score;
}

Status VersionSet::WriteSnapshot(log::Writer* log) {
  // TODO: Break up into multiple records to reduce memory usage on recovery?

  // Save metadata
  VersionEdit edit;
  edit.SetComparatorName(icmp_.user_comparator()->Name());

  // Save compaction pointers
  for (int level = 0; level < config::kNumLevels; level++) {
    if (!compact_pointer_[level].empty()) {
      InternalKey key;
      key.DecodeFrom(compact_pointer_[level]);
      edit.SetCompactPointer(level, key);
    }
  }

  // Save files
  for (int level = 0; level < config::kNumLevels; level++) {
    const std::vector<FileMetaData*>& files = current_->files_[level];
D
dgrogan@chromium.org 已提交
881
    for (size_t i = 0; i < files.size(); i++) {
J
jorlow@chromium.org 已提交
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
      const FileMetaData* f = files[i];
      edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
    }
  }

  std::string record;
  edit.EncodeTo(&record);
  return log->AddRecord(record);
}

int VersionSet::NumLevelFiles(int level) const {
  assert(level >= 0);
  assert(level < config::kNumLevels);
  return current_->files_[level].size();
}

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
const char* VersionSet::LevelSummary(LevelSummaryStorage* scratch) const {
  // Update code if kNumLevels changes
  assert(config::kNumLevels == 7);
  snprintf(scratch->buffer, sizeof(scratch->buffer),
           "files[ %d %d %d %d %d %d %d ]",
           int(current_->files_[0].size()),
           int(current_->files_[1].size()),
           int(current_->files_[2].size()),
           int(current_->files_[3].size()),
           int(current_->files_[4].size()),
           int(current_->files_[5].size()),
           int(current_->files_[6].size()));
  return scratch->buffer;
}

J
jorlow@chromium.org 已提交
913 914 915 916
uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
  uint64_t result = 0;
  for (int level = 0; level < config::kNumLevels; level++) {
    const std::vector<FileMetaData*>& files = v->files_[level];
D
dgrogan@chromium.org 已提交
917
    for (size_t i = 0; i < files.size(); i++) {
J
jorlow@chromium.org 已提交
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
      if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
        // Entire file is before "ikey", so just add the file size
        result += files[i]->file_size;
      } else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
        // Entire file is after "ikey", so ignore
        if (level > 0) {
          // Files other than level 0 are sorted by meta->smallest, so
          // no further files in this level will contain data for
          // "ikey".
          break;
        }
      } else {
        // "ikey" falls in the range for this table.  Add the
        // approximate offset of "ikey" within the table.
        Table* tableptr;
        Iterator* iter = table_cache_->NewIterator(
J
jorlow@chromium.org 已提交
934
            ReadOptions(), files[i]->number, files[i]->file_size, &tableptr);
J
jorlow@chromium.org 已提交
935 936 937 938 939 940 941 942 943 944 945
        if (tableptr != NULL) {
          result += tableptr->ApproximateOffsetOf(ikey.Encode());
        }
        delete iter;
      }
    }
  }
  return result;
}

void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
946 947 948
  for (Version* v = dummy_versions_.next_;
       v != &dummy_versions_;
       v = v->next_) {
J
jorlow@chromium.org 已提交
949 950
    for (int level = 0; level < config::kNumLevels; level++) {
      const std::vector<FileMetaData*>& files = v->files_[level];
D
dgrogan@chromium.org 已提交
951
      for (size_t i = 0; i < files.size(); i++) {
J
jorlow@chromium.org 已提交
952 953 954 955 956 957
        live->insert(files[i]->number);
      }
    }
  }
}

958 959 960 961
int64_t VersionSet::NumLevelBytes(int level) const {
  assert(level >= 0);
  assert(level < config::kNumLevels);
  return TotalFileSize(current_->files_[level]);
J
jorlow@chromium.org 已提交
962 963 964 965
}

int64_t VersionSet::MaxNextLevelOverlappingBytes() {
  int64_t result = 0;
966
  std::vector<FileMetaData*> overlaps;
967
  for (int level = 1; level < config::kNumLevels - 1; level++) {
D
dgrogan@chromium.org 已提交
968
    for (size_t i = 0; i < current_->files_[level].size(); i++) {
969 970
      const FileMetaData* f = current_->files_[level][i];
      GetOverlappingInputs(level+1, f->smallest, f->largest, &overlaps);
J
jorlow@chromium.org 已提交
971
      const int64_t sum = TotalFileSize(overlaps);
972 973 974 975 976 977 978 979
      if (sum > result) {
        result = sum;
      }
    }
  }
  return result;
}

J
jorlow@chromium.org 已提交
980 981 982 983 984 985 986 987 988 989
// Store in "*inputs" all files in "level" that overlap [begin,end]
void VersionSet::GetOverlappingInputs(
    int level,
    const InternalKey& begin,
    const InternalKey& end,
    std::vector<FileMetaData*>* inputs) {
  inputs->clear();
  Slice user_begin = begin.user_key();
  Slice user_end = end.user_key();
  const Comparator* user_cmp = icmp_.user_comparator();
D
dgrogan@chromium.org 已提交
990
  for (size_t i = 0; i < current_->files_[level].size(); i++) {
J
jorlow@chromium.org 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    FileMetaData* f = current_->files_[level][i];
    if (user_cmp->Compare(f->largest.user_key(), user_begin) < 0 ||
        user_cmp->Compare(f->smallest.user_key(), user_end) > 0) {
      // Either completely before or after range; skip it
    } else {
      inputs->push_back(f);
    }
  }
}

// Stores the minimal range that covers all entries in inputs in
// *smallest, *largest.
// REQUIRES: inputs is not empty
void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
                          InternalKey* smallest,
                          InternalKey* largest) {
  assert(!inputs.empty());
  smallest->Clear();
  largest->Clear();
D
dgrogan@chromium.org 已提交
1010
  for (size_t i = 0; i < inputs.size(); i++) {
J
jorlow@chromium.org 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    FileMetaData* f = inputs[i];
    if (i == 0) {
      *smallest = f->smallest;
      *largest = f->largest;
    } else {
      if (icmp_.Compare(f->smallest, *smallest) < 0) {
        *smallest = f->smallest;
      }
      if (icmp_.Compare(f->largest, *largest) > 0) {
        *largest = f->largest;
      }
    }
  }
}

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
// Stores the minimal range that covers all entries in inputs1 and inputs2
// in *smallest, *largest.
// REQUIRES: inputs is not empty
void VersionSet::GetRange2(const std::vector<FileMetaData*>& inputs1,
                           const std::vector<FileMetaData*>& inputs2,
                           InternalKey* smallest,
                           InternalKey* largest) {
  std::vector<FileMetaData*> all = inputs1;
  all.insert(all.end(), inputs2.begin(), inputs2.end());
  GetRange(all, smallest, largest);
}

J
jorlow@chromium.org 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
Iterator* VersionSet::MakeInputIterator(Compaction* c) {
  ReadOptions options;
  options.verify_checksums = options_->paranoid_checks;
  options.fill_cache = false;

  // Level-0 files have to be merged together.  For other levels,
  // we will make a concatenating iterator per level.
  // TODO(opt): use concatenating iterator for level-0 if there is no overlap
  const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
  Iterator** list = new Iterator*[space];
  int num = 0;
  for (int which = 0; which < 2; which++) {
    if (!c->inputs_[which].empty()) {
      if (c->level() + which == 0) {
        const std::vector<FileMetaData*>& files = c->inputs_[which];
D
dgrogan@chromium.org 已提交
1053
        for (size_t i = 0; i < files.size(); i++) {
J
jorlow@chromium.org 已提交
1054 1055
          list[num++] = table_cache_->NewIterator(
              options, files[i]->number, files[i]->file_size);
J
jorlow@chromium.org 已提交
1056 1057 1058 1059
        }
      } else {
        // Create concatenating iterator for the files from this level
        list[num++] = NewTwoLevelIterator(
1060
            new Version::LevelFileNumIterator(icmp_, &c->inputs_[which]),
J
jorlow@chromium.org 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
            &GetFileIterator, table_cache_, options);
      }
    }
  }
  assert(num <= space);
  Iterator* result = NewMergingIterator(&icmp_, list, num);
  delete[] list;
  return result;
}

Compaction* VersionSet::PickCompaction() {
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
  Compaction* c;
  int level;

  // We prefer compactions triggered by too much data in a level over
  // the compactions triggered by seeks.
  const bool size_compaction = (current_->compaction_score_ >= 1);
  const bool seek_compaction = (current_->file_to_compact_ != NULL);
  if (size_compaction) {
    level = current_->compaction_level_;
    assert(level >= 0);
    assert(level+1 < config::kNumLevels);
    c = new Compaction(level);

    // Pick the first file that comes after compact_pointer_[level]
    for (size_t i = 0; i < current_->files_[level].size(); i++) {
      FileMetaData* f = current_->files_[level][i];
      if (compact_pointer_[level].empty() ||
          icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
        c->inputs_[0].push_back(f);
        break;
      }
    }
    if (c->inputs_[0].empty()) {
      // Wrap-around to the beginning of the key space
      c->inputs_[0].push_back(current_->files_[level][0]);
    }
  } else if (seek_compaction) {
    level = current_->file_to_compact_level_;
    c = new Compaction(level);
    c->inputs_[0].push_back(current_->file_to_compact_);
  } else {
J
jorlow@chromium.org 已提交
1103 1104 1105 1106 1107 1108 1109 1110
    return NULL;
  }

  c->input_version_ = current_;
  c->input_version_->Ref();

  // Files in level 0 may overlap each other, so pick up all overlapping ones
  if (level == 0) {
1111 1112
    InternalKey smallest, largest;
    GetRange(c->inputs_[0], &smallest, &largest);
J
jorlow@chromium.org 已提交
1113 1114 1115 1116 1117 1118 1119
    // Note that the next call will discard the file we placed in
    // c->inputs_[0] earlier and replace it with an overlapping set
    // which will include the picked file.
    GetOverlappingInputs(0, smallest, largest, &c->inputs_[0]);
    assert(!c->inputs_[0].empty());
  }

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
  SetupOtherInputs(c);

  return c;
}

void VersionSet::SetupOtherInputs(Compaction* c) {
  const int level = c->level();
  InternalKey smallest, largest;
  GetRange(c->inputs_[0], &smallest, &largest);

J
jorlow@chromium.org 已提交
1130 1131
  GetOverlappingInputs(level+1, smallest, largest, &c->inputs_[1]);

1132 1133 1134 1135
  // Get entire range covered by compaction
  InternalKey all_start, all_limit;
  GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);

J
jorlow@chromium.org 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  // See if we can grow the number of inputs in "level" without
  // changing the number of "level+1" files we pick up.
  if (!c->inputs_[1].empty()) {
    std::vector<FileMetaData*> expanded0;
    GetOverlappingInputs(level, all_start, all_limit, &expanded0);
    if (expanded0.size() > c->inputs_[0].size()) {
      InternalKey new_start, new_limit;
      GetRange(expanded0, &new_start, &new_limit);
      std::vector<FileMetaData*> expanded1;
      GetOverlappingInputs(level+1, new_start, new_limit, &expanded1);
      if (expanded1.size() == c->inputs_[1].size()) {
1147
        Log(options_->info_log,
J
jorlow@chromium.org 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
            "Expanding@%d %d+%d to %d+%d\n",
            level,
            int(c->inputs_[0].size()),
            int(c->inputs_[1].size()),
            int(expanded0.size()),
            int(expanded1.size()));
        smallest = new_start;
        largest = new_limit;
        c->inputs_[0] = expanded0;
        c->inputs_[1] = expanded1;
1158
        GetRange2(c->inputs_[0], c->inputs_[1], &all_start, &all_limit);
J
jorlow@chromium.org 已提交
1159 1160 1161 1162
      }
    }
  }

1163 1164 1165 1166 1167 1168
  // Compute the set of grandparent files that overlap this compaction
  // (parent == level+1; grandparent == level+2)
  if (level + 2 < config::kNumLevels) {
    GetOverlappingInputs(level + 2, all_start, all_limit, &c->grandparents_);
  }

J
jorlow@chromium.org 已提交
1169
  if (false) {
1170
    Log(options_->info_log, "Compacting %d '%s' .. '%s'",
J
jorlow@chromium.org 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
        level,
        EscapeString(smallest.Encode()).c_str(),
        EscapeString(largest.Encode()).c_str());
  }

  // Update the place where we will do the next compaction for this level.
  // We update this immediately instead of waiting for the VersionEdit
  // to be applied so that if the compaction fails, we will try a different
  // key range next time.
  compact_pointer_[level] = largest.Encode().ToString();
  c->edit_.SetCompactPointer(level, largest);
}

Compaction* VersionSet::CompactRange(
    int level,
    const InternalKey& begin,
    const InternalKey& end) {
  std::vector<FileMetaData*> inputs;
  GetOverlappingInputs(level, begin, end, &inputs);
  if (inputs.empty()) {
    return NULL;
  }

  Compaction* c = new Compaction(level);
  c->input_version_ = current_;
  c->input_version_->Ref();
  c->inputs_[0] = inputs;
1198
  SetupOtherInputs(c);
J
jorlow@chromium.org 已提交
1199 1200 1201 1202 1203 1204
  return c;
}

Compaction::Compaction(int level)
    : level_(level),
      max_output_file_size_(MaxFileSizeForLevel(level)),
1205 1206
      input_version_(NULL),
      grandparent_index_(0),
J
jorlow@chromium.org 已提交
1207 1208
      seen_key_(false),
      overlapped_bytes_(0) {
J
jorlow@chromium.org 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
  for (int i = 0; i < config::kNumLevels; i++) {
    level_ptrs_[i] = 0;
  }
}

Compaction::~Compaction() {
  if (input_version_ != NULL) {
    input_version_->Unref();
  }
}

1220
bool Compaction::IsTrivialMove() const {
J
jorlow@chromium.org 已提交
1221
  // Avoid a move if there is lots of overlapping grandparent data.
1222 1223
  // Otherwise, the move could create a parent file that will require
  // a very expensive merge later on.
J
jorlow@chromium.org 已提交
1224 1225 1226
  return (num_input_files(0) == 1 &&
          num_input_files(1) == 0 &&
          TotalFileSize(grandparents_) <= kMaxGrandParentOverlapBytes);
1227 1228
}

J
jorlow@chromium.org 已提交
1229 1230
void Compaction::AddInputDeletions(VersionEdit* edit) {
  for (int which = 0; which < 2; which++) {
D
dgrogan@chromium.org 已提交
1231
    for (size_t i = 0; i < inputs_[which].size(); i++) {
J
jorlow@chromium.org 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
      edit->DeleteFile(level_ + which, inputs_[which][i]->number);
    }
  }
}

bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
  // Maybe use binary search to find right entry instead of linear search?
  const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
  for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
    const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
    for (; level_ptrs_[lvl] < files.size(); ) {
      FileMetaData* f = files[level_ptrs_[lvl]];
      if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
        // We've advanced far enough
        if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
          // Key falls in this file's range, so definitely not base level
          return false;
        }
        break;
      }
      level_ptrs_[lvl]++;
    }
  }
  return true;
}

1258
bool Compaction::ShouldStopBefore(const Slice& internal_key) {
1259 1260 1261
  // Scan to find earliest grandparent file that contains key.
  const InternalKeyComparator* icmp = &input_version_->vset_->icmp_;
  while (grandparent_index_ < grandparents_.size() &&
1262 1263
      icmp->Compare(internal_key,
                    grandparents_[grandparent_index_]->largest.Encode()) > 0) {
J
jorlow@chromium.org 已提交
1264 1265 1266
    if (seen_key_) {
      overlapped_bytes_ += grandparents_[grandparent_index_]->file_size;
    }
1267 1268
    grandparent_index_++;
  }
J
jorlow@chromium.org 已提交
1269
  seen_key_ = true;
1270

J
jorlow@chromium.org 已提交
1271 1272 1273
  if (overlapped_bytes_ > kMaxGrandParentOverlapBytes) {
    // Too much overlap for current output; start new output
    overlapped_bytes_ = 0;
1274 1275 1276 1277 1278 1279
    return true;
  } else {
    return false;
  }
}

J
jorlow@chromium.org 已提交
1280 1281 1282 1283 1284 1285 1286 1287
void Compaction::ReleaseInputs() {
  if (input_version_ != NULL) {
    input_version_->Unref();
    input_version_ = NULL;
  }
}

}