db_impl_open.cc 68.5 KB
Newer Older
S
Siying Dong 已提交
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
S
Siying Dong 已提交
5 6 7 8
//
// 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.
9
#include <cinttypes>
S
Siying Dong 已提交
10 11

#include "db/builder.h"
12
#include "db/db_impl/db_impl.h"
13
#include "db/error_handler.h"
14
#include "db/periodic_work_scheduler.h"
15
#include "env/composite_env_wrapper.h"
16
#include "file/read_write_util.h"
17
#include "file/sst_file_manager_impl.h"
18
#include "file/writable_file_writer.h"
19
#include "monitoring/persistent_stats_history.h"
20
#include "options/options_helper.h"
21
#include "rocksdb/table.h"
S
Siying Dong 已提交
22
#include "rocksdb/wal_filter.h"
23
#include "test_util/sync_point.h"
24
#include "util/rate_limiter.h"
S
Siying Dong 已提交
25

26
namespace ROCKSDB_NAMESPACE {
27
Options SanitizeOptions(const std::string& dbname, const Options& src) {
S
Siying Dong 已提交
28 29 30 31 32 33 34 35 36 37
  auto db_options = SanitizeOptions(dbname, DBOptions(src));
  ImmutableDBOptions immutable_db_options(db_options);
  auto cf_options =
      SanitizeOptions(immutable_db_options, ColumnFamilyOptions(src));
  return Options(db_options, cf_options);
}

DBOptions SanitizeOptions(const std::string& dbname, const DBOptions& src) {
  DBOptions result(src);

38 39
  if (result.env == nullptr) {
    result.env = Env::Default();
40 41
  }

S
Siying Dong 已提交
42 43 44 45
  // result.max_open_files means an "infinite" open files.
  if (result.max_open_files != -1) {
    int max_max_open_files = port::GetMaxOpenFiles();
    if (max_max_open_files == -1) {
L
Leonidas Galanis 已提交
46
      max_max_open_files = 0x400000;
S
Siying Dong 已提交
47 48
    }
    ClipToRange(&result.max_open_files, 20, max_max_open_files);
49 50
    TEST_SYNC_POINT_CALLBACK("SanitizeOptions::AfterChangeMaxOpenFiles",
                             &result.max_open_files);
S
Siying Dong 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64
  }

  if (result.info_log == nullptr) {
    Status s = CreateLoggerFromOptions(dbname, result, &result.info_log);
    if (!s.ok()) {
      // No place suitable for logging
      result.info_log = nullptr;
    }
  }

  if (!result.write_buffer_manager) {
    result.write_buffer_manager.reset(
        new WriteBufferManager(result.db_write_buffer_size));
  }
65 66 67
  auto bg_job_limits = DBImpl::GetBGJobLimits(
      result.max_background_flushes, result.max_background_compactions,
      result.max_background_jobs, true /* parallelize_compactions */);
68
  result.env->IncBackgroundThreadsIfNeeded(bg_job_limits.max_compactions,
S
Siying Dong 已提交
69
                                           Env::Priority::LOW);
70
  result.env->IncBackgroundThreadsIfNeeded(bg_job_limits.max_flushes,
S
Siying Dong 已提交
71 72 73 74 75 76 77 78
                                           Env::Priority::HIGH);

  if (result.rate_limiter.get() != nullptr) {
    if (result.bytes_per_sync == 0) {
      result.bytes_per_sync = 1024 * 1024;
    }
  }

79 80 81 82 83 84 85 86 87
  if (result.delayed_write_rate == 0) {
    if (result.rate_limiter.get() != nullptr) {
      result.delayed_write_rate = result.rate_limiter->GetBytesPerSecond();
    }
    if (result.delayed_write_rate == 0) {
      result.delayed_write_rate = 16 * 1024 * 1024;
    }
  }

S
Siying Dong 已提交
88 89 90 91 92
  if (result.WAL_ttl_seconds > 0 || result.WAL_size_limit_MB > 0) {
    result.recycle_log_file_num = false;
  }

  if (result.recycle_log_file_num &&
93 94 95
      (result.wal_recovery_mode ==
           WALRecoveryMode::kTolerateCorruptedTailRecords ||
       result.wal_recovery_mode == WALRecoveryMode::kPointInTimeRecovery ||
S
Siying Dong 已提交
96
       result.wal_recovery_mode == WALRecoveryMode::kAbsoluteConsistency)) {
97 98 99 100 101 102 103 104 105 106 107 108
    // - kTolerateCorruptedTailRecords is inconsistent with recycle log file
    //   feature. WAL recycling expects recovery success upon encountering a
    //   corrupt record at the point where new data ends and recycled data
    //   remains at the tail. However, `kTolerateCorruptedTailRecords` must fail
    //   upon encountering any such corrupt record, as it cannot differentiate
    //   between this and a real corruption, which would cause committed updates
    //   to be truncated -- a violation of the recovery guarantee.
    // - kPointInTimeRecovery and kAbsoluteConsistency are incompatible with
    //   recycle log file feature temporarily due to a bug found introducing a
    //   hole in the recovered data
    //   (https://github.com/facebook/rocksdb/pull/7252#issuecomment-673766236).
    //   Besides this bug, we believe the features are fundamentally compatible.
109
    result.recycle_log_file_num = 0;
S
Siying Dong 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123
  }

  if (result.wal_dir.empty()) {
    // Use dbname as default
    result.wal_dir = dbname;
  }
  if (result.wal_dir.back() == '/') {
    result.wal_dir = result.wal_dir.substr(0, result.wal_dir.size() - 1);
  }

  if (result.db_paths.size() == 0) {
    result.db_paths.emplace_back(dbname, std::numeric_limits<uint64_t>::max());
  }

124
  if (result.use_direct_reads && result.compaction_readahead_size == 0) {
125
    TEST_SYNC_POINT_CALLBACK("SanitizeOptions:direct_io", nullptr);
S
Siying Dong 已提交
126 127 128
    result.compaction_readahead_size = 1024 * 1024 * 2;
  }

129
  if (result.compaction_readahead_size > 0 || result.use_direct_reads) {
S
Siying Dong 已提交
130 131 132 133 134 135 136 137 138 139
    result.new_table_reader_for_compaction_inputs = true;
  }

  // Force flush on DB open if 2PC is enabled, since with 2PC we have no
  // guarantee that consecutive log files have consecutive sequence id, which
  // make recovery complicated.
  if (result.allow_2pc) {
    result.avoid_flush_during_recovery = false;
  }

140
#ifndef ROCKSDB_LITE
141 142 143 144 145 146 147 148 149
  ImmutableDBOptions immutable_db_options(result);
  if (!IsWalDirSameAsDBPath(&immutable_db_options)) {
    // Either the WAL dir and db_paths[0]/db_name are not the same, or we
    // cannot tell for sure. In either case, assume they're different and
    // explicitly cleanup the trash log files (bypass DeleteScheduler)
    // Do this first so even if we end up calling
    // DeleteScheduler::CleanupDirectory on the same dir later, it will be
    // safe
    std::vector<std::string> filenames;
150
    result.env->GetChildren(result.wal_dir, &filenames).PermitUncheckedError();
151
    for (std::string& filename : filenames) {
152 153 154
      if (filename.find(".log.trash", filename.length() -
                                          std::string(".log.trash").length()) !=
          std::string::npos) {
155
        std::string trash_file = result.wal_dir + "/" + filename;
156
        result.env->DeleteFile(trash_file).PermitUncheckedError();
157 158 159
      }
    }
  }
160 161 162 163 164 165 166 167 168
  // When the DB is stopped, it's possible that there are some .trash files that
  // were not deleted yet, when we open the DB we will find these .trash files
  // and schedule them to be deleted (or delete immediately if SstFileManager
  // was not used)
  auto sfm = static_cast<SstFileManagerImpl*>(result.sst_file_manager.get());
  for (size_t i = 0; i < result.db_paths.size(); i++) {
    DeleteScheduler::CleanupDirectory(result.env, sfm, result.db_paths[i].path);
  }

169 170 171 172 173 174 175 176
  // Create a default SstFileManager for purposes of tracking compaction size
  // and facilitating recovery from out of space errors.
  if (result.sst_file_manager.get() == nullptr) {
    std::shared_ptr<SstFileManager> sst_file_manager(
        NewSstFileManager(result.env, result.info_log));
    result.sst_file_manager = sst_file_manager;
  }
#endif
177 178 179 180 181 182 183

  if (!result.paranoid_checks) {
    result.skip_checking_sst_file_sizes_on_db_open = true;
    ROCKS_LOG_INFO(result.info_log,
                   "file size check will be skipped during open.");
  }

S
Siying Dong 已提交
184 185 186 187
  return result;
}

namespace {
188
Status ValidateOptionsByTable(
S
Siying Dong 已提交
189 190 191 192
    const DBOptions& db_opts,
    const std::vector<ColumnFamilyDescriptor>& column_families) {
  Status s;
  for (auto cf : column_families) {
193
    s = ValidateOptions(db_opts, cf.options);
S
Siying Dong 已提交
194 195 196 197 198 199
    if (!s.ok()) {
      return s;
    }
  }
  return Status::OK();
}
200
}  // namespace
S
Siying Dong 已提交
201

202
Status DBImpl::ValidateOptions(
S
Siying Dong 已提交
203 204 205 206
    const DBOptions& db_options,
    const std::vector<ColumnFamilyDescriptor>& column_families) {
  Status s;
  for (auto& cfd : column_families) {
207
    s = ColumnFamilyData::ValidateOptions(db_options, cfd.options);
S
Siying Dong 已提交
208 209 210 211
    if (!s.ok()) {
      return s;
    }
  }
212 213 214
  s = ValidateOptions(db_options);
  return s;
}
S
Siying Dong 已提交
215

216
Status DBImpl::ValidateOptions(const DBOptions& db_options) {
S
Siying Dong 已提交
217 218 219 220 221 222 223 224 225 226 227 228
  if (db_options.db_paths.size() > 4) {
    return Status::NotSupported(
        "More than four DB paths are not supported yet. ");
  }

  if (db_options.allow_mmap_reads && db_options.use_direct_reads) {
    // Protect against assert in PosixMMapReadableFile constructor
    return Status::NotSupported(
        "If memory mapped reads (allow_mmap_reads) are enabled "
        "then direct I/O reads (use_direct_reads) must be disabled. ");
  }

229 230
  if (db_options.allow_mmap_writes &&
      db_options.use_direct_io_for_flush_and_compaction) {
S
Siying Dong 已提交
231 232
    return Status::NotSupported(
        "If memory mapped writes (allow_mmap_writes) are enabled "
233 234
        "then direct I/O writes (use_direct_io_for_flush_and_compaction) must "
        "be disabled. ");
S
Siying Dong 已提交
235 236 237 238 239 240
  }

  if (db_options.keep_log_file_num == 0) {
    return Status::InvalidArgument("keep_log_file_num must be greater than 0");
  }

M
Maysam Yabandeh 已提交
241 242 243 244 245 246 247 248 249 250 251
  if (db_options.unordered_write &&
      !db_options.allow_concurrent_memtable_write) {
    return Status::InvalidArgument(
        "unordered_write is incompatible with !allow_concurrent_memtable_write");
  }

  if (db_options.unordered_write && db_options.enable_pipelined_write) {
    return Status::InvalidArgument(
        "unordered_write is incompatible with enable_pipelined_write");
  }

252 253 254 255 256
  if (db_options.atomic_flush && db_options.enable_pipelined_write) {
    return Status::InvalidArgument(
        "atomic_flush is incompatible with enable_pipelined_write");
  }

257 258 259 260 261 262
  // TODO remove this restriction
  if (db_options.atomic_flush && db_options.best_efforts_recovery) {
    return Status::InvalidArgument(
        "atomic_flush is currently incompatible with best-efforts recovery");
  }

S
Siying Dong 已提交
263 264
  return Status::OK();
}
265

266
Status DBImpl::NewDB(std::vector<std::string>* new_filenames) {
S
Siying Dong 已提交
267
  VersionEdit new_db;
268 269 270 271 272 273 274 275 276
  Status s = SetIdentityFile(env_, dbname_);
  if (!s.ok()) {
    return s;
  }
  if (immutable_db_options_.write_dbid_to_manifest) {
    std::string temp_db_id;
    GetDbIdentityFromIdentityFile(&temp_db_id);
    new_db.SetDBId(temp_db_id);
  }
S
Siying Dong 已提交
277 278 279 280 281 282 283
  new_db.SetLogNumber(0);
  new_db.SetNextFile(2);
  new_db.SetLastSequence(0);

  ROCKS_LOG_INFO(immutable_db_options_.info_log, "Creating manifest 1 \n");
  const std::string manifest = DescriptorFileName(dbname_, 1);
  {
284 285 286
    std::unique_ptr<FSWritableFile> file;
    FileOptions file_options = fs_->OptimizeForManifestWrite(file_options_);
    s = NewWritableFile(fs_.get(), manifest, &file, file_options);
S
Siying Dong 已提交
287 288 289 290 291
    if (!s.ok()) {
      return s;
    }
    file->SetPreallocationBlockSize(
        immutable_db_options_.manifest_preallocation_size);
292
    std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
293 294
        std::move(file), manifest, file_options, env_, io_tracer_,
        nullptr /* stats */, immutable_db_options_.listeners));
S
Siying Dong 已提交
295 296 297 298 299 300 301 302 303 304
    log::Writer log(std::move(file_writer), 0, false);
    std::string record;
    new_db.EncodeTo(&record);
    s = log.AddRecord(record);
    if (s.ok()) {
      s = SyncManifest(env_, &immutable_db_options_, log.file());
    }
  }
  if (s.ok()) {
    // Make "CURRENT" file that points to the new manifest file.
305
    s = SetCurrentFile(fs_.get(), dbname_, 1, directories_.GetDbDir());
306 307 308 309
    if (new_filenames) {
      new_filenames->emplace_back(
          manifest.substr(manifest.find_last_of("/\\") + 1));
    }
S
Siying Dong 已提交
310
  } else {
311
    fs_->DeleteFile(manifest, IOOptions(), nullptr);
S
Siying Dong 已提交
312 313 314 315
  }
  return s;
}

316 317 318
IOStatus DBImpl::CreateAndNewDirectory(
    FileSystem* fs, const std::string& dirname,
    std::unique_ptr<FSDirectory>* directory) {
S
Siying Dong 已提交
319 320 321 322 323 324 325
  // We call CreateDirIfMissing() as the directory may already exist (if we
  // are reopening a DB), when this happens we don't want creating the
  // directory to cause an error. However, we need to check if creating the
  // directory fails or else we may get an obscure message about the lock
  // file not existing. One real-world example of this occurring is if
  // env->CreateDirIfMissing() doesn't create intermediate directories, e.g.
  // when dbname_ is "dir/db" but when "dir" doesn't exist.
326 327 328
  IOStatus io_s = fs->CreateDirIfMissing(dirname, IOOptions(), nullptr);
  if (!io_s.ok()) {
    return io_s;
S
Siying Dong 已提交
329
  }
330
  return fs->NewDirectory(dirname, IOOptions(), directory, nullptr);
S
Siying Dong 已提交
331 332
}

333 334 335 336 337 338
IOStatus Directories::SetDirectories(FileSystem* fs, const std::string& dbname,
                                     const std::string& wal_dir,
                                     const std::vector<DbPath>& data_paths) {
  IOStatus io_s = DBImpl::CreateAndNewDirectory(fs, dbname, &db_dir_);
  if (!io_s.ok()) {
    return io_s;
S
Siying Dong 已提交
339 340
  }
  if (!wal_dir.empty() && dbname != wal_dir) {
341 342 343
    io_s = DBImpl::CreateAndNewDirectory(fs, wal_dir, &wal_dir_);
    if (!io_s.ok()) {
      return io_s;
S
Siying Dong 已提交
344 345 346 347 348 349 350 351 352
    }
  }

  data_dirs_.clear();
  for (auto& p : data_paths) {
    const std::string db_path = p.path;
    if (db_path == dbname) {
      data_dirs_.emplace_back(nullptr);
    } else {
353 354 355 356
      std::unique_ptr<FSDirectory> path_directory;
      io_s = DBImpl::CreateAndNewDirectory(fs, db_path, &path_directory);
      if (!io_s.ok()) {
        return io_s;
S
Siying Dong 已提交
357 358 359 360 361
      }
      data_dirs_.emplace_back(path_directory.release());
    }
  }
  assert(data_dirs_.size() == data_paths.size());
362
  return IOStatus::OK();
S
Siying Dong 已提交
363 364 365 366
}

Status DBImpl::Recover(
    const std::vector<ColumnFamilyDescriptor>& column_families, bool read_only,
367
    bool error_if_wal_file_exists, bool error_if_data_exists_in_wals,
368
    uint64_t* recovered_seq) {
S
Siying Dong 已提交
369 370 371 372
  mutex_.AssertHeld();

  bool is_new_db = false;
  assert(db_lock_ == nullptr);
373
  std::vector<std::string> files_in_dbname;
S
Siying Dong 已提交
374
  if (!read_only) {
375
    Status s = directories_.SetDirectories(fs_.get(), dbname_,
S
Siying Dong 已提交
376 377 378 379 380 381 382 383 384 385 386
                                           immutable_db_options_.wal_dir,
                                           immutable_db_options_.db_paths);
    if (!s.ok()) {
      return s;
    }

    s = env_->LockFile(LockFileName(dbname_), &db_lock_);
    if (!s.ok()) {
      return s;
    }

Y
Yanqin Jin 已提交
387
    std::string current_fname = CurrentFileName(dbname_);
388 389 390 391 392 393 394 395 396
    // Path to any MANIFEST file in the db dir. It does not matter which one.
    // Since best-efforts recovery ignores CURRENT file, existence of a
    // MANIFEST indicates the recovery to recover existing db. If no MANIFEST
    // can be found, a new db will be created.
    std::string manifest_path;
    if (!immutable_db_options_.best_efforts_recovery) {
      s = env_->FileExists(current_fname);
    } else {
      s = Status::NotFound();
397 398 399 400 401 402
      Status io_s = env_->GetChildren(dbname_, &files_in_dbname);
      if (!io_s.ok()) {
        s = io_s;
        files_in_dbname.clear();
      }
      for (const std::string& file : files_in_dbname) {
403
        uint64_t number = 0;
404
        FileType type = kWalFile;  // initialize
405 406 407 408 409 410 411 412 413
        if (ParseFileName(file, &number, &type) && type == kDescriptorFile) {
          // Found MANIFEST (descriptor log), thus best-efforts recovery does
          // not have to treat the db as empty.
          s = Status::OK();
          manifest_path = dbname_ + "/" + file;
          break;
        }
      }
    }
S
Siying Dong 已提交
414 415
    if (s.IsNotFound()) {
      if (immutable_db_options_.create_if_missing) {
416
        s = NewDB(&files_in_dbname);
S
Siying Dong 已提交
417 418 419 420 421 422
        is_new_db = true;
        if (!s.ok()) {
          return s;
        }
      } else {
        return Status::InvalidArgument(
Y
Yanqin Jin 已提交
423
            current_fname, "does not exist (create_if_missing is false)");
S
Siying Dong 已提交
424 425 426
      }
    } else if (s.ok()) {
      if (immutable_db_options_.error_if_exists) {
427 428
        return Status::InvalidArgument(dbname_,
                                       "exists (error_if_exists is true)");
S
Siying Dong 已提交
429 430 431 432 433 434
      }
    } else {
      // Unexpected error reading file
      assert(s.IsIOError());
      return s;
    }
435
    // Verify compatibility of file_options_ and filesystem
436
    {
437 438 439
      std::unique_ptr<FSRandomAccessFile> idfile;
      FileOptions customized_fs(file_options_);
      customized_fs.use_direct_reads |=
440
          immutable_db_options_.use_direct_io_for_flush_and_compaction;
441 442 443
      const std::string& fname =
          manifest_path.empty() ? current_fname : manifest_path;
      s = fs_->NewRandomAccessFile(fname, customized_fs, &idfile, nullptr);
444
      if (!s.ok()) {
445
        std::string error_str = s.ToString();
446
        // Check if unsupported Direct I/O is the root cause
447
        customized_fs.use_direct_reads = false;
448
        s = fs_->NewRandomAccessFile(fname, customized_fs, &idfile, nullptr);
449 450 451 452 453
        if (s.ok()) {
          return Status::InvalidArgument(
              "Direct I/O is not supported by the specified DB.");
        } else {
          return Status::InvalidArgument(
454
              "Found options incompatible with filesystem", error_str.c_str());
455 456 457
        }
      }
    }
458 459 460 461 462 463 464 465 466 467
  } else if (immutable_db_options_.best_efforts_recovery) {
    assert(files_in_dbname.empty());
    Status s = env_->GetChildren(dbname_, &files_in_dbname);
    if (s.IsNotFound()) {
      return Status::InvalidArgument(dbname_,
                                     "does not exist (open for read only)");
    } else if (s.IsIOError()) {
      return s;
    }
    assert(s.ok());
S
Siying Dong 已提交
468
  }
469
  assert(db_id_.empty());
470 471 472 473 474
  Status s;
  bool missing_table_file = false;
  if (!immutable_db_options_.best_efforts_recovery) {
    s = versions_->Recover(column_families, read_only, &db_id_);
  } else {
475 476 477
    assert(!files_in_dbname.empty());
    s = versions_->TryRecover(column_families, read_only, files_in_dbname,
                              &db_id_, &missing_table_file);
478
    if (s.ok()) {
479 480 481
      // TryRecover may delete previous column_family_set_.
      column_family_memtables_.reset(
          new ColumnFamilyMemTablesImpl(versions_->GetColumnFamilySet()));
482
      s = FinishBestEffortsRecovery();
483 484
    }
  }
485 486 487 488 489 490 491
  if (!s.ok()) {
    return s;
  }
  // Happens when immutable_db_options_.write_dbid_to_manifest is set to true
  // the very first time.
  if (db_id_.empty()) {
    // Check for the IDENTITY file and create it if not there.
492
    s = fs_->FileExists(IdentityFileName(dbname_), IOOptions(), nullptr);
493 494 495 496 497 498 499 500 501 502 503 504
    // Typically Identity file is created in NewDB() and for some reason if
    // it is no longer available then at this point DB ID is not in Identity
    // file or Manifest.
    if (s.IsNotFound()) {
      s = SetIdentityFile(env_, dbname_);
      if (!s.ok()) {
        return s;
      }
    } else if (!s.ok()) {
      assert(s.IsIOError());
      return s;
    }
505 506
    s = GetDbIdentityFromIdentityFile(&db_id_);
    if (immutable_db_options_.write_dbid_to_manifest && s.ok()) {
507 508 509 510 511
      VersionEdit edit;
      edit.SetDBId(db_id_);
      Options options;
      MutableCFOptions mutable_cf_options(options);
      versions_->db_id_ = db_id_;
512
      s = versions_->LogAndApply(versions_->GetColumnFamilySet()->GetDefault(),
513 514 515 516
                             mutable_cf_options, &edit, &mutex_, nullptr,
                             false);
    }
  } else {
517
    s = SetIdentityFile(env_, dbname_, db_id_);
518
  }
519

S
Siying Dong 已提交
520 521 522
  if (immutable_db_options_.paranoid_checks && s.ok()) {
    s = CheckConsistency();
  }
523
  if (s.ok() && !read_only) {
524
    std::map<std::string, std::shared_ptr<FSDirectory>> created_dirs;
525
    for (auto cfd : *versions_->GetColumnFamilySet()) {
526
      s = cfd->AddDirectories(&created_dirs);
527 528 529 530 531
      if (!s.ok()) {
        return s;
      }
    }
  }
532 533 534 535
  // DB mutex is already held
  if (s.ok() && immutable_db_options_.persist_stats_to_disk) {
    s = InitPersistStatsColumnFamily();
  }
536

537
  std::vector<std::string> files_in_wal_dir;
S
Siying Dong 已提交
538
  if (s.ok()) {
539
    // Initial max_total_in_memory_state_ before recovery wals. Log recovery
540 541 542 543 544 545 546 547
    // may check this value to decide whether to flush.
    max_total_in_memory_state_ = 0;
    for (auto cfd : *versions_->GetColumnFamilySet()) {
      auto* mutable_cf_options = cfd->GetLatestMutableCFOptions();
      max_total_in_memory_state_ += mutable_cf_options->write_buffer_size *
                                    mutable_cf_options->max_write_buffer_number;
    }

S
Siying Dong 已提交
548 549 550 551
    SequenceNumber next_sequence(kMaxSequenceNumber);
    default_cf_handle_ = new ColumnFamilyHandleImpl(
        versions_->GetColumnFamilySet()->GetDefault(), this, &mutex_);
    default_cf_internal_stats_ = default_cf_handle_->cfd()->internal_stats();
552 553
    // TODO(Zhongyi): handle single_column_family_mode_ when
    // persistent_stats is enabled
S
Siying Dong 已提交
554 555 556 557 558 559 560 561 562 563
    single_column_family_mode_ =
        versions_->GetColumnFamilySet()->NumberOfColumnFamilies() == 1;

    // Recover from all newer log files than the ones named in the
    // descriptor (new log files may have been added by the previous
    // incarnation without registering them in the descriptor).
    //
    // Note that prev_log_number() is no longer used, but we pay
    // attention to it in case we are recovering a database
    // produced by an older version of rocksdb.
564
    if (!immutable_db_options_.best_efforts_recovery) {
565
      s = env_->GetChildren(immutable_db_options_.wal_dir, &files_in_wal_dir);
566
    }
567 568 569 570
    if (s.IsNotFound()) {
      return Status::InvalidArgument("wal_dir not found",
                                     immutable_db_options_.wal_dir);
    } else if (!s.ok()) {
S
Siying Dong 已提交
571 572 573
      return s;
    }

574
    std::unordered_map<uint64_t, std::string> wal_files;
575
    for (const auto& file : files_in_wal_dir) {
S
Siying Dong 已提交
576 577
      uint64_t number;
      FileType type;
578
      if (ParseFileName(file, &number, &type) && type == kWalFile) {
S
Siying Dong 已提交
579 580 581 582
        if (is_new_db) {
          return Status::Corruption(
              "While creating a new Db, wal_dir contains "
              "existing log file: ",
583
              file);
S
Siying Dong 已提交
584
        } else {
585 586
          wal_files[number] =
              LogFileName(immutable_db_options_.wal_dir, number);
S
Siying Dong 已提交
587 588 589 590
        }
      }
    }

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    if (immutable_db_options_.track_and_verify_wals_in_manifest) {
      // Verify WALs in MANIFEST.
      s = versions_->GetWalSet().CheckWals(env_, wal_files);
    } else if (!versions_->GetWalSet().GetWals().empty()) {
      // Tracking is disabled, clear previously tracked WALs from MANIFEST,
      // otherwise, in the future, if WAL tracking is enabled again,
      // since the WALs deleted when WAL tracking is disabled are not persisted
      // into MANIFEST, WAL check may fail.
      VersionEdit edit;
      for (const auto& wal : versions_->GetWalSet().GetWals()) {
        WalNumber number = wal.first;
        edit.DeleteWal(number);
      }
      s = versions_->LogAndApplyToDefaultColumnFamily(&edit, &mutex_);
    }
    if (!s.ok()) {
      return s;
    }

    if (!wal_files.empty()) {
611
      if (error_if_wal_file_exists) {
S
Siying Dong 已提交
612
        return Status::Corruption(
613 614 615
            "The db was opened in readonly mode with error_if_wal_file_exists"
            "flag but a WAL file already exists");
      } else if (error_if_data_exists_in_wals) {
616
        for (auto& wal_file : wal_files) {
S
Siying Dong 已提交
617
          uint64_t bytes;
618
          s = env_->GetFileSize(wal_file.second, &bytes);
S
Siying Dong 已提交
619 620 621
          if (s.ok()) {
            if (bytes > 0) {
              return Status::Corruption(
622 623
                  "error_if_data_exists_in_wals is set but there are data "
                  " in WAL files.");
S
Siying Dong 已提交
624 625 626 627 628 629
            }
          }
        }
      }
    }

630 631 632 633 634 635 636 637 638 639 640 641 642
    if (!wal_files.empty()) {
      // Recover in the order in which the wals were generated
      std::vector<uint64_t> wals;
      wals.reserve(wal_files.size());
      for (const auto& wal_file : wal_files) {
        wals.push_back(wal_file.first);
      }
      std::sort(wals.begin(), wals.end());

      bool corrupted_wal_found = false;
      s = RecoverLogFiles(wals, &next_sequence, read_only,
                          &corrupted_wal_found);
      if (corrupted_wal_found && recovered_seq != nullptr) {
643 644
        *recovered_seq = next_sequence;
      }
S
Siying Dong 已提交
645 646 647 648 649 650 651 652 653 654
      if (!s.ok()) {
        // Clear memtables if recovery failed
        for (auto cfd : *versions_->GetColumnFamilySet()) {
          cfd->CreateNewMemtable(*cfd->GetLatestMutableCFOptions(),
                                 kMaxSequenceNumber);
        }
      }
    }
  }

655 656 657 658 659
  if (read_only) {
    // If we are opening as read-only, we need to update options_file_number_
    // to reflect the most recent OPTIONS file. It does not matter for regular
    // read-write db instance because options_file_number_ will later be
    // updated to versions_->NewFileNumber() in RenameTempFileToOptionsFile.
660
    std::vector<std::string> filenames;
661
    if (s.ok()) {
662 663 664 665 666 667 668 669 670 671
      const std::string normalized_dbname = NormalizePath(dbname_);
      const std::string normalized_wal_dir =
          NormalizePath(immutable_db_options_.wal_dir);
      if (immutable_db_options_.best_efforts_recovery) {
        filenames = std::move(files_in_dbname);
      } else if (normalized_dbname == normalized_wal_dir) {
        filenames = std::move(files_in_wal_dir);
      } else {
        s = env_->GetChildren(GetName(), &filenames);
      }
672 673 674 675 676
    }
    if (s.ok()) {
      uint64_t number = 0;
      uint64_t options_file_number = 0;
      FileType type;
677
      for (const auto& fname : filenames) {
678 679 680 681 682 683 684
        if (ParseFileName(fname, &number, &type) && type == kOptionsFile) {
          options_file_number = std::max(number, options_file_number);
        }
      }
      versions_->options_file_number_ = options_file_number;
    }
  }
S
Siying Dong 已提交
685 686 687
  return s;
}

688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
Status DBImpl::PersistentStatsProcessFormatVersion() {
  mutex_.AssertHeld();
  Status s;
  // persist version when stats CF doesn't exist
  bool should_persist_format_version = !persistent_stats_cfd_exists_;
  mutex_.Unlock();
  if (persistent_stats_cfd_exists_) {
    // Check persistent stats format version compatibility. Drop and recreate
    // persistent stats CF if format version is incompatible
    uint64_t format_version_recovered = 0;
    Status s_format = DecodePersistentStatsVersionNumber(
        this, StatsVersionKeyType::kFormatVersion, &format_version_recovered);
    uint64_t compatible_version_recovered = 0;
    Status s_compatible = DecodePersistentStatsVersionNumber(
        this, StatsVersionKeyType::kCompatibleVersion,
        &compatible_version_recovered);
    // abort reading from existing stats CF if any of following is true:
    // 1. failed to read format version or compatible version from disk
    // 2. sst's format version is greater than current format version, meaning
    // this sst is encoded with a newer RocksDB release, and current compatible
    // version is below the sst's compatible version
    if (!s_format.ok() || !s_compatible.ok() ||
        (kStatsCFCurrentFormatVersion < format_version_recovered &&
         kStatsCFCompatibleFormatVersion < compatible_version_recovered)) {
      if (!s_format.ok() || !s_compatible.ok()) {
713
        ROCKS_LOG_WARN(
714
            immutable_db_options_.info_log,
715 716 717
            "Recreating persistent stats column family since reading "
            "persistent stats version key failed. Format key: %s, compatible "
            "key: %s",
718 719
            s_format.ToString().c_str(), s_compatible.ToString().c_str());
      } else {
720
        ROCKS_LOG_WARN(
721
            immutable_db_options_.info_log,
722 723 724 725 726 727 728 729
            "Recreating persistent stats column family due to corrupted or "
            "incompatible format version. Recovered format: %" PRIu64
            "; recovered format compatible since: %" PRIu64 "\n",
            format_version_recovered, compatible_version_recovered);
      }
      s = DropColumnFamily(persist_stats_cf_handle_);
      if (s.ok()) {
        s = DestroyColumnFamilyHandle(persist_stats_cf_handle_);
730 731
      }
      ColumnFamilyHandle* handle = nullptr;
732 733 734 735 736 737 738 739 740 741
      if (s.ok()) {
        ColumnFamilyOptions cfo;
        OptimizeForPersistentStats(&cfo);
        s = CreateColumnFamily(cfo, kPersistentStatsColumnFamilyName, &handle);
      }
      if (s.ok()) {
        persist_stats_cf_handle_ = static_cast<ColumnFamilyHandleImpl*>(handle);
        // should also persist version here because old stats CF is discarded
        should_persist_format_version = true;
      }
742 743
    }
  }
744
  if (should_persist_format_version) {
745 746 747
    // Persistent stats CF being created for the first time, need to write
    // format version key
    WriteBatch batch;
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    if (s.ok()) {
      s = batch.Put(persist_stats_cf_handle_, kFormatVersionKeyString,
                    ToString(kStatsCFCurrentFormatVersion));
    }
    if (s.ok()) {
      s = batch.Put(persist_stats_cf_handle_, kCompatibleVersionKeyString,
                    ToString(kStatsCFCompatibleFormatVersion));
    }
    if (s.ok()) {
      WriteOptions wo;
      wo.low_pri = true;
      wo.no_slowdown = true;
      wo.sync = false;
      s = Write(wo, &batch);
    }
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
  }
  mutex_.Lock();
  return s;
}

Status DBImpl::InitPersistStatsColumnFamily() {
  mutex_.AssertHeld();
  assert(!persist_stats_cf_handle_);
  ColumnFamilyData* persistent_stats_cfd =
      versions_->GetColumnFamilySet()->GetColumnFamily(
          kPersistentStatsColumnFamilyName);
  persistent_stats_cfd_exists_ = persistent_stats_cfd != nullptr;

  Status s;
  if (persistent_stats_cfd != nullptr) {
    // We are recovering from a DB which already contains persistent stats CF,
    // the CF is already created in VersionSet::ApplyOneVersionEdit, but
    // column family handle was not. Need to explicitly create handle here.
    persist_stats_cf_handle_ =
        new ColumnFamilyHandleImpl(persistent_stats_cfd, this, &mutex_);
  } else {
    mutex_.Unlock();
    ColumnFamilyHandle* handle = nullptr;
    ColumnFamilyOptions cfo;
    OptimizeForPersistentStats(&cfo);
    s = CreateColumnFamily(cfo, kPersistentStatsColumnFamilyName, &handle);
    persist_stats_cf_handle_ = static_cast<ColumnFamilyHandleImpl*>(handle);
    mutex_.Lock();
  }
  return s;
}

795 796
// REQUIRES: wal_numbers are sorted in ascending order
Status DBImpl::RecoverLogFiles(const std::vector<uint64_t>& wal_numbers,
797
                               SequenceNumber* next_sequence, bool read_only,
798
                               bool* corrupted_wal_found) {
S
Siying Dong 已提交
799 800 801 802 803
  struct LogReporter : public log::Reader::Reporter {
    Env* env;
    Logger* info_log;
    const char* fname;
    Status* status;  // nullptr if immutable_db_options_.paranoid_checks==false
804
    void Corruption(size_t bytes, const Status& s) override {
S
Siying Dong 已提交
805
      ROCKS_LOG_WARN(info_log, "%s%s: dropping %d bytes; %s",
806 807 808 809
                     (status == nullptr ? "(ignoring error) " : ""), fname,
                     static_cast<int>(bytes), s.ToString().c_str());
      if (status != nullptr && status->ok()) {
        *status = s;
S
Siying Dong 已提交
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
      }
    }
  };

  mutex_.AssertHeld();
  Status status;
  std::unordered_map<int, VersionEdit> version_edits;
  // no need to refcount because iteration is under mutex
  for (auto cfd : *versions_->GetColumnFamilySet()) {
    VersionEdit edit;
    edit.SetColumnFamily(cfd->GetID());
    version_edits.insert({cfd->GetID(), edit});
  }
  int job_id = next_job_id_.fetch_add(1);
  {
    auto stream = event_logger_.Log();
    stream << "job" << job_id << "event"
           << "recovery_started";
828
    stream << "wal_files";
S
Siying Dong 已提交
829
    stream.StartArray();
830 831
    for (auto wal_number : wal_numbers) {
      stream << wal_number;
S
Siying Dong 已提交
832 833 834 835 836 837 838 839 840
    }
    stream.EndArray();
  }

#ifndef ROCKSDB_LITE
  if (immutable_db_options_.wal_filter != nullptr) {
    std::map<std::string, uint32_t> cf_name_id_map;
    std::map<uint32_t, uint64_t> cf_lognumber_map;
    for (auto cfd : *versions_->GetColumnFamilySet()) {
841
      cf_name_id_map.insert(std::make_pair(cfd->GetName(), cfd->GetID()));
S
Siying Dong 已提交
842
      cf_lognumber_map.insert(
843
          std::make_pair(cfd->GetID(), cfd->GetLogNumber()));
S
Siying Dong 已提交
844 845 846 847 848 849 850 851 852 853
    }

    immutable_db_options_.wal_filter->ColumnFamilyLogNumberMap(cf_lognumber_map,
                                                               cf_name_id_map);
  }
#endif

  bool stop_replay_by_wal_filter = false;
  bool stop_replay_for_corruption = false;
  bool flushed = false;
854 855 856 857
  uint64_t corrupted_wal_number = kMaxSequenceNumber;
  uint64_t min_wal_number = MinLogNumberToKeep();
  for (auto wal_number : wal_numbers) {
    if (wal_number < min_wal_number) {
S
Siying Dong 已提交
858 859 860
      ROCKS_LOG_INFO(immutable_db_options_.info_log,
                     "Skipping log #%" PRIu64
                     " since it is older than min log to keep #%" PRIu64,
861
                     wal_number, min_wal_number);
S
Siying Dong 已提交
862 863
      continue;
    }
S
Siying Dong 已提交
864 865 866
    // The previous incarnation may not have written any MANIFEST
    // records after allocating this log number.  So we manually
    // update the file number allocation counter in VersionSet.
867
    versions_->MarkFileNumberUsed(wal_number);
S
Siying Dong 已提交
868
    // Open the log file
869
    std::string fname = LogFileName(immutable_db_options_.wal_dir, wal_number);
S
Siying Dong 已提交
870 871

    ROCKS_LOG_INFO(immutable_db_options_.info_log,
872
                   "Recovering log #%" PRIu64 " mode %d", wal_number,
873
                   static_cast<int>(immutable_db_options_.wal_recovery_mode));
S
Siying Dong 已提交
874 875 876 877 878 879 880 881 882 883 884 885 886
    auto logFileDropped = [this, &fname]() {
      uint64_t bytes;
      if (env_->GetFileSize(fname, &bytes).ok()) {
        auto info_log = immutable_db_options_.info_log.get();
        ROCKS_LOG_WARN(info_log, "%s: dropping %d bytes", fname.c_str(),
                       static_cast<int>(bytes));
      }
    };
    if (stop_replay_by_wal_filter) {
      logFileDropped();
      continue;
    }

887
    std::unique_ptr<SequentialFileReader> file_reader;
S
Siying Dong 已提交
888
    {
889 890 891 892
      std::unique_ptr<FSSequentialFile> file;
      status = fs_->NewSequentialFile(fname,
                                      fs_->OptimizeForLogRead(file_options_),
                                      &file, nullptr);
S
Siying Dong 已提交
893 894 895 896 897 898 899 900 901 902
      if (!status.ok()) {
        MaybeIgnoreError(&status);
        if (!status.ok()) {
          return status;
        } else {
          // Fail with one log file, but that's ok.
          // Try next one.
          continue;
        }
      }
903
      file_reader.reset(new SequentialFileReader(
904 905
          std::move(file), fname, immutable_db_options_.log_readahead_size,
          io_tracer_));
S
Siying Dong 已提交
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    }

    // Create the log reader.
    LogReporter reporter;
    reporter.env = env_;
    reporter.info_log = immutable_db_options_.info_log.get();
    reporter.fname = fname.c_str();
    if (!immutable_db_options_.paranoid_checks ||
        immutable_db_options_.wal_recovery_mode ==
            WALRecoveryMode::kSkipAnyCorruptedRecords) {
      reporter.status = nullptr;
    } else {
      reporter.status = &status;
    }
    // We intentially make log::Reader do checksumming even if
    // paranoid_checks==false so that corruptions cause entire commits
    // to be skipped instead of propagating bad information (like overly
    // large sequence numbers).
    log::Reader reader(immutable_db_options_.info_log, std::move(file_reader),
925
                       &reporter, true /*checksum*/, wal_number);
S
Siying Dong 已提交
926 927 928 929 930 931 932

    // Determine if we should tolerate incomplete records at the tail end of the
    // Read all the records and add to a memtable
    std::string scratch;
    Slice record;
    WriteBatch batch;

933 934
    TEST_SYNC_POINT_CALLBACK("DBImpl::RecoverLogFiles:BeforeReadWal",
                             /*arg=*/nullptr);
S
Siying Dong 已提交
935 936 937 938 939 940 941 942 943
    while (!stop_replay_by_wal_filter &&
           reader.ReadRecord(&record, &scratch,
                             immutable_db_options_.wal_recovery_mode) &&
           status.ok()) {
      if (record.size() < WriteBatchInternal::kHeader) {
        reporter.Corruption(record.size(),
                            Status::Corruption("log record too small"));
        continue;
      }
944 945 946 947 948

      status = WriteBatchInternal::SetContents(&batch, record);
      if (!status.ok()) {
        return status;
      }
S
Siying Dong 已提交
949 950 951 952 953 954 955 956
      SequenceNumber sequence = WriteBatchInternal::Sequence(&batch);

      if (immutable_db_options_.wal_recovery_mode ==
          WALRecoveryMode::kPointInTimeRecovery) {
        // In point-in-time recovery mode, if sequence id of log files are
        // consecutive, we continue recovery despite corruption. This could
        // happen when we open and write to a corrupted DB, where sequence id
        // will start from the last sequence id we recovered.
957
        if (sequence == *next_sequence) {
S
Siying Dong 已提交
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
          stop_replay_for_corruption = false;
        }
        if (stop_replay_for_corruption) {
          logFileDropped();
          break;
        }
      }

#ifndef ROCKSDB_LITE
      if (immutable_db_options_.wal_filter != nullptr) {
        WriteBatch new_batch;
        bool batch_changed = false;

        WalFilter::WalProcessingOption wal_processing_option =
            immutable_db_options_.wal_filter->LogRecordFound(
973
                wal_number, fname, batch, &new_batch, &batch_changed);
S
Siying Dong 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

        switch (wal_processing_option) {
          case WalFilter::WalProcessingOption::kContinueProcessing:
            // do nothing, proceeed normally
            break;
          case WalFilter::WalProcessingOption::kIgnoreCurrentRecord:
            // skip current record
            continue;
          case WalFilter::WalProcessingOption::kStopReplay:
            // skip current record and stop replay
            stop_replay_by_wal_filter = true;
            continue;
          case WalFilter::WalProcessingOption::kCorruptedRecord: {
            status =
                Status::Corruption("Corruption reported by Wal Filter ",
                                   immutable_db_options_.wal_filter->Name());
            MaybeIgnoreError(&status);
            if (!status.ok()) {
              reporter.Corruption(record.size(), status);
              continue;
            }
            break;
          }
          default: {
            assert(false);  // unhandled case
            status = Status::NotSupported(
                "Unknown WalProcessingOption returned"
                " by Wal Filter ",
                immutable_db_options_.wal_filter->Name());
            MaybeIgnoreError(&status);
            if (!status.ok()) {
              return status;
            } else {
              // Ignore the error with current record processing.
              continue;
            }
          }
        }

        if (batch_changed) {
          // Make sure that the count in the new batch is
          // within the orignal count.
          int new_count = WriteBatchInternal::Count(&new_batch);
          int original_count = WriteBatchInternal::Count(&batch);
          if (new_count > original_count) {
            ROCKS_LOG_FATAL(
                immutable_db_options_.info_log,
                "Recovering log #%" PRIu64
                " mode %d log filter %s returned "
                "more records (%d) than original (%d) which is not allowed. "
                "Aborting recovery.",
1025
                wal_number,
1026
                static_cast<int>(immutable_db_options_.wal_recovery_mode),
S
Siying Dong 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
                immutable_db_options_.wal_filter->Name(), new_count,
                original_count);
            status = Status::NotSupported(
                "More than original # of records "
                "returned by Wal Filter ",
                immutable_db_options_.wal_filter->Name());
            return status;
          }
          // Set the same sequence number in the new_batch
          // as the original batch.
          WriteBatchInternal::SetSequence(&new_batch,
                                          WriteBatchInternal::Sequence(&batch));
          batch = new_batch;
        }
      }
#endif  // ROCKSDB_LITE

      // If column family was not found, it might mean that the WAL write
      // batch references to the column family that was dropped after the
      // insert. We don't want to fail the whole write batch in that case --
      // we just ignore the update.
      // That's why we set ignore missing column families to true
      bool has_valid_writes = false;
      status = WriteBatchInternal::InsertInto(
1051
          &batch, column_family_memtables_.get(), &flush_scheduler_,
1052
          &trim_history_scheduler_, true, wal_number, this,
1053 1054
          false /* concurrent_memtable_writes */, next_sequence,
          &has_valid_writes, seq_per_batch_, batch_per_txn_);
S
Siying Dong 已提交
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
      MaybeIgnoreError(&status);
      if (!status.ok()) {
        // We are treating this as a failure while reading since we read valid
        // blocks that do not form coherent data
        reporter.Corruption(record.size(), status);
        continue;
      }

      if (has_valid_writes && !read_only) {
        // we can do this because this is called before client has access to the
        // DB and there is only a single thread operating on DB
        ColumnFamilyData* cfd;

        while ((cfd = flush_scheduler_.TakeNextColumnFamily()) != nullptr) {
1069
          cfd->UnrefAndTryDelete();
S
Siying Dong 已提交
1070 1071
          // If this asserts, it means that InsertInto failed in
          // filtering updates to already-flushed column families
1072
          assert(cfd->GetLogNumber() <= wal_number);
S
Siying Dong 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
          auto iter = version_edits.find(cfd->GetID());
          assert(iter != version_edits.end());
          VersionEdit* edit = &iter->second;
          status = WriteLevel0TableForRecovery(job_id, cfd, cfd->mem(), edit);
          if (!status.ok()) {
            // Reflect errors immediately so that conditions like full
            // file-systems cause the DB::Open() to fail.
            return status;
          }
          flushed = true;

          cfd->CreateNewMemtable(*cfd->GetLatestMutableCFOptions(),
                                 *next_sequence);
        }
      }
    }

    if (!status.ok()) {
1091 1092 1093 1094 1095 1096
      if (status.IsNotSupported()) {
        // We should not treat NotSupported as corruption. It is rather a clear
        // sign that we are processing a WAL that is produced by an incompatible
        // version of the code.
        return status;
      }
S
Siying Dong 已提交
1097 1098 1099 1100 1101 1102
      if (immutable_db_options_.wal_recovery_mode ==
          WALRecoveryMode::kSkipAnyCorruptedRecords) {
        // We should ignore all errors unconditionally
        status = Status::OK();
      } else if (immutable_db_options_.wal_recovery_mode ==
                 WALRecoveryMode::kPointInTimeRecovery) {
1103 1104 1105 1106 1107 1108
        if (status.IsIOError()) {
          ROCKS_LOG_ERROR(immutable_db_options_.info_log,
                          "IOError during point-in-time reading log #%" PRIu64
                          " seq #%" PRIu64
                          ". %s. This likely mean loss of synced WAL, "
                          "thus recovery fails.",
1109
                          wal_number, *next_sequence,
1110 1111 1112
                          status.ToString().c_str());
          return status;
        }
S
Siying Dong 已提交
1113 1114 1115
        // We should ignore the error but not continue replaying
        status = Status::OK();
        stop_replay_for_corruption = true;
1116 1117 1118
        corrupted_wal_number = wal_number;
        if (corrupted_wal_found != nullptr) {
          *corrupted_wal_found = true;
1119
        }
S
Siying Dong 已提交
1120 1121 1122
        ROCKS_LOG_INFO(immutable_db_options_.info_log,
                       "Point in time recovered to log #%" PRIu64
                       " seq #%" PRIu64,
1123
                       wal_number, *next_sequence);
S
Siying Dong 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
      } else {
        assert(immutable_db_options_.wal_recovery_mode ==
                   WALRecoveryMode::kTolerateCorruptedTailRecords ||
               immutable_db_options_.wal_recovery_mode ==
                   WALRecoveryMode::kAbsoluteConsistency);
        return status;
      }
    }

    flush_scheduler_.Clear();
1134
    trim_history_scheduler_.Clear();
S
Siying Dong 已提交
1135 1136 1137
    auto last_sequence = *next_sequence - 1;
    if ((*next_sequence != kMaxSequenceNumber) &&
        (versions_->LastSequence() <= last_sequence)) {
1138
      versions_->SetLastAllocatedSequence(last_sequence);
1139
      versions_->SetLastPublishedSequence(last_sequence);
S
Siying Dong 已提交
1140 1141 1142
      versions_->SetLastSequence(last_sequence);
    }
  }
1143 1144 1145 1146 1147
  // Compare the corrupted log number to all columnfamily's current log number.
  // Abort Open() if any column family's log number is greater than
  // the corrupted log number, which means CF contains data beyond the point of
  // corruption. This could during PIT recovery when the WAL is corrupted and
  // some (but not all) CFs are flushed
1148
  // Exclude the PIT case where no log is dropped after the corruption point.
1149
  // This is to cover the case for empty wals after corrupted log, in which we
1150
  // don't reset stop_replay_for_corruption.
1151 1152 1153 1154 1155 1156
  if (stop_replay_for_corruption == true &&
      (immutable_db_options_.wal_recovery_mode ==
           WALRecoveryMode::kPointInTimeRecovery ||
       immutable_db_options_.wal_recovery_mode ==
           WALRecoveryMode::kTolerateCorruptedTailRecords)) {
    for (auto cfd : *versions_->GetColumnFamilySet()) {
1157
      if (cfd->GetLogNumber() > corrupted_wal_number) {
1158 1159 1160 1161 1162 1163 1164
        ROCKS_LOG_ERROR(immutable_db_options_.info_log,
                        "Column family inconsistency: SST file contains data"
                        " beyond the point of corruption.");
        return Status::Corruption("SST file is ahead of WALs");
      }
    }
  }
S
Siying Dong 已提交
1165 1166 1167 1168 1169 1170 1171

  // True if there's any data in the WALs; if not, we can skip re-processing
  // them later
  bool data_seen = false;
  if (!read_only) {
    // no need to refcount since client still doesn't have access
    // to the DB and can not drop column families while we iterate
1172
    auto max_wal_number = wal_numbers.back();
S
Siying Dong 已提交
1173 1174 1175 1176 1177
    for (auto cfd : *versions_->GetColumnFamilySet()) {
      auto iter = version_edits.find(cfd->GetID());
      assert(iter != version_edits.end());
      VersionEdit* edit = &iter->second;

1178
      if (cfd->GetLogNumber() > max_wal_number) {
S
Siying Dong 已提交
1179
        // Column family cfd has already flushed the data
1180 1181
        // from all wals. Memtable has to be empty because
        // we filter the updates based on wal_number
S
Siying Dong 已提交
1182 1183 1184 1185 1186 1187
        // (in WriteBatch::InsertInto)
        assert(cfd->mem()->GetFirstSequenceNumber() == 0);
        assert(edit->NumEntries() == 0);
        continue;
      }

1188 1189 1190
      TEST_SYNC_POINT_CALLBACK(
          "DBImpl::RecoverLogFiles:BeforeFlushFinalMemtable", /*arg=*/nullptr);

S
Siying Dong 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
      // flush the final memtable (if non-empty)
      if (cfd->mem()->GetFirstSequenceNumber() != 0) {
        // If flush happened in the middle of recovery (e.g. due to memtable
        // being full), we flush at the end. Otherwise we'll need to record
        // where we were on last flush, which make the logic complicated.
        if (flushed || !immutable_db_options_.avoid_flush_during_recovery) {
          status = WriteLevel0TableForRecovery(job_id, cfd, cfd->mem(), edit);
          if (!status.ok()) {
            // Recovery failed
            break;
          }
          flushed = true;

          cfd->CreateNewMemtable(*cfd->GetLatestMutableCFOptions(),
                                 versions_->LastSequence());
        }
        data_seen = true;
      }

1210 1211 1212
      // Update the log number info in the version edit corresponding to this
      // column family. Note that the version edits will be written to MANIFEST
      // together later.
1213 1214
      // writing wal_number in the manifest means that any log file
      // with number strongly less than (wal_number + 1) is already
S
Siying Dong 已提交
1215
      // recovered and should be ignored on next reincarnation.
1216 1217
      // Since we already recovered max_wal_number, we want all wals
      // with numbers `<= max_wal_number` (includes this one) to be ignored
S
Siying Dong 已提交
1218
      if (flushed || cfd->mem()->GetFirstSequenceNumber() == 0) {
1219
        edit->SetLogNumber(max_wal_number + 1);
S
Siying Dong 已提交
1220
      }
1221 1222
    }
    if (status.ok()) {
S
Siying Dong 已提交
1223 1224 1225 1226
      // we must mark the next log number as used, even though it's
      // not actually used. that is because VersionSet assumes
      // VersionSet::next_file_number_ always to be strictly greater than any
      // log number
1227
      versions_->MarkFileNumberUsed(max_wal_number + 1);
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237

      autovector<ColumnFamilyData*> cfds;
      autovector<const MutableCFOptions*> cf_opts;
      autovector<autovector<VersionEdit*>> edit_lists;
      for (auto* cfd : *versions_->GetColumnFamilySet()) {
        cfds.push_back(cfd);
        cf_opts.push_back(cfd->GetLatestMutableCFOptions());
        auto iter = version_edits.find(cfd->GetID());
        assert(iter != version_edits.end());
        edit_lists.push_back({&iter->second});
S
Siying Dong 已提交
1238
      }
1239 1240 1241 1242
      // write MANIFEST with update
      status = versions_->LogAndApply(cfds, cf_opts, edit_lists, &mutex_,
                                      directories_.GetDbDir(),
                                      /*new_descriptor_log=*/true);
S
Siying Dong 已提交
1243 1244 1245
    }
  }

1246
  if (status.ok() && data_seen && !flushed) {
1247
    status = RestoreAliveLogFiles(wal_numbers);
S
Siying Dong 已提交
1248 1249 1250 1251 1252 1253 1254 1255
  }

  event_logger_.Log() << "job" << job_id << "event"
                      << "recovery_finished";

  return status;
}

1256 1257
Status DBImpl::RestoreAliveLogFiles(const std::vector<uint64_t>& wal_numbers) {
  if (wal_numbers.empty()) {
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    return Status::OK();
  }
  Status s;
  mutex_.AssertHeld();
  assert(immutable_db_options_.avoid_flush_during_recovery);
  if (two_write_queues_) {
    log_write_mutex_.Lock();
  }
  // Mark these as alive so they'll be considered for deletion later by
  // FindObsoleteFiles()
  total_log_size_ = 0;
  log_empty_ = false;
1270 1271 1272 1273
  for (auto wal_number : wal_numbers) {
    LogFileNumberSize log(wal_number);
    std::string fname = LogFileName(immutable_db_options_.wal_dir, wal_number);
    // This gets the appear size of the wals, not including preallocated space.
1274 1275 1276 1277 1278 1279
    s = env_->GetFileSize(fname, &log.size);
    if (!s.ok()) {
      break;
    }
    total_log_size_ += log.size;
    alive_log_files_.push_back(log);
1280
    // We preallocate space for wals, but then after a crash and restart, those
1281 1282
    // preallocated space are not needed anymore. It is likely only the last
    // log has such preallocated space, so we only truncate for the last log.
1283
    if (wal_number == wal_numbers.back()) {
1284 1285 1286 1287 1288 1289 1290
      std::unique_ptr<FSWritableFile> last_log;
      Status truncate_status = fs_->ReopenWritableFile(
          fname,
          fs_->OptimizeForLogWrite(
              file_options_,
              BuildDBOptions(immutable_db_options_, mutable_db_options_)),
          &last_log, nullptr);
1291
      if (truncate_status.ok()) {
1292
        truncate_status = last_log->Truncate(log.size, IOOptions(), nullptr);
1293 1294
      }
      if (truncate_status.ok()) {
1295
        truncate_status = last_log->Close(IOOptions(), nullptr);
1296 1297 1298 1299
      }
      // Not a critical error if fail to truncate.
      if (!truncate_status.ok()) {
        ROCKS_LOG_WARN(immutable_db_options_.info_log,
1300
                       "Failed to truncate log #%" PRIu64 ": %s", wal_number,
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
                       truncate_status.ToString().c_str());
      }
    }
  }
  if (two_write_queues_) {
    log_write_mutex_.Unlock();
  }
  return s;
}

S
Siying Dong 已提交
1311 1312 1313 1314
Status DBImpl::WriteLevel0TableForRecovery(int job_id, ColumnFamilyData* cfd,
                                           MemTable* mem, VersionEdit* edit) {
  mutex_.AssertHeld();
  const uint64_t start_micros = env_->NowMicros();
1315

S
Siying Dong 已提交
1316
  FileMetaData meta;
1317
  std::vector<BlobFileAddition> blob_file_additions;
1318

1319 1320 1321
  std::unique_ptr<std::list<uint64_t>::iterator> pending_outputs_inserted_elem(
      new std::list<uint64_t>::iterator(
          CaptureCurrentFileNumberInPendingOutputs()));
S
Siying Dong 已提交
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
  meta.fd = FileDescriptor(versions_->NewFileNumber(), 0, 0);
  ReadOptions ro;
  ro.total_order_seek = true;
  Arena arena;
  Status s;
  TableProperties table_properties;
  {
    ScopedArenaIterator iter(mem->NewIterator(ro, &arena));
    ROCKS_LOG_DEBUG(immutable_db_options_.info_log,
                    "[%s] [WriteLevel0TableForRecovery]"
                    " Level-0 table #%" PRIu64 ": started",
                    cfd->GetName().c_str(), meta.fd.GetNumber());

    // Get the latest mutable cf options while the mutex is still locked
    const MutableCFOptions mutable_cf_options =
        *cfd->GetLatestMutableCFOptions();
    bool paranoid_file_checks =
        cfd->GetLatestMutableCFOptions()->paranoid_file_checks;
S
Sagar Vemuri 已提交
1340

1341
    int64_t _current_time = 0;
1342 1343
    env_->GetCurrentTime(&_current_time)
        .PermitUncheckedError();  // ignore error
S
Sagar Vemuri 已提交
1344
    const uint64_t current_time = static_cast<uint64_t>(_current_time);
1345
    meta.oldest_ancester_time = current_time;
S
Sagar Vemuri 已提交
1346

S
Siying Dong 已提交
1347
    {
S
Stream  
Shaohua Li 已提交
1348
      auto write_hint = cfd->CalculateSSTWriteHint(0);
S
Siying Dong 已提交
1349 1350 1351 1352 1353
      mutex_.Unlock();

      SequenceNumber earliest_write_conflict_snapshot;
      std::vector<SequenceNumber> snapshot_seqs =
          snapshots_.GetAll(&earliest_write_conflict_snapshot);
1354 1355 1356 1357
      auto snapshot_checker = snapshot_checker_.get();
      if (use_custom_gc_ && snapshot_checker == nullptr) {
        snapshot_checker = DisableGCSnapshotChecker::Instance();
      }
1358 1359 1360 1361 1362 1363 1364
      std::vector<std::unique_ptr<FragmentedRangeTombstoneIterator>>
          range_del_iters;
      auto range_del_iter =
          mem->NewRangeTombstoneIterator(ro, kMaxSequenceNumber);
      if (range_del_iter != nullptr) {
        range_del_iters.emplace_back(range_del_iter);
      }
1365

1366
      IOStatus io_s;
S
Siying Dong 已提交
1367
      s = BuildTable(
1368 1369
          dbname_, versions_.get(), env_, fs_.get(), *cfd->ioptions(),
          mutable_cf_options, file_options_for_compaction_, cfd->table_cache(),
1370 1371 1372 1373
          iter.get(), std::move(range_del_iters), &meta, &blob_file_additions,
          cfd->internal_comparator(), cfd->int_tbl_prop_collector_factories(),
          cfd->GetID(), cfd->GetName(), snapshot_seqs,
          earliest_write_conflict_snapshot, snapshot_checker,
S
Siying Dong 已提交
1374
          GetCompressionFlush(*cfd->ioptions(), mutable_cf_options),
1375
          mutable_cf_options.sample_for_compression,
1376
          mutable_cf_options.compression_opts, paranoid_file_checks,
1377
          cfd->internal_stats(), TableFileCreationReason::kRecovery, &io_s,
1378 1379 1380 1381
          io_tracer_, &event_logger_, job_id, Env::IO_HIGH,
          nullptr /* table_properties */, -1 /* level */, current_time,
          0 /* oldest_key_time */, write_hint, 0 /* file_creation_time */,
          db_id_, db_session_id_);
S
Siying Dong 已提交
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
      LogFlush(immutable_db_options_.info_log);
      ROCKS_LOG_DEBUG(immutable_db_options_.info_log,
                      "[%s] [WriteLevel0TableForRecovery]"
                      " Level-0 table #%" PRIu64 ": %" PRIu64 " bytes %s",
                      cfd->GetName().c_str(), meta.fd.GetNumber(),
                      meta.fd.GetFileSize(), s.ToString().c_str());
      mutex_.Lock();
    }
  }
  ReleaseFileNumberFromPendingOutputs(pending_outputs_inserted_elem);

  // Note that if file_size is zero, the file has been deleted and
  // should not be added to the manifest.
1395 1396 1397 1398 1399 1400
  const bool has_output = meta.fd.GetFileSize() > 0;
  assert(has_output || blob_file_additions.empty());

  constexpr int level = 0;

  if (s.ok() && has_output) {
S
Siying Dong 已提交
1401 1402
    edit->AddFile(level, meta.fd.GetNumber(), meta.fd.GetPathId(),
                  meta.fd.GetFileSize(), meta.smallest, meta.largest,
1403
                  meta.fd.smallest_seqno, meta.fd.largest_seqno,
1404
                  meta.marked_for_compaction, meta.oldest_blob_file_number,
1405 1406
                  meta.oldest_ancester_time, meta.file_creation_time,
                  meta.file_checksum, meta.file_checksum_func_name);
1407 1408

    edit->SetBlobFileAdditions(std::move(blob_file_additions));
S
Siying Dong 已提交
1409 1410
  }

1411
  InternalStats::CompactionStats stats(CompactionReason::kFlush, 1);
S
Siying Dong 已提交
1412
  stats.micros = env_->NowMicros() - start_micros;
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424

  if (has_output) {
    stats.bytes_written = meta.fd.GetFileSize();

    const auto& blobs = edit->GetBlobFileAdditions();
    for (const auto& blob : blobs) {
      stats.bytes_written += blob.GetTotalBlobBytes();
    }

    stats.num_output_files = static_cast<int>(blobs.size()) + 1;
  }

1425
  cfd->internal_stats()->AddCompactionStats(level, Env::Priority::USER, stats);
1426
  cfd->internal_stats()->AddCFStats(InternalStats::BYTES_FLUSHED,
1427
                                    stats.bytes_written);
S
Siying Dong 已提交
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
  RecordTick(stats_, COMPACT_WRITE_BYTES, meta.fd.GetFileSize());
  return s;
}

Status DB::Open(const Options& options, const std::string& dbname, DB** dbptr) {
  DBOptions db_options(options);
  ColumnFamilyOptions cf_options(options);
  std::vector<ColumnFamilyDescriptor> column_families;
  column_families.push_back(
      ColumnFamilyDescriptor(kDefaultColumnFamilyName, cf_options));
1438 1439 1440 1441
  if (db_options.persist_stats_to_disk) {
    column_families.push_back(
        ColumnFamilyDescriptor(kPersistentStatsColumnFamilyName, cf_options));
  }
S
Siying Dong 已提交
1442 1443 1444
  std::vector<ColumnFamilyHandle*> handles;
  Status s = DB::Open(db_options, dbname, column_families, &handles, dbptr);
  if (s.ok()) {
1445 1446 1447 1448 1449
    if (db_options.persist_stats_to_disk) {
      assert(handles.size() == 2);
    } else {
      assert(handles.size() == 1);
    }
S
Siying Dong 已提交
1450 1451
    // i can delete the handle since DBImpl is always holding a reference to
    // default column family
1452 1453 1454
    if (db_options.persist_stats_to_disk && handles[1] != nullptr) {
      delete handles[1];
    }
S
Siying Dong 已提交
1455 1456 1457 1458
    delete handles[0];
  }
  return s;
}
1459

S
Siying Dong 已提交
1460 1461 1462
Status DB::Open(const DBOptions& db_options, const std::string& dbname,
                const std::vector<ColumnFamilyDescriptor>& column_families,
                std::vector<ColumnFamilyHandle*>* handles, DB** dbptr) {
1463 1464
  const bool kSeqPerBatch = true;
  const bool kBatchPerTxn = true;
1465
  return DBImpl::Open(db_options, dbname, column_families, handles, dbptr,
1466
                      !kSeqPerBatch, kBatchPerTxn);
1467 1468
}

1469 1470 1471 1472
IOStatus DBImpl::CreateWAL(uint64_t log_file_num, uint64_t recycle_log_number,
                           size_t preallocate_block_size,
                           log::Writer** new_log) {
  IOStatus io_s;
1473
  std::unique_ptr<FSWritableFile> lfile;
1474 1475 1476

  DBOptions db_options =
      BuildDBOptions(immutable_db_options_, mutable_db_options_);
1477 1478
  FileOptions opt_file_options =
      fs_->OptimizeForLogWrite(file_options_, db_options);
1479 1480 1481 1482 1483 1484 1485 1486 1487
  std::string log_fname =
      LogFileName(immutable_db_options_.wal_dir, log_file_num);

  if (recycle_log_number) {
    ROCKS_LOG_INFO(immutable_db_options_.info_log,
                   "reusing log %" PRIu64 " from recycle list\n",
                   recycle_log_number);
    std::string old_log_fname =
        LogFileName(immutable_db_options_.wal_dir, recycle_log_number);
1488 1489
    TEST_SYNC_POINT("DBImpl::CreateWAL:BeforeReuseWritableFile1");
    TEST_SYNC_POINT("DBImpl::CreateWAL:BeforeReuseWritableFile2");
1490 1491
    io_s = fs_->ReuseWritableFile(log_fname, old_log_fname, opt_file_options,
                                  &lfile, /*dbg=*/nullptr);
1492
  } else {
1493
    io_s = NewWritableFile(fs_.get(), log_fname, &lfile, opt_file_options);
1494 1495
  }

1496
  if (io_s.ok()) {
1497 1498 1499 1500
    lfile->SetWriteLifeTimeHint(CalculateWALWriteHint());
    lfile->SetPreallocationBlockSize(preallocate_block_size);

    const auto& listeners = immutable_db_options_.listeners;
1501 1502 1503
    std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
        std::move(lfile), log_fname, opt_file_options, env_, io_tracer_,
        nullptr /* stats */, listeners));
1504 1505 1506 1507
    *new_log = new log::Writer(std::move(file_writer), log_file_num,
                               immutable_db_options_.recycle_log_file_num > 0,
                               immutable_db_options_.manual_wal_flush);
  }
1508
  return io_s;
1509 1510
}

1511 1512 1513
Status DBImpl::Open(const DBOptions& db_options, const std::string& dbname,
                    const std::vector<ColumnFamilyDescriptor>& column_families,
                    std::vector<ColumnFamilyHandle*>* handles, DB** dbptr,
1514
                    const bool seq_per_batch, const bool batch_per_txn) {
1515
  Status s = ValidateOptionsByTable(db_options, column_families);
S
Siying Dong 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
  if (!s.ok()) {
    return s;
  }

  s = ValidateOptions(db_options, column_families);
  if (!s.ok()) {
    return s;
  }

  *dbptr = nullptr;
  handles->clear();

  size_t max_write_buffer_size = 0;
  for (auto cf : column_families) {
    max_write_buffer_size =
        std::max(max_write_buffer_size, cf.options.write_buffer_size);
  }

1534
  DBImpl* impl = new DBImpl(db_options, dbname, seq_per_batch, batch_per_txn);
S
Siying Dong 已提交
1535 1536
  s = impl->env_->CreateDirIfMissing(impl->immutable_db_options_.wal_dir);
  if (s.ok()) {
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
    std::vector<std::string> paths;
    for (auto& db_path : impl->immutable_db_options_.db_paths) {
      paths.emplace_back(db_path.path);
    }
    for (auto& cf : column_families) {
      for (auto& cf_path : cf.options.cf_paths) {
        paths.emplace_back(cf_path.path);
      }
    }
    for (auto& path : paths) {
      s = impl->env_->CreateDirIfMissing(path);
S
Siying Dong 已提交
1548 1549 1550 1551
      if (!s.ok()) {
        break;
      }
    }
1552 1553 1554 1555 1556 1557

    // For recovery from NoSpace() error, we can only handle
    // the case where the database is stored in a single path
    if (paths.size() <= 1) {
      impl->error_handler_.EnableAutoRecovery();
    }
S
Siying Dong 已提交
1558
  }
1559 1560
  if (s.ok()) {
    s = impl->CreateArchivalDirectory();
S
Siying Dong 已提交
1561 1562 1563 1564 1565
  }
  if (!s.ok()) {
    delete impl;
    return s;
  }
1566

1567
  impl->wal_in_db_path_ = IsWalDirSameAsDBPath(&impl->immutable_db_options_);
1568

S
Siying Dong 已提交
1569 1570
  impl->mutex_.Lock();
  // Handles create_if_missing, error_if_exists
1571 1572
  uint64_t recovered_seq(kMaxSequenceNumber);
  s = impl->Recover(column_families, false, false, false, &recovered_seq);
S
Siying Dong 已提交
1573 1574
  if (s.ok()) {
    uint64_t new_log_number = impl->versions_->NewFileNumber();
1575 1576 1577 1578 1579
    log::Writer* new_log = nullptr;
    const size_t preallocate_block_size =
        impl->GetWalPreallocateBlockSize(max_write_buffer_size);
    s = impl->CreateWAL(new_log_number, 0 /*recycle_log_number*/,
                        preallocate_block_size, &new_log);
S
Siying Dong 已提交
1580
    if (s.ok()) {
1581 1582 1583 1584 1585
      InstrumentedMutexLock wl(&impl->log_write_mutex_);
      impl->logfile_number_ = new_log_number;
      assert(new_log != nullptr);
      impl->logs_.emplace_back(new_log_number, new_log);
    }
S
Siying Dong 已提交
1586

1587
    if (s.ok()) {
S
Siying Dong 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
      // set column family handles
      for (auto cf : column_families) {
        auto cfd =
            impl->versions_->GetColumnFamilySet()->GetColumnFamily(cf.name);
        if (cfd != nullptr) {
          handles->push_back(
              new ColumnFamilyHandleImpl(cfd, impl, &impl->mutex_));
          impl->NewThreadStatusCfInfo(cfd);
        } else {
          if (db_options.create_missing_column_families) {
            // missing column family, create it
            ColumnFamilyHandle* handle;
            impl->mutex_.Unlock();
            s = impl->CreateColumnFamily(cf.options, cf.name, &handle);
            impl->mutex_.Lock();
            if (s.ok()) {
              handles->push_back(handle);
            } else {
              break;
            }
          } else {
1609
            s = Status::InvalidArgument("Column family not found", cf.name);
S
Siying Dong 已提交
1610 1611 1612 1613 1614 1615
            break;
          }
        }
      }
    }
    if (s.ok()) {
1616
      SuperVersionContext sv_context(/* create_superversion */ true);
S
Siying Dong 已提交
1617
      for (auto cfd : *impl->versions_->GetColumnFamilySet()) {
1618 1619
        impl->InstallSuperVersionAndScheduleWork(
            cfd, &sv_context, *cfd->GetLatestMutableCFOptions());
S
Siying Dong 已提交
1620
      }
1621
      sv_context.Clean();
1622
      if (impl->two_write_queues_) {
1623 1624
        impl->log_write_mutex_.Lock();
      }
S
Siying Dong 已提交
1625 1626
      impl->alive_log_files_.push_back(
          DBImpl::LogFileNumberSize(impl->logfile_number_));
1627
      if (impl->two_write_queues_) {
1628 1629
        impl->log_write_mutex_.Unlock();
      }
1630

S
Siying Dong 已提交
1631
      impl->DeleteObsoleteFiles();
1632
      s = impl->directories_.GetDbDir()->Fsync(IOOptions(), nullptr);
S
Siying Dong 已提交
1633
    }
1634 1635 1636 1637
    if (s.ok()) {
      // In WritePrepared there could be gap in sequence numbers. This breaks
      // the trick we use in kPointInTimeRecovery which assumes the first seq in
      // the log right after the corrupted log is one larger than the last seq
1638
      // we read from the wals. To let this trick keep working, we add a dummy
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
      // entry with the expected sequence to the first log right after recovery.
      // In non-WritePrepared case also the new log after recovery could be
      // empty, and thus missing the consecutive seq hint to distinguish
      // middle-log corruption to corrupted-log-remained-after-recovery. This
      // case also will be addressed by a dummy write.
      if (recovered_seq != kMaxSequenceNumber) {
        WriteBatch empty_batch;
        WriteBatchInternal::SetSequence(&empty_batch, recovered_seq);
        WriteOptions write_options;
        uint64_t log_used, log_size;
        log::Writer* log_writer = impl->logs_.back().writer;
        s = impl->WriteToWAL(empty_batch, log_writer, &log_used, &log_size);
1651 1652 1653 1654 1655 1656 1657
        if (s.ok()) {
          // Need to fsync, otherwise it might get lost after a power reset.
          s = impl->FlushWAL(false);
          if (s.ok()) {
            s = log_writer->file()->Sync(impl->immutable_db_options_.use_fsync);
          }
        }
1658 1659
      }
    }
S
Siying Dong 已提交
1660
  }
1661
  if (s.ok() && impl->immutable_db_options_.persist_stats_to_disk) {
1662
    // try to read format version
1663 1664
    s = impl->PersistentStatsProcessFormatVersion();
  }
S
Siying Dong 已提交
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686

  if (s.ok()) {
    for (auto cfd : *impl->versions_->GetColumnFamilySet()) {
      if (cfd->ioptions()->compaction_style == kCompactionStyleFIFO) {
        auto* vstorage = cfd->current()->storage_info();
        for (int i = 1; i < vstorage->num_levels(); ++i) {
          int num_files = vstorage->NumLevelFiles(i);
          if (num_files > 0) {
            s = Status::InvalidArgument(
                "Not all files are at level 0. Cannot "
                "open with FIFO compaction style.");
            break;
          }
        }
      }
      if (!cfd->mem()->IsSnapshotSupported()) {
        impl->is_snapshot_supported_ = false;
      }
      if (cfd->ioptions()->merge_operator != nullptr &&
          !cfd->mem()->IsMergeOperatorSupported()) {
        s = Status::InvalidArgument(
            "The memtable of column family %s does not support merge operator "
1687 1688
            "its options.merge_operator is non-null",
            cfd->GetName().c_str());
S
Siying Dong 已提交
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
      }
      if (!s.ok()) {
        break;
      }
    }
  }
  TEST_SYNC_POINT("DBImpl::Open:Opened");
  Status persist_options_status;
  if (s.ok()) {
    // Persist RocksDB Options before scheduling the compaction.
    // The WriteOptionsFile() will release and lock the mutex internally.
Y
Yi Wu 已提交
1700 1701
    persist_options_status = impl->WriteOptionsFile(
        false /*need_mutex_lock*/, false /*need_enter_write_thread*/);
S
Siying Dong 已提交
1702 1703 1704 1705

    *dbptr = impl;
    impl->opened_successfully_ = true;
    impl->MaybeScheduleFlushOrCompaction();
1706 1707
  } else {
    persist_options_status.PermitUncheckedError();
S
Siying Dong 已提交
1708 1709 1710 1711 1712 1713 1714
  }
  impl->mutex_.Unlock();

#ifndef ROCKSDB_LITE
  auto sfm = static_cast<SstFileManagerImpl*>(
      impl->immutable_db_options_.sst_file_manager.get());
  if (s.ok() && sfm) {
1715 1716 1717 1718 1719 1720
    // Set Statistics ptr for SstFileManager to dump the stats of
    // DeleteScheduler.
    sfm->SetStatisticsPtr(impl->immutable_db_options_.statistics);
    ROCKS_LOG_INFO(impl->immutable_db_options_.info_log,
                   "SstFileManager instance %p", sfm);

S
Siying Dong 已提交
1721
    // Notify SstFileManager about all sst files that already exist in
1722
    // db_paths[0] and cf_paths[0] when the DB is opened.
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743

    // SstFileManagerImpl needs to know sizes of the files. For files whose size
    // we already know (sst files that appear in manifest - typically that's the
    // vast majority of all files), we'll pass the size to SstFileManager.
    // For all other files SstFileManager will query the size from filesystem.

    std::vector<LiveFileMetaData> metadata;

    impl->mutex_.Lock();
    impl->versions_->GetLiveFilesMetaData(&metadata);
    impl->mutex_.Unlock();

    std::unordered_map<std::string, uint64_t> known_file_sizes;
    for (const auto& md : metadata) {
      std::string name = md.name;
      if (!name.empty() && name[0] == '/') {
        name = name.substr(1);
      }
      known_file_sizes[name] = md.size;
    }

1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
    std::vector<std::string> paths;
    paths.emplace_back(impl->immutable_db_options_.db_paths[0].path);
    for (auto& cf : column_families) {
      if (!cf.options.cf_paths.empty()) {
        paths.emplace_back(cf.options.cf_paths[0].path);
      }
    }
    // Remove duplicate paths.
    std::sort(paths.begin(), paths.end());
    paths.erase(std::unique(paths.begin(), paths.end()), paths.end());
    for (auto& path : paths) {
      std::vector<std::string> existing_files;
1756 1757 1758
      // TODO: Check for errors here?
      impl->immutable_db_options_.env->GetChildren(path, &existing_files)
          .PermitUncheckedError();
1759 1760 1761 1762 1763 1764
      for (auto& file_name : existing_files) {
        uint64_t file_number;
        FileType file_type;
        std::string file_path = path + "/" + file_name;
        if (ParseFileName(file_name, &file_number, &file_type) &&
            file_type == kTableFile) {
1765
          // TODO: Check for errors from OnAddFile?
1766 1767 1768 1769
          if (known_file_sizes.count(file_name)) {
            // We're assuming that each sst file name exists in at most one of
            // the paths.
            sfm->OnAddFile(file_path, known_file_sizes.at(file_name),
1770 1771
                           /* compaction */ false)
                .PermitUncheckedError();
1772
          } else {
1773
            sfm->OnAddFile(file_path).PermitUncheckedError();
1774
          }
1775
        }
S
Siying Dong 已提交
1776 1777
      }
    }
1778 1779 1780 1781 1782 1783 1784 1785

    // Reserve some disk buffer space. This is a heuristic - when we run out
    // of disk space, this ensures that there is atleast write_buffer_size
    // amount of free space before we resume DB writes. In low disk space
    // conditions, we want to avoid a lot of small L0 files due to frequent
    // WAL write failures and resultant forced flushes
    sfm->ReserveDiskBuffer(max_write_buffer_size,
                           impl->immutable_db_options_.db_paths[0].path);
S
Siying Dong 已提交
1786
  }
1787

S
Siying Dong 已提交
1788 1789 1790
#endif  // !ROCKSDB_LITE

  if (s.ok()) {
1791 1792
    ROCKS_LOG_HEADER(impl->immutable_db_options_.info_log, "DB pointer %p",
                     impl);
S
Siying Dong 已提交
1793
    LogFlush(impl->immutable_db_options_.info_log);
1794 1795 1796
    assert(impl->TEST_WALBufferIsEmpty());
    // If the assert above fails then we need to FlushWAL before returning
    // control back to the user.
S
Siying Dong 已提交
1797
    if (!persist_options_status.ok()) {
Y
Yi Wu 已提交
1798 1799 1800
      s = Status::IOError(
          "DB::Open() failed --- Unable to persist Options file",
          persist_options_status.ToString());
S
Siying Dong 已提交
1801
    }
1802 1803 1804 1805
  } else {
    ROCKS_LOG_WARN(impl->immutable_db_options_.info_log,
                   "Persisting Option File error: %s",
                   persist_options_status.ToString().c_str());
S
Siying Dong 已提交
1806
  }
1807
  if (s.ok()) {
1808
    impl->StartPeriodicWorkScheduler();
1809
  } else {
S
Siying Dong 已提交
1810 1811 1812 1813 1814 1815 1816 1817 1818
    for (auto* h : *handles) {
      delete h;
    }
    handles->clear();
    delete impl;
    *dbptr = nullptr;
  }
  return s;
}
1819
}  // namespace ROCKSDB_NAMESPACE