compaction_picker.cc 48.1 KB
Newer Older
I
Igor Canadi 已提交
1 2 3 4 5 6 7 8 9 10
//  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.
//
// 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/compaction_picker.h"
11

L
liuhuahang 已提交
12
#ifndef __STDC_FORMAT_MACROS
I
Igor Canadi 已提交
13
#define __STDC_FORMAT_MACROS
L
liuhuahang 已提交
14 15
#endif

I
Igor Canadi 已提交
16
#include <inttypes.h>
17
#include <limits>
S
sdong 已提交
18
#include <string>
19
#include "db/filename.h"
H
Haobo Xu 已提交
20
#include "util/log_buffer.h"
I
Igor Canadi 已提交
21
#include "util/statistics.h"
I
Igor Canadi 已提交
22 23 24

namespace rocksdb {

M
miguelportilla 已提交
25 26 27 28 29 30 31 32
uint64_t TotalCompensatedFileSize(const std::vector<FileMetaData*>& files) {
  uint64_t sum = 0;
  for (size_t i = 0; i < files.size() && files[i]; i++) {
    sum += files[i]->compensated_file_size;
  }
  return sum;
}

I
Igor Canadi 已提交
33
namespace {
34 35 36 37 38
// Determine compression type, based on user options, level of the output
// file and whether compression is disabled.
// If enable_compression is false, then compression is always disabled no
// matter what the values of the other two parameters are.
// Otherwise, the compression type is determined based on options and level.
39 40 41
CompressionType GetCompressionType(
    const ImmutableCFOptions& ioptions, int level,
    const bool enable_compression = true) {
42 43 44 45 46
  if (!enable_compression) {
    // disable compression
    return kNoCompression;
  }
  // If the use has specified a different compression level for each level,
J
Jonah Cohen 已提交
47
  // then pick the compression for that level.
48 49
  if (!ioptions.compression_per_level.empty()) {
    const int n = ioptions.compression_per_level.size() - 1;
50 51 52
    // It is possible for level_ to be -1; in that case, we use level
    // 0's compression.  This occurs mostly in backwards compatibility
    // situations when the builder doesn't know what level the file
J
Jonah Cohen 已提交
53
    // belongs to.  Likewise, if level is beyond the end of the
54
    // specified compression levels, use the last value.
55
    return ioptions.compression_per_level[std::max(0, std::min(level, n))];
56
  } else {
57
    return ioptions.compression;
58 59
  }
}
I
Igor Canadi 已提交
60

61

I
Igor Canadi 已提交
62 63
}  // anonymous namespace

64
CompactionPicker::CompactionPicker(const ImmutableCFOptions& ioptions,
I
Igor Canadi 已提交
65
                                   const InternalKeyComparator* icmp)
66 67
    : ioptions_(ioptions),
      compactions_in_progress_(ioptions_.num_levels),
I
Igor Canadi 已提交
68 69 70 71 72 73 74 75 76 77 78
      icmp_(icmp) {
}

CompactionPicker::~CompactionPicker() {}

void CompactionPicker::SizeBeingCompacted(std::vector<uint64_t>& sizes) {
  for (int level = 0; level < NumberLevels() - 1; level++) {
    uint64_t total = 0;
    for (auto c : compactions_in_progress_[level]) {
      assert(c->level() == level);
      for (int i = 0; i < c->num_input_files(0); i++) {
79
        total += c->input(0, i)->compensated_file_size;
I
Igor Canadi 已提交
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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
      }
    }
    sizes[level] = total;
  }
}

// Clear all files to indicate that they are not being compacted
// Delete this compaction from the list of running compactions.
void CompactionPicker::ReleaseCompactionFiles(Compaction* c, Status status) {
  c->MarkFilesBeingCompacted(false);
  compactions_in_progress_[c->level()].erase(c);
  if (!status.ok()) {
    c->ResetNextCompactionIndex();
  }
}

void CompactionPicker::GetRange(const std::vector<FileMetaData*>& inputs,
                                InternalKey* smallest, InternalKey* largest) {
  assert(!inputs.empty());
  smallest->Clear();
  largest->Clear();
  for (size_t i = 0; i < inputs.size(); i++) {
    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;
      }
    }
  }
}

void CompactionPicker::GetRange(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);
}

S
sdong 已提交
125 126 127
bool CompactionPicker::ExpandWhileOverlapping(const std::string& cf_name,
                                              VersionStorageInfo* vstorage,
                                              Compaction* c) {
128
  assert(c != nullptr);
I
Igor Canadi 已提交
129
  // If inputs are empty then there is nothing to expand.
130 131 132 133
  if (c->inputs_[0].empty()) {
    assert(c->inputs_[1].empty());
    // This isn't good compaction
    return false;
I
Igor Canadi 已提交
134 135 136 137 138
  }

  // GetOverlappingInputs will always do the right thing for level-0.
  // So we don't need to do any expansion if level == 0.
  if (c->level() == 0) {
I
Igor Canadi 已提交
139
    return true;
I
Igor Canadi 已提交
140 141 142 143 144 145 146 147 148 149 150 151
  }

  const int level = c->level();
  InternalKey smallest, largest;

  // Keep expanding c->inputs_[0] until we are sure that there is a
  // "clean cut" boundary between the files in input and the surrounding files.
  // This will ensure that no parts of a key are lost during compaction.
  int hint_index = -1;
  size_t old_size;
  do {
    old_size = c->inputs_[0].size();
152
    GetRange(c->inputs_[0].files, &smallest, &largest);
I
Igor Canadi 已提交
153
    c->inputs_[0].clear();
S
sdong 已提交
154 155 156
    vstorage->GetOverlappingInputs(level, &smallest, &largest,
                                   &c->inputs_[0].files, hint_index,
                                   &hint_index);
I
Igor Canadi 已提交
157 158 159
  } while(c->inputs_[0].size() > old_size);

  // Get the new range
160
  GetRange(c->inputs_[0].files, &smallest, &largest);
I
Igor Canadi 已提交
161 162 163 164

  // If, after the expansion, there are files that are already under
  // compaction, then we must drop/cancel this compaction.
  int parent_index = -1;
165
  if (c->inputs_[0].empty()) {
166
    Log(InfoLogLevel::WARN_LEVEL, ioptions_.info_log,
I
Igor Canadi 已提交
167
        "[%s] ExpandWhileOverlapping() failure because zero input files",
S
sdong 已提交
168
        cf_name.c_str());
169
  }
170
  if (c->inputs_[0].empty() || FilesInCompaction(c->inputs_[0].files) ||
I
Igor Canadi 已提交
171
      (c->level() != c->output_level() &&
S
sdong 已提交
172
       ParentRangeInCompaction(vstorage, &smallest, &largest, level,
I
Igor Canadi 已提交
173 174 175
                               &parent_index))) {
    c->inputs_[0].clear();
    c->inputs_[1].clear();
176 177 178 179 180 181
    if (!c->inputs_[0].empty()) {
      Log(InfoLogLevel::WARN_LEVEL, ioptions_.info_log,
          "[%s] ExpandWhileOverlapping() failure because some of the necessary"
          " compaction input files are currently being compacted.",
          c->column_family_data()->GetName().c_str());
    }
I
Igor Canadi 已提交
182
    return false;
I
Igor Canadi 已提交
183
  }
I
Igor Canadi 已提交
184
  return true;
I
Igor Canadi 已提交
185 186 187
}

// Returns true if any one of specified files are being compacted
188 189
bool CompactionPicker::FilesInCompaction(
    const std::vector<FileMetaData*>& files) {
I
Igor Canadi 已提交
190 191 192 193 194 195 196 197
  for (unsigned int i = 0; i < files.size(); i++) {
    if (files[i]->being_compacted) {
      return true;
    }
  }
  return false;
}

198 199 200 201 202 203
Compaction* CompactionPicker::FormCompaction(
      const CompactionOptions& compact_options,
      const autovector<CompactionInputFiles>& input_files,
      int output_level, VersionStorageInfo* vstorage,
      const MutableCFOptions& mutable_cf_options) const {
  uint64_t max_grandparent_overlap_bytes =
204
      output_level + 1 < vstorage->num_levels() ?
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
          mutable_cf_options.MaxGrandParentOverlapBytes(output_level + 1) :
          std::numeric_limits<uint64_t>::max();
  assert(input_files.size());
  auto c = new Compaction(vstorage, input_files,
      input_files[0].level, output_level,
      max_grandparent_overlap_bytes,
      compact_options, false);
  c->mutable_cf_options_ = mutable_cf_options;
  c->MarkFilesBeingCompacted(true);

  // TODO(yhchiang): complete the SetBottomMostLevel as follows
  // If there is no any key of the range in DB that is older than the
  // range to compact, it is bottom most.  For leveled compaction,
  // if number-of_level-1 is empty, and output is going to number-of_level-2,
  // it is also bottom-most.  On the other hand, if number of level=1 (
  // something like universal), the compaction is only "bottom-most" if
  // the oldest file is involved.
  c->SetupBottomMostLevel(
      vstorage,
224
      (output_level == vstorage->num_levels() - 1),
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
      (output_level == 0));
  return c;
}

Status CompactionPicker::GetCompactionInputsFromFileNumbers(
    autovector<CompactionInputFiles>* input_files,
    std::unordered_set<uint64_t>* input_set,
    const VersionStorageInfo* vstorage,
    const CompactionOptions& compact_options) const {
  if (input_set->size() == 0U) {
    return Status::InvalidArgument(
        "Compaction must include at least one file.");
  }
  assert(input_files);

  autovector<CompactionInputFiles> matched_input_files;
241
  matched_input_files.resize(vstorage->num_levels());
242 243 244 245
  int first_non_empty_level = -1;
  int last_non_empty_level = -1;
  // TODO(yhchiang): use a lazy-initialized mapping from
  //                 file_number to FileMetaData in Version.
246
  for (int level = 0; level < vstorage->num_levels(); ++level) {
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    for (auto file : vstorage->LevelFiles(level)) {
      auto iter = input_set->find(file->fd.GetNumber());
      if (iter != input_set->end()) {
        matched_input_files[level].files.push_back(file);
        input_set->erase(iter);
        last_non_empty_level = level;
        if (first_non_empty_level == -1) {
          first_non_empty_level = level;
        }
      }
    }
  }

  if (!input_set->empty()) {
    std::string message(
        "Cannot find matched SST files for the following file numbers:");
    for (auto fn : *input_set) {
      message += " ";
      message += std::to_string(fn);
    }
    return Status::InvalidArgument(message);
  }

  for (int level = first_non_empty_level;
       level <= last_non_empty_level; ++level) {
    matched_input_files[level].level = level;
    input_files->emplace_back(std::move(matched_input_files[level]));
  }

  return Status::OK();
}



I
Igor Canadi 已提交
281
// Returns true if any one of the parent files are being compacted
S
sdong 已提交
282
bool CompactionPicker::ParentRangeInCompaction(VersionStorageInfo* vstorage,
I
Igor Canadi 已提交
283 284 285 286 287 288
                                               const InternalKey* smallest,
                                               const InternalKey* largest,
                                               int level, int* parent_index) {
  std::vector<FileMetaData*> inputs;
  assert(level + 1 < NumberLevels());

S
sdong 已提交
289 290
  vstorage->GetOverlappingInputs(level + 1, smallest, largest, &inputs,
                                 *parent_index, parent_index);
I
Igor Canadi 已提交
291 292 293 294 295 296 297
  return FilesInCompaction(inputs);
}

// Populates the set of inputs from "level+1" that overlap with "level".
// Will also attempt to expand "level" if that doesn't expand "level+1"
// or cause "level" to include a file for compaction that has an overlapping
// user-key with another file.
298
void CompactionPicker::SetupOtherInputs(
S
sdong 已提交
299 300
    const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
    VersionStorageInfo* vstorage, Compaction* c) {
I
Igor Canadi 已提交
301 302 303 304 305 306 307 308 309 310 311
  // If inputs are empty, then there is nothing to expand.
  // If both input and output levels are the same, no need to consider
  // files at level "level+1"
  if (c->inputs_[0].empty() || c->level() == c->output_level()) {
    return;
  }

  const int level = c->level();
  InternalKey smallest, largest;

  // Get the range one last time.
312
  GetRange(c->inputs_[0].files, &smallest, &largest);
I
Igor Canadi 已提交
313 314

  // Populate the set of next-level files (inputs_[1]) to include in compaction
S
sdong 已提交
315 316 317
  vstorage->GetOverlappingInputs(level + 1, &smallest, &largest,
                                 &c->inputs_[1].files, c->parent_index_,
                                 &c->parent_index_);
I
Igor Canadi 已提交
318 319 320

  // Get entire range covered by compaction
  InternalKey all_start, all_limit;
321
  GetRange(c->inputs_[0].files, c->inputs_[1].files, &all_start, &all_limit);
I
Igor Canadi 已提交
322 323 324 325 326 327 328 329

  // See if we can further grow the number of inputs in "level" without
  // changing the number of "level+1" files we pick up. We also choose NOT
  // to expand if this would cause "level" to include some entries for some
  // user key, while excluding other entries for the same user key. This
  // can happen when one user key spans multiple files.
  if (!c->inputs_[1].empty()) {
    std::vector<FileMetaData*> expanded0;
S
sdong 已提交
330 331
    vstorage->GetOverlappingInputs(level, &all_start, &all_limit, &expanded0,
                                   c->base_index_, nullptr);
332 333
    const uint64_t inputs0_size = TotalCompensatedFileSize(c->inputs_[0].files);
    const uint64_t inputs1_size = TotalCompensatedFileSize(c->inputs_[1].files);
334
    const uint64_t expanded0_size = TotalCompensatedFileSize(expanded0);
335
    uint64_t limit = mutable_cf_options.ExpandedCompactionByteSizeLimit(level);
I
Igor Canadi 已提交
336 337 338
    if (expanded0.size() > c->inputs_[0].size() &&
        inputs1_size + expanded0_size < limit &&
        !FilesInCompaction(expanded0) &&
S
sdong 已提交
339
        !vstorage->HasOverlappingUserKey(&expanded0, level)) {
I
Igor Canadi 已提交
340 341 342
      InternalKey new_start, new_limit;
      GetRange(expanded0, &new_start, &new_limit);
      std::vector<FileMetaData*> expanded1;
S
sdong 已提交
343 344 345
      vstorage->GetOverlappingInputs(level + 1, &new_start, &new_limit,
                                     &expanded1, c->parent_index_,
                                     &c->parent_index_);
I
Igor Canadi 已提交
346 347
      if (expanded1.size() == c->inputs_[1].size() &&
          !FilesInCompaction(expanded1)) {
348
        Log(InfoLogLevel::INFO_LEVEL, ioptions_.info_log,
349 350
            "[%s] Expanding@%d %zu+%zu (%" PRIu64 "+%" PRIu64
            " bytes) to %zu+%zu (%" PRIu64 "+%" PRIu64 "bytes)\n",
S
sdong 已提交
351 352 353
            cf_name.c_str(), level, c->inputs_[0].size(), c->inputs_[1].size(),
            inputs0_size, inputs1_size, expanded0.size(), expanded1.size(),
            expanded0_size, inputs1_size);
I
Igor Canadi 已提交
354 355
        smallest = new_start;
        largest = new_limit;
356 357 358 359
        c->inputs_[0].files = expanded0;
        c->inputs_[1].files = expanded1;
        GetRange(c->inputs_[0].files, c->inputs_[1].files,
                 &all_start, &all_limit);
I
Igor Canadi 已提交
360 361 362 363 364 365 366
      }
    }
  }

  // Compute the set of grandparent files that overlap this compaction
  // (parent == level+1; grandparent == level+2)
  if (level + 2 < NumberLevels()) {
S
sdong 已提交
367 368
    vstorage->GetOverlappingInputs(level + 2, &all_start, &all_limit,
                                   &c->grandparents_);
I
Igor Canadi 已提交
369 370 371
  }
}

372
Compaction* CompactionPicker::CompactRange(
S
sdong 已提交
373 374 375
    const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
    VersionStorageInfo* vstorage, int input_level, int output_level,
    uint32_t output_path_id, const InternalKey* begin, const InternalKey* end,
376
    InternalKey** compaction_end) {
I
Igor Canadi 已提交
377
  // CompactionPickerFIFO has its own implementation of compact range
378
  assert(ioptions_.compaction_style != kCompactionStyleFIFO);
I
Igor Canadi 已提交
379

I
Igor Canadi 已提交
380 381 382 383 384
  std::vector<FileMetaData*> inputs;
  bool covering_the_whole_range = true;

  // All files are 'overlapping' in universal style compaction.
  // We have to compact the entire range in one shot.
385
  if (ioptions_.compaction_style == kCompactionStyleUniversal) {
I
Igor Canadi 已提交
386 387 388
    begin = nullptr;
    end = nullptr;
  }
S
sdong 已提交
389
  vstorage->GetOverlappingInputs(input_level, begin, end, &inputs);
I
Igor Canadi 已提交
390 391 392 393 394 395 396 397 398
  if (inputs.empty()) {
    return nullptr;
  }

  // Avoid compacting too much in one shot in case the range is large.
  // But we cannot do this for level-0 since level-0 files can overlap
  // and we must not pick one file and drop another older file if the
  // two files overlap.
  if (input_level > 0) {
399 400
    const uint64_t limit = mutable_cf_options.MaxFileSizeForLevel(input_level) *
      mutable_cf_options.source_compaction_factor;
I
Igor Canadi 已提交
401 402
    uint64_t total = 0;
    for (size_t i = 0; i + 1 < inputs.size(); ++i) {
403
      uint64_t s = inputs[i]->compensated_file_size;
I
Igor Canadi 已提交
404 405 406 407 408 409 410 411 412
      total += s;
      if (total >= limit) {
        **compaction_end = inputs[i + 1]->smallest;
        covering_the_whole_range = false;
        inputs.resize(i + 1);
        break;
      }
    }
  }
413
  assert(output_path_id < static_cast<uint32_t>(ioptions_.db_paths.size()));
414
  Compaction* c = new Compaction(
415
      vstorage->num_levels(), input_level, output_level,
416 417
      mutable_cf_options.MaxFileSizeForLevel(output_level),
      mutable_cf_options.MaxGrandParentOverlapBytes(input_level),
S
sdong 已提交
418
      output_path_id, GetCompressionType(ioptions_, output_level));
I
Igor Canadi 已提交
419

420
  c->inputs_[0].files = inputs;
S
sdong 已提交
421
  if (ExpandWhileOverlapping(cf_name, vstorage, c) == false) {
I
Igor Canadi 已提交
422
    delete c;
423
    Log(InfoLogLevel::WARN_LEVEL, ioptions_.info_log,
S
sdong 已提交
424
        "[%s] Could not compact due to expansion failure.\n", cf_name.c_str());
I
Igor Canadi 已提交
425 426 427
    return nullptr;
  }

S
sdong 已提交
428
  SetupOtherInputs(cf_name, mutable_cf_options, vstorage, c);
I
Igor Canadi 已提交
429 430 431 432 433 434 435 436 437 438 439

  if (covering_the_whole_range) {
    *compaction_end = nullptr;
  }

  // These files that are to be manaully compacted do not trample
  // upon other files because manual compactions are processed when
  // the system has a max of 1 background compaction thread.
  c->MarkFilesBeingCompacted(true);

  // Is this compaction creating a file at the bottommost level
S
sdong 已提交
440 441
  c->SetupBottomMostLevel(
      vstorage, true, ioptions_.compaction_style == kCompactionStyleUniversal);
442 443

  c->is_manual_compaction_ = true;
444
  c->mutable_cf_options_ = mutable_cf_options;
445

I
Igor Canadi 已提交
446 447 448
  return c;
}

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 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 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
namespace {
// Test whether two files have overlapping key-ranges.
bool HaveOverlappingKeyRanges(
    const Comparator* c,
    const SstFileMetaData& a, const SstFileMetaData& b) {
  if (c->Compare(a.smallestkey, b.smallestkey) >= 0) {
    if (c->Compare(a.smallestkey, b.largestkey) <= 0) {
      // b.smallestkey <= a.smallestkey <= b.largestkey
      return true;
    }
  } else if (c->Compare(a.largestkey, b.smallestkey) >= 0) {
    // a.smallestkey < b.smallestkey <= a.largestkey
    return true;
  }
  if (c->Compare(a.largestkey, b.largestkey) <= 0) {
    if (c->Compare(a.largestkey, b.smallestkey) >= 0) {
      // b.smallestkey <= a.largestkey <= b.largestkey
      return true;
    }
  } else if (c->Compare(a.smallestkey, b.largestkey) <= 0) {
    // a.smallestkey <= b.largestkey < a.largestkey
    return true;
  }
  return false;
}
}  // namespace

Status CompactionPicker::SanitizeCompactionInputFilesForAllLevels(
      std::unordered_set<uint64_t>* input_files,
      const ColumnFamilyMetaData& cf_meta,
      const int output_level) const {
  auto& levels = cf_meta.levels;
  auto comparator = icmp_->user_comparator();

  // TODO(yhchiang): If there is any input files of L1 or up and there
  // is at least one L0 files. All L0 files older than the L0 file needs
  // to be included. Otherwise, it is a false conditoin

  // TODO(yhchiang): add is_adjustable to CompactionOptions

  // the smallest and largest key of the current compaction input
  std::string smallestkey;
  std::string largestkey;
  // a flag for initializing smallest and largest key
  bool is_first = false;
  const int kNotFound = -1;

  // For each level, it does the following things:
  // 1. Find the first and the last compaction input files
  //    in the current level.
  // 2. Include all files between the first and the last
  //    compaction input files.
  // 3. Update the compaction key-range.
  // 4. For all remaining levels, include files that have
  //    overlapping key-range with the compaction key-range.
  for (int l = 0; l <= output_level; ++l) {
    auto& current_files = levels[l].files;
    int first_included = static_cast<int>(current_files.size());
    int last_included = kNotFound;

    // identify the first and the last compaction input files
    // in the current level.
    for (size_t f = 0; f < current_files.size(); ++f) {
      if (input_files->find(TableFileNameToNumber(current_files[f].name)) !=
          input_files->end()) {
        first_included = std::min(first_included, static_cast<int>(f));
        last_included = std::max(last_included, static_cast<int>(f));
        if (is_first == false) {
          smallestkey = current_files[f].smallestkey;
          largestkey = current_files[f].largestkey;
          is_first = true;
        }
      }
    }
    if (last_included == kNotFound) {
      continue;
    }

    if (l != 0) {
      // expend the compaction input of the current level if it
      // has overlapping key-range with other non-compaction input
      // files in the same level.
      while (first_included > 0) {
        if (comparator->Compare(
                current_files[first_included - 1].largestkey,
                current_files[first_included].smallestkey) < 0) {
          break;
        }
        first_included--;
      }

      while (last_included < static_cast<int>(current_files.size()) - 1) {
        if (comparator->Compare(
                current_files[last_included + 1].smallestkey,
                current_files[last_included].largestkey) > 0) {
          break;
        }
        last_included++;
      }
    }

    // include all files between the first and the last compaction input files.
    for (int f = first_included; f <= last_included; ++f) {
      if (current_files[f].being_compacted) {
        return Status::Aborted(
            "Necessary compaction input file " + current_files[f].name +
            " is currently being compacted.");
      }
      input_files->insert(
          TableFileNameToNumber(current_files[f].name));
    }

    // update smallest and largest key
    if (l == 0) {
      for (int f = first_included; f <= last_included; ++f) {
        if (comparator->Compare(
            smallestkey, current_files[f].smallestkey) > 0) {
          smallestkey = current_files[f].smallestkey;
        }
        if (comparator->Compare(
            largestkey, current_files[f].largestkey) < 0) {
          largestkey = current_files[f].largestkey;
        }
      }
    } else {
      if (comparator->Compare(
          smallestkey, current_files[first_included].smallestkey) > 0) {
        smallestkey = current_files[first_included].smallestkey;
      }
      if (comparator->Compare(
          largestkey, current_files[last_included].largestkey) < 0) {
        largestkey = current_files[last_included].largestkey;
      }
    }

    SstFileMetaData aggregated_file_meta;
    aggregated_file_meta.smallestkey = smallestkey;
    aggregated_file_meta.largestkey = largestkey;

    // For all lower levels, include all overlapping files.
    for (int m = l + 1; m <= output_level; ++m) {
      for (auto& next_lv_file : levels[m].files) {
        if (HaveOverlappingKeyRanges(
            comparator, aggregated_file_meta, next_lv_file)) {
          if (next_lv_file.being_compacted) {
            return Status::Aborted(
                "File " + next_lv_file.name +
                " that has overlapping key range with one of the compaction "
                " input file is currently being compacted.");
          }
          input_files->insert(
              TableFileNameToNumber(next_lv_file.name));
        }
      }
    }
  }
  return Status::OK();
}

Status CompactionPicker::SanitizeCompactionInputFiles(
    std::unordered_set<uint64_t>* input_files,
    const ColumnFamilyMetaData& cf_meta,
    const int output_level) const {
  assert(static_cast<int>(cf_meta.levels.size()) - 1 ==
         cf_meta.levels[cf_meta.levels.size() - 1].level);
  if (output_level >= static_cast<int>(cf_meta.levels.size())) {
    return Status::InvalidArgument(
        "Output level for column family " + cf_meta.name +
        " must between [0, " +
        std::to_string(cf_meta.levels[cf_meta.levels.size() - 1].level) +
        "].");
  }

  if (output_level > MaxOutputLevel()) {
    return Status::InvalidArgument(
        "Exceed the maximum output level defined by "
        "the current compaction algorithm --- " +
            std::to_string(MaxOutputLevel()));
  }

  if (output_level < 0) {
    return Status::InvalidArgument(
        "Output level cannot be negative.");
  }

  if (input_files->size() == 0) {
    return Status::InvalidArgument(
        "A compaction must contain at least one file.");
  }

  Status s = SanitizeCompactionInputFilesForAllLevels(
      input_files, cf_meta, output_level);

  if (!s.ok()) {
    return s;
  }

  // for all input files, check whether the file number matches
  // any currently-existing files.
  for (auto file_num : *input_files) {
    bool found = false;
    for (auto level_meta : cf_meta.levels) {
      for (auto file_meta : level_meta.files) {
        if (file_num == TableFileNameToNumber(file_meta.name)) {
          if (file_meta.being_compacted) {
            return Status::Aborted(
                "Specified compaction input file " +
                MakeTableFileName("", file_num) +
                " is already being compacted.");
          }
          found = true;
          break;
        }
      }
      if (found) {
        break;
      }
    }
    if (!found) {
      return Status::InvalidArgument(
          "Specified compaction input file " +
          MakeTableFileName("", file_num) +
          " does not exist in column family " + cf_meta.name + ".");
    }
  }

  return Status::OK();
}

678
Compaction* LevelCompactionPicker::PickCompaction(
S
sdong 已提交
679 680
    const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
    VersionStorageInfo* vstorage, LogBuffer* log_buffer) {
I
Igor Canadi 已提交
681 682 683
  Compaction* c = nullptr;
  int level = -1;

684 685 686 687
  // Compute the compactions needed. It is better to do it here
  // and also in LogAndApply(), otherwise the values could be stale.
  std::vector<uint64_t> size_being_compacted(NumberLevels() - 1);
  SizeBeingCompacted(size_being_compacted);
S
sdong 已提交
688 689 690 691

  CompactionOptionsFIFO dummy_compaction_options_fifo;
  vstorage->ComputeCompactionScore(
      mutable_cf_options, dummy_compaction_options_fifo, size_being_compacted);
692

I
Igor Canadi 已提交
693 694 695 696 697
  // We prefer compactions triggered by too much data in a level over
  // the compactions triggered by seeks.
  //
  // Find the compactions by size on all levels.
  for (int i = 0; i < NumberLevels() - 1; i++) {
S
sdong 已提交
698 699 700 701 702 703 704
    double score = vstorage->CompactionScore(i);
    level = vstorage->CompactionScoreLevel(i);
    assert(i == 0 || score <= vstorage->CompactionScore(i - 1));
    if ((score >= 1)) {
      c = PickCompactionBySize(mutable_cf_options, vstorage, level, score);
      if (c == nullptr ||
          ExpandWhileOverlapping(cf_name, vstorage, c) == false) {
I
Igor Canadi 已提交
705 706 707
        delete c;
        c = nullptr;
      } else {
I
Igor Canadi 已提交
708 709 710 711 712 713 714 715 716 717 718 719 720 721
        break;
      }
    }
  }

  if (c == nullptr) {
    return nullptr;
  }

  // Two level 0 compaction won't run at the same time, so don't need to worry
  // about files on level 0 being compacted.
  if (level == 0) {
    assert(compactions_in_progress_[0].empty());
    InternalKey smallest, largest;
722
    GetRange(c->inputs_[0].files, &smallest, &largest);
I
Igor Canadi 已提交
723 724 725 726
    // 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.
    c->inputs_[0].clear();
S
sdong 已提交
727 728
    vstorage->GetOverlappingInputs(0, &smallest, &largest,
                                   &c->inputs_[0].files);
I
Igor Canadi 已提交
729 730 731 732

    // If we include more L0 files in the same compaction run it can
    // cause the 'smallest' and 'largest' key to get extended to a
    // larger range. So, re-invoke GetRange to get the new key range
733
    GetRange(c->inputs_[0].files, &smallest, &largest);
S
sdong 已提交
734
    if (ParentRangeInCompaction(vstorage, &smallest, &largest, level,
I
Igor Canadi 已提交
735 736 737 738 739 740 741 742
                                &c->parent_index_)) {
      delete c;
      return nullptr;
    }
    assert(!c->inputs_[0].empty());
  }

  // Setup "level+1" files (inputs_[1])
S
sdong 已提交
743
  SetupOtherInputs(cf_name, mutable_cf_options, vstorage, c);
I
Igor Canadi 已提交
744 745 746 747 748

  // mark all the files that are being compacted
  c->MarkFilesBeingCompacted(true);

  // Is this compaction creating a file at the bottommost level
S
sdong 已提交
749
  c->SetupBottomMostLevel(vstorage, false, false);
I
Igor Canadi 已提交
750 751 752 753

  // remember this currently undergoing compaction
  compactions_in_progress_[level].insert(c);

754
  c->mutable_cf_options_ = mutable_cf_options;
I
Igor Canadi 已提交
755 756 757
  return c;
}

758
Compaction* LevelCompactionPicker::PickCompactionBySize(
S
sdong 已提交
759 760
    const MutableCFOptions& mutable_cf_options, VersionStorageInfo* vstorage,
    int level, double score) {
I
Igor Canadi 已提交
761 762 763 764 765 766 767 768 769 770 771 772
  Compaction* c = nullptr;

  // level 0 files are overlapping. So we cannot pick more
  // than one concurrent compactions at this level. This
  // could be made better by looking at key-ranges that are
  // being compacted at level 0.
  if (level == 0 && compactions_in_progress_[level].size() == 1) {
    return nullptr;
  }

  assert(level >= 0);
  assert(level + 1 < NumberLevels());
773
  c = new Compaction(vstorage->num_levels(), level, level + 1,
774 775 776
                     mutable_cf_options.MaxFileSizeForLevel(level + 1),
                     mutable_cf_options.MaxGrandParentOverlapBytes(level), 0,
                     GetCompressionType(ioptions_, level + 1));
I
Igor Canadi 已提交
777 778 779 780
  c->score_ = score;

  // Pick the largest file in this level that is not already
  // being compacted
S
sdong 已提交
781 782
  const std::vector<int>& file_size = vstorage->FilesBySize(level);
  const std::vector<FileMetaData*>& level_files = vstorage->LevelFiles(level);
I
Igor Canadi 已提交
783 784 785 786

  // record the first file that is not yet compacted
  int nextIndex = -1;

S
sdong 已提交
787
  for (unsigned int i = vstorage->NextCompactionIndex(level);
I
Igor Canadi 已提交
788 789
       i < file_size.size(); i++) {
    int index = file_size[i];
790
    FileMetaData* f = level_files[index];
I
Igor Canadi 已提交
791

792
    assert((i == file_size.size() - 1) ||
S
sdong 已提交
793
           (i >= VersionStorageInfo::kNumberFilesToSort - 1) ||
794
           (f->compensated_file_size >=
795
            level_files[file_size[i + 1]]->compensated_file_size));
I
Igor Canadi 已提交
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810

    // do not pick a file to compact if it is being compacted
    // from n-1 level.
    if (f->being_compacted) {
      continue;
    }

    // remember the startIndex for the next call to PickCompaction
    if (nextIndex == -1) {
      nextIndex = i;
    }

    // Do not pick this file if its parents at level+1 are being compacted.
    // Maybe we can avoid redoing this work in SetupOtherInputs
    int parent_index = -1;
S
sdong 已提交
811 812
    if (ParentRangeInCompaction(vstorage, &f->smallest, &f->largest, level,
                                &parent_index)) {
I
Igor Canadi 已提交
813 814
      continue;
    }
815
    c->inputs_[0].files.push_back(f);
I
Igor Canadi 已提交
816 817 818 819 820 821 822 823 824 825 826
    c->base_index_ = index;
    c->parent_index_ = parent_index;
    break;
  }

  if (c->inputs_[0].empty()) {
    delete c;
    c = nullptr;
  }

  // store where to start the iteration in the next call to PickCompaction
S
sdong 已提交
827
  vstorage->SetNextCompactionIndex(level, nextIndex);
I
Igor Canadi 已提交
828 829 830 831 832 833 834

  return c;
}

// Universal style of compaction. Pick files that are contiguous in
// time-range to compact.
//
835
Compaction* UniversalCompactionPicker::PickCompaction(
S
sdong 已提交
836 837
    const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
    VersionStorageInfo* vstorage, LogBuffer* log_buffer) {
838
  const int kLevel0 = 0;
S
sdong 已提交
839 840
  double score = vstorage->CompactionScore(kLevel0);
  const std::vector<FileMetaData*>& level_files = vstorage->LevelFiles(kLevel0);
I
Igor Canadi 已提交
841

842
  if ((level_files.size() <
843
       (unsigned int)mutable_cf_options.level0_file_num_compaction_trigger)) {
S
sdong 已提交
844
    LogToBuffer(log_buffer, "[%s] Universal: nothing to do\n", cf_name.c_str());
I
Igor Canadi 已提交
845 846
    return nullptr;
  }
S
sdong 已提交
847
  VersionStorageInfo::FileSummaryStorage tmp;
848
  LogToBuffer(log_buffer, 3072, "[%s] Universal: candidate files(%zu): %s\n",
S
sdong 已提交
849 850
              cf_name.c_str(), level_files.size(),
              vstorage->LevelFileSummary(&tmp, kLevel0));
I
Igor Canadi 已提交
851 852

  // Check for size amplification first.
M
Mike Lin 已提交
853
  Compaction* c;
S
sdong 已提交
854 855
  if ((c = PickCompactionUniversalSizeAmp(cf_name, mutable_cf_options, vstorage,
                                          score, log_buffer)) != nullptr) {
I
Igor Canadi 已提交
856
    LogToBuffer(log_buffer, "[%s] Universal: compacting for size amp\n",
S
sdong 已提交
857
                cf_name.c_str());
M
Mike Lin 已提交
858
  } else {
I
Igor Canadi 已提交
859 860
    // Size amplification is within limits. Try reducing read
    // amplification while maintaining file size ratios.
861
    unsigned int ratio = ioptions_.compaction_options_universal.size_ratio;
I
Igor Canadi 已提交
862

S
sdong 已提交
863 864 865
    if ((c = PickCompactionUniversalReadAmp(cf_name, mutable_cf_options,
                                            vstorage, score, ratio, UINT_MAX,
                                            log_buffer)) != nullptr) {
I
Igor Canadi 已提交
866
      LogToBuffer(log_buffer, "[%s] Universal: compacting for size ratio\n",
S
sdong 已提交
867
                  cf_name.c_str());
M
Mike Lin 已提交
868 869 870 871 872
    } else {
      // Size amplification and file size ratios are within configured limits.
      // If max read amplification is exceeding configured limits, then force
      // compaction without looking at filesize ratios and try to reduce
      // the number of files to fewer than level0_file_num_compaction_trigger.
873
      unsigned int num_files = level_files.size() -
874
          mutable_cf_options.level0_file_num_compaction_trigger;
875
      if ((c = PickCompactionUniversalReadAmp(
S
sdong 已提交
876
               cf_name, mutable_cf_options, vstorage, score, UINT_MAX,
877
               num_files, log_buffer)) != nullptr) {
S
sdong 已提交
878 879 880
        LogToBuffer(log_buffer,
                    "[%s] Universal: compacting for file num -- %u\n",
                    cf_name.c_str(), num_files);
M
Mike Lin 已提交
881
      }
I
Igor Canadi 已提交
882 883 884 885 886
    }
  }
  if (c == nullptr) {
    return nullptr;
  }
887
  assert(c->inputs_[kLevel0].size() > 1);
I
Igor Canadi 已提交
888 889 890

  // validate that all the chosen files are non overlapping in time
  FileMetaData* newerfile __attribute__((unused)) = nullptr;
891 892
  for (unsigned int i = 0; i < c->inputs_[kLevel0].size(); i++) {
    FileMetaData* f = c->inputs_[kLevel0][i];
I
Igor Canadi 已提交
893 894 895 896 897 898 899
    assert (f->smallest_seqno <= f->largest_seqno);
    assert(newerfile == nullptr ||
           newerfile->smallest_seqno > f->largest_seqno);
    newerfile = f;
  }

  // Is the earliest file part of this compaction?
900 901
  FileMetaData* last_file = level_files.back();
  c->bottommost_level_ = c->inputs_[kLevel0].files.back() == last_file;
I
Igor Canadi 已提交
902

I
Igor Canadi 已提交
903
  // update statistics
904
  MeasureTime(ioptions_.statistics,
905
              NUM_FILES_IN_SINGLE_COMPACTION, c->inputs_[kLevel0].size());
I
Igor Canadi 已提交
906

I
Igor Canadi 已提交
907 908 909 910
  // mark all the files that are being compacted
  c->MarkFilesBeingCompacted(true);

  // remember this currently undergoing compaction
911
  compactions_in_progress_[kLevel0].insert(c);
I
Igor Canadi 已提交
912 913 914

  // Record whether this compaction includes all sst files.
  // For now, it is only relevant in universal compaction mode.
915
  c->is_full_compaction_ = (c->inputs_[kLevel0].size() == level_files.size());
I
Igor Canadi 已提交
916

917
  c->mutable_cf_options_ = mutable_cf_options;
I
Igor Canadi 已提交
918 919 920
  return c;
}

921 922
uint32_t UniversalCompactionPicker::GetPathId(
    const ImmutableCFOptions& ioptions, uint64_t file_size) {
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
  // Two conditions need to be satisfied:
  // (1) the target path needs to be able to hold the file's size
  // (2) Total size left in this and previous paths need to be not
  //     smaller than expected future file size before this new file is
  //     compacted, which is estimated based on size_ratio.
  // For example, if now we are compacting files of size (1, 1, 2, 4, 8),
  // we will make sure the target file, probably with size of 16, will be
  // placed in a path so that eventually when new files are generated and
  // compacted to (1, 1, 2, 4, 8, 16), all those files can be stored in or
  // before the path we chose.
  //
  // TODO(sdong): now the case of multiple column families is not
  // considered in this algorithm. So the target size can be violated in
  // that case. We need to improve it.
  uint64_t accumulated_size = 0;
938 939
  uint64_t future_size = file_size *
    (100 - ioptions.compaction_options_universal.size_ratio) / 100;
940
  uint32_t p = 0;
941 942
  for (; p < ioptions.db_paths.size() - 1; p++) {
    uint64_t target_size = ioptions.db_paths[p].target_size;
943 944 945 946 947 948 949 950 951
    if (target_size > file_size &&
        accumulated_size + (target_size - file_size) > future_size) {
      return p;
    }
    accumulated_size += target_size;
  }
  return p;
}

I
Igor Canadi 已提交
952 953 954 955 956
//
// Consider compaction files based on their size differences with
// the next file in time order.
//
Compaction* UniversalCompactionPicker::PickCompactionUniversalReadAmp(
S
sdong 已提交
957 958
    const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
    VersionStorageInfo* vstorage, double score, unsigned int ratio,
959
    unsigned int max_number_of_files_to_compact, LogBuffer* log_buffer) {
960
  const int kLevel0 = 0;
I
Igor Canadi 已提交
961 962

  unsigned int min_merge_width =
963
    ioptions_.compaction_options_universal.min_merge_width;
I
Igor Canadi 已提交
964
  unsigned int max_merge_width =
965
    ioptions_.compaction_options_universal.max_merge_width;
I
Igor Canadi 已提交
966 967

  // The files are sorted from newest first to oldest last.
S
sdong 已提交
968
  const auto& files = vstorage->LevelFiles(kLevel0);
969

I
Igor Canadi 已提交
970 971 972
  FileMetaData* f = nullptr;
  bool done = false;
  int start_index = 0;
I
Igor Canadi 已提交
973
  unsigned int candidate_count = 0;
I
Igor Canadi 已提交
974 975 976 977 978 979 980

  unsigned int max_files_to_compact = std::min(max_merge_width,
                                       max_number_of_files_to_compact);
  min_merge_width = std::max(min_merge_width, 2U);

  // Considers a candidate file only if it is smaller than the
  // total size accumulated so far.
981
  for (unsigned int loop = 0; loop < files.size(); loop++) {
I
Igor Canadi 已提交
982 983 984 985

    candidate_count = 0;

    // Skip files that are already being compacted
986 987
    for (f = nullptr; loop < files.size(); loop++) {
      f = files[loop];
I
Igor Canadi 已提交
988 989 990 991 992

      if (!f->being_compacted) {
        candidate_count = 1;
        break;
      }
993 994
      LogToBuffer(log_buffer, "[%s] Universal: file %" PRIu64
                              "[%d] being compacted, skipping",
S
sdong 已提交
995
                  cf_name.c_str(), f->fd.GetNumber(), loop);
I
Igor Canadi 已提交
996 997 998 999 1000
      f = nullptr;
    }

    // This file is not being compacted. Consider it as the
    // first candidate to be compacted.
1001
    uint64_t candidate_size =  f != nullptr? f->compensated_file_size : 0;
I
Igor Canadi 已提交
1002
    if (f != nullptr) {
1003 1004 1005 1006
      char file_num_buf[kFormatFileNumberBufSize];
      FormatFileNumber(f->fd.GetNumber(), f->fd.GetPathId(), file_num_buf,
                       sizeof(file_num_buf));
      LogToBuffer(log_buffer, "[%s] Universal: Possible candidate file %s[%d].",
S
sdong 已提交
1007
                  cf_name.c_str(), file_num_buf, loop);
I
Igor Canadi 已提交
1008 1009 1010
    }

    // Check if the suceeding files need compaction.
1011 1012
    for (unsigned int i = loop + 1;
         candidate_count < max_files_to_compact && i < files.size(); i++) {
I
Igor Canadi 已提交
1013 1014
      FileMetaData* suceeding_file = files[i];
      if (suceeding_file->being_compacted) {
I
Igor Canadi 已提交
1015 1016
        break;
      }
1017
      // Pick files if the total/last candidate file size (increased by the
I
Igor Canadi 已提交
1018
      // specified ratio) is still larger than the next candidate file.
1019 1020 1021 1022
      // candidate_size is the total size of files picked so far with the
      // default kCompactionStopStyleTotalSize; with
      // kCompactionStopStyleSimilarSize, it's simply the size of the last
      // picked file.
1023
      double sz = candidate_size * (100.0 + ratio) / 100.0;
I
Igor Canadi 已提交
1024
      if (sz < static_cast<double>(suceeding_file->fd.GetFileSize())) {
I
Igor Canadi 已提交
1025
        break;
1026
      }
1027 1028
      if (ioptions_.compaction_options_universal.stop_style ==
          kCompactionStopStyleSimilarSize) {
1029 1030
        // Similar-size stopping rule: also check the last picked file isn't
        // far larger than the next candidate file.
I
Igor Canadi 已提交
1031
        sz = (suceeding_file->fd.GetFileSize() * (100.0 + ratio)) / 100.0;
1032
        if (sz < static_cast<double>(candidate_size)) {
1033 1034 1035 1036 1037 1038
          // If the small file we've encountered begins a run of similar-size
          // files, we'll pick them up on a future iteration of the outer
          // loop. If it's some lonely straggler, it'll eventually get picked
          // by the last-resort read amp strategy which disregards size ratios.
          break;
        }
I
Igor Canadi 已提交
1039 1040 1041
        candidate_size = suceeding_file->compensated_file_size;
      } else {  // default kCompactionStopStyleTotalSize
        candidate_size += suceeding_file->compensated_file_size;
I
Igor Canadi 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
      }
      candidate_count++;
    }

    // Found a series of consecutive files that need compaction.
    if (candidate_count >= (unsigned int)min_merge_width) {
      start_index = loop;
      done = true;
      break;
    } else {
      for (unsigned int i = loop;
1053
           i < loop + candidate_count && i < files.size(); i++) {
I
Igor Canadi 已提交
1054
        FileMetaData* skipping_file = files[i];
1055 1056 1057
        LogToBuffer(log_buffer, "[%s] Universal: Skipping file %" PRIu64
                                "[%d] with size %" PRIu64
                                " (compensated size %" PRIu64 ") %d\n",
I
Igor Canadi 已提交
1058 1059 1060 1061
                    cf_name.c_str(), f->fd.GetNumber(), i,
                    skipping_file->fd.GetFileSize(),
                    skipping_file->compensated_file_size,
                    skipping_file->being_compacted);
I
Igor Canadi 已提交
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
      }
    }
  }
  if (!done || candidate_count <= 1) {
    return nullptr;
  }
  unsigned int first_index_after = start_index + candidate_count;
  // Compression is enabled if files compacted earlier already reached
  // size ratio of compression.
  bool enable_compression = true;
  int ratio_to_compress =
1073
      ioptions_.compaction_options_universal.compression_size_percent;
I
Igor Canadi 已提交
1074
  if (ratio_to_compress >= 0) {
S
sdong 已提交
1075
    uint64_t total_size = vstorage->NumLevelBytes(kLevel0);
I
Igor Canadi 已提交
1076
    uint64_t older_file_size = 0;
1077 1078 1079
    for (unsigned int i = files.size() - 1;
         i >= first_index_after; i--) {
      older_file_size += files[i]->fd.GetFileSize();
I
Igor Canadi 已提交
1080 1081 1082 1083 1084 1085
      if (older_file_size * 100L >= total_size * (long) ratio_to_compress) {
        enable_compression = false;
        break;
      }
    }
  }
1086 1087 1088 1089 1090

  uint64_t estimated_total_size = 0;
  for (unsigned int i = 0; i < first_index_after; i++) {
    estimated_total_size += files[i]->fd.GetFileSize();
  }
1091
  uint32_t path_id = GetPathId(ioptions_, estimated_total_size);
1092

S
sdong 已提交
1093
  Compaction* c = new Compaction(
1094
      vstorage->num_levels(), kLevel0, kLevel0,
S
sdong 已提交
1095 1096
      mutable_cf_options.MaxFileSizeForLevel(kLevel0), LLONG_MAX, path_id,
      GetCompressionType(ioptions_, kLevel0, enable_compression));
I
Igor Canadi 已提交
1097 1098 1099
  c->score_ = score;

  for (unsigned int i = start_index; i < first_index_after; i++) {
I
Igor Canadi 已提交
1100 1101
    FileMetaData* picking_file = files[i];
    c->inputs_[0].files.push_back(picking_file);
1102
    char file_num_buf[kFormatFileNumberBufSize];
I
Igor Canadi 已提交
1103 1104
    FormatFileNumber(picking_file->fd.GetNumber(), picking_file->fd.GetPathId(),
                     file_num_buf, sizeof(file_num_buf));
1105
    LogToBuffer(log_buffer,
1106
                "[%s] Universal: Picking file %s[%d] "
1107
                "with size %" PRIu64 " (compensated size %" PRIu64 ")\n",
I
Igor Canadi 已提交
1108 1109 1110
                cf_name.c_str(), file_num_buf, i,
                picking_file->fd.GetFileSize(),
                picking_file->compensated_file_size);
I
Igor Canadi 已提交
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
  }
  return c;
}

// Look at overall size amplification. If size amplification
// exceeeds the configured value, then do a compaction
// of the candidate files all the way upto the earliest
// base file (overrides configured values of file-size ratios,
// min_merge_width and max_merge_width).
//
Compaction* UniversalCompactionPicker::PickCompactionUniversalSizeAmp(
S
sdong 已提交
1122 1123
    const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
    VersionStorageInfo* vstorage, double score, LogBuffer* log_buffer) {
1124
  const int kLevel = 0;
I
Igor Canadi 已提交
1125 1126

  // percentage flexibilty while reducing size amplification
1127
  uint64_t ratio = ioptions_.compaction_options_universal.
I
Igor Canadi 已提交
1128 1129 1130
                     max_size_amplification_percent;

  // The files are sorted from newest first to oldest last.
S
sdong 已提交
1131
  const auto& files = vstorage->LevelFiles(kLevel);
I
Igor Canadi 已提交
1132 1133 1134 1135 1136 1137 1138

  unsigned int candidate_count = 0;
  uint64_t candidate_size = 0;
  unsigned int start_index = 0;
  FileMetaData* f = nullptr;

  // Skip files that are already being compacted
1139 1140
  for (unsigned int loop = 0; loop < files.size() - 1; loop++) {
    f = files[loop];
I
Igor Canadi 已提交
1141 1142 1143 1144
    if (!f->being_compacted) {
      start_index = loop;         // Consider this as the first candidate.
      break;
    }
1145 1146 1147
    char file_num_buf[kFormatFileNumberBufSize];
    FormatFileNumber(f->fd.GetNumber(), f->fd.GetPathId(), file_num_buf,
                     sizeof(file_num_buf));
1148
    LogToBuffer(log_buffer, "[%s] Universal: skipping file %s[%d] compacted %s",
S
sdong 已提交
1149
                cf_name.c_str(), file_num_buf, loop,
1150
                " cannot be a candidate to reduce size amp.\n");
I
Igor Canadi 已提交
1151 1152
    f = nullptr;
  }
1153

I
Igor Canadi 已提交
1154 1155 1156 1157
  if (f == nullptr) {
    return nullptr;             // no candidate files
  }

1158 1159 1160
  char file_num_buf[kFormatFileNumberBufSize];
  FormatFileNumber(f->fd.GetNumber(), f->fd.GetPathId(), file_num_buf,
                   sizeof(file_num_buf));
1161
  LogToBuffer(log_buffer, "[%s] Universal: First candidate file %s[%d] %s",
S
sdong 已提交
1162
              cf_name.c_str(), file_num_buf, start_index,
1163
              " to reduce size amp.\n");
I
Igor Canadi 已提交
1164 1165

  // keep adding up all the remaining files
1166 1167
  for (unsigned int loop = start_index; loop < files.size() - 1; loop++) {
    f = files[loop];
I
Igor Canadi 已提交
1168
    if (f->being_compacted) {
1169 1170
      FormatFileNumber(f->fd.GetNumber(), f->fd.GetPathId(), file_num_buf,
                       sizeof(file_num_buf));
1171
      LogToBuffer(
1172
          log_buffer, "[%s] Universal: Possible candidate file %s[%d] %s.",
S
sdong 已提交
1173
          cf_name.c_str(), file_num_buf, loop,
I
Igor Canadi 已提交
1174 1175 1176
          " is already being compacted. No size amp reduction possible.\n");
      return nullptr;
    }
1177
    candidate_size += f->compensated_file_size;
I
Igor Canadi 已提交
1178 1179 1180 1181 1182 1183 1184
    candidate_count++;
  }
  if (candidate_count == 0) {
    return nullptr;
  }

  // size of earliest file
1185
  uint64_t earliest_file_size = files.back()->fd.GetFileSize();
I
Igor Canadi 已提交
1186 1187 1188

  // size amplification = percentage of additional size
  if (candidate_size * 100 < ratio * earliest_file_size) {
I
Igor Canadi 已提交
1189 1190
    LogToBuffer(
        log_buffer,
1191 1192
        "[%s] Universal: size amp not needed. newer-files-total-size %" PRIu64
        "earliest-file-size %" PRIu64,
S
sdong 已提交
1193
        cf_name.c_str(), candidate_size, earliest_file_size);
I
Igor Canadi 已提交
1194 1195
    return nullptr;
  } else {
1196 1197 1198 1199
    LogToBuffer(
        log_buffer,
        "[%s] Universal: size amp needed. newer-files-total-size %" PRIu64
        "earliest-file-size %" PRIu64,
S
sdong 已提交
1200
        cf_name.c_str(), candidate_size, earliest_file_size);
I
Igor Canadi 已提交
1201
  }
1202
  assert(start_index < files.size() - 1);
I
Igor Canadi 已提交
1203

1204 1205 1206 1207 1208
  // Estimate total file size
  uint64_t estimated_total_size = 0;
  for (unsigned int loop = start_index; loop < files.size(); loop++) {
    estimated_total_size += files[loop]->fd.GetFileSize();
  }
1209
  uint32_t path_id = GetPathId(ioptions_, estimated_total_size);
1210

I
Igor Canadi 已提交
1211 1212 1213
  // create a compaction request
  // We always compact all the files, so always compress.
  Compaction* c =
1214
      new Compaction(vstorage->num_levels(), kLevel, kLevel,
S
sdong 已提交
1215 1216
                     mutable_cf_options.MaxFileSizeForLevel(kLevel), LLONG_MAX,
                     path_id, GetCompressionType(ioptions_, kLevel));
I
Igor Canadi 已提交
1217
  c->score_ = score;
1218
  for (unsigned int loop = start_index; loop < files.size(); loop++) {
1219
    f = files[loop];
1220
    c->inputs_[0].files.push_back(f);
1221
    LogToBuffer(log_buffer,
S
sdong 已提交
1222 1223 1224 1225 1226
                "[%s] Universal: size amp picking file %" PRIu64
                "[%d] "
                "with size %" PRIu64 " (compensated size %" PRIu64 ")",
                cf_name.c_str(), f->fd.GetNumber(), loop, f->fd.GetFileSize(),
                f->compensated_file_size);
I
Igor Canadi 已提交
1227 1228 1229 1230
  }
  return c;
}

1231
Compaction* FIFOCompactionPicker::PickCompaction(
S
sdong 已提交
1232 1233
    const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
    VersionStorageInfo* vstorage, LogBuffer* log_buffer) {
1234
  assert(vstorage->num_levels() == 1);
1235
  const int kLevel0 = 0;
S
sdong 已提交
1236
  const std::vector<FileMetaData*>& level_files = vstorage->LevelFiles(kLevel0);
I
Igor Canadi 已提交
1237
  uint64_t total_size = 0;
1238
  for (const auto& file : level_files) {
1239
    total_size += file->compensated_file_size;
I
Igor Canadi 已提交
1240 1241
  }

1242
  if (total_size <= ioptions_.compaction_options_fifo.max_table_files_size ||
1243
      level_files.size() == 0) {
I
Igor Canadi 已提交
1244 1245 1246 1247
    // total size not exceeded
    LogToBuffer(log_buffer,
                "[%s] FIFO compaction: nothing to do. Total size %" PRIu64
                ", max size %" PRIu64 "\n",
S
sdong 已提交
1248
                cf_name.c_str(), total_size,
1249
                ioptions_.compaction_options_fifo.max_table_files_size);
I
Igor Canadi 已提交
1250 1251 1252 1253 1254 1255 1256
    return nullptr;
  }

  if (compactions_in_progress_[0].size() > 0) {
    LogToBuffer(log_buffer,
                "[%s] FIFO compaction: Already executing compaction. No need "
                "to run parallel compactions since compactions are very fast",
S
sdong 已提交
1257
                cf_name.c_str());
I
Igor Canadi 已提交
1258 1259 1260
    return nullptr;
  }

S
sdong 已提交
1261
  Compaction* c = new Compaction(1, 0, 0, 0, 0, 0, kNoCompression, false,
I
Igor Canadi 已提交
1262 1263
                                 true /* is deletion compaction */);
  // delete old files (FIFO)
1264
  for (auto ritr = level_files.rbegin(); ritr != level_files.rend(); ++ritr) {
I
Igor Canadi 已提交
1265
    auto f = *ritr;
1266
    total_size -= f->compensated_file_size;
1267
    c->inputs_[0].files.push_back(f);
I
Igor Canadi 已提交
1268
    char tmp_fsize[16];
1269
    AppendHumanBytes(f->fd.GetFileSize(), tmp_fsize, sizeof(tmp_fsize));
I
Igor Canadi 已提交
1270 1271
    LogToBuffer(log_buffer, "[%s] FIFO compaction: picking file %" PRIu64
                            " with size %s for deletion",
S
sdong 已提交
1272
                cf_name.c_str(), f->fd.GetNumber(), tmp_fsize);
1273
    if (total_size <= ioptions_.compaction_options_fifo.max_table_files_size) {
I
Igor Canadi 已提交
1274 1275 1276 1277 1278 1279
      break;
    }
  }

  c->MarkFilesBeingCompacted(true);
  compactions_in_progress_[0].insert(c);
1280
  c->mutable_cf_options_ = mutable_cf_options;
I
Igor Canadi 已提交
1281 1282 1283
  return c;
}

1284
Compaction* FIFOCompactionPicker::CompactRange(
S
sdong 已提交
1285 1286
    const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
    VersionStorageInfo* vstorage, int input_level, int output_level,
1287 1288
    uint32_t output_path_id, const InternalKey* begin, const InternalKey* end,
    InternalKey** compaction_end) {
I
Igor Canadi 已提交
1289 1290 1291
  assert(input_level == 0);
  assert(output_level == 0);
  *compaction_end = nullptr;
1292
  LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL, ioptions_.info_log);
S
sdong 已提交
1293 1294
  Compaction* c =
      PickCompaction(cf_name, mutable_cf_options, vstorage, &log_buffer);
1295
  if (c != nullptr) {
1296
    assert(output_path_id < static_cast<uint32_t>(ioptions_.db_paths.size()));
1297 1298
    c->output_path_id_ = output_path_id;
  }
I
Igor Canadi 已提交
1299 1300 1301 1302
  log_buffer.FlushBufferToLog();
  return c;
}

I
Igor Canadi 已提交
1303
}  // namespace rocksdb