repair.cc 13.3 KB
Newer Older
1 2 3 4 5
//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
J
jorlow@chromium.org 已提交
6 7 8 9 10 11 12 13
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// We recover the contents of the descriptor from the other files we find.
// (1) Any log files are first converted to tables
// (2) We scan every table to compute
//     (a) smallest/largest for the table
D
dgrogan@chromium.org 已提交
14
//     (b) largest sequence number in the table
J
jorlow@chromium.org 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28
// (3) We generate descriptor contents:
//      - log number is set to zero
//      - next-file-number is set to 1 + largest file number we found
//      - last-sequence-number is set to largest sequence# found across
//        all tables (see 2c)
//      - compaction pointers are cleared
//      - every table file is added at level 0
//
// Possible optimization 1:
//   (a) Compute total size and use to pick appropriate max-level M
//   (b) Sort tables by largest sequence# in the table
//   (c) For each table: if it overlaps earlier table, place in level-0,
//       else place in level-M.
// Possible optimization 2:
D
dgrogan@chromium.org 已提交
29 30
//   Store per-table metadata (smallest, largest, largest-seq#, ...)
//   in the table's meta section to speed up ScanTable.
J
jorlow@chromium.org 已提交
31

I
Igor Canadi 已提交
32 33
#ifndef ROCKSDB_LITE

L
liuhuahang 已提交
34
#ifndef __STDC_FORMAT_MACROS
35
#define __STDC_FORMAT_MACROS
L
liuhuahang 已提交
36 37
#endif

38
#include <inttypes.h>
J
jorlow@chromium.org 已提交
39 40 41 42 43 44 45 46 47 48
#include "db/builder.h"
#include "db/db_impl.h"
#include "db/dbformat.h"
#include "db/filename.h"
#include "db/log_reader.h"
#include "db/log_writer.h"
#include "db/memtable.h"
#include "db/table_cache.h"
#include "db/version_edit.h"
#include "db/write_batch_internal.h"
49 50 51
#include "rocksdb/comparator.h"
#include "rocksdb/db.h"
#include "rocksdb/env.h"
L
Lei Jin 已提交
52 53
#include "rocksdb/options.h"
#include "rocksdb/immutable_options.h"
54
#include "util/scoped_arena_iterator.h"
J
jorlow@chromium.org 已提交
55

56
namespace rocksdb {
J
jorlow@chromium.org 已提交
57 58 59 60 61 62 63 64 65

namespace {

class Repairer {
 public:
  Repairer(const std::string& dbname, const Options& options)
      : dbname_(dbname),
        env_(options.env),
        icmp_(options.comparator),
66
        options_(SanitizeOptions(dbname, &icmp_, options)),
L
Lei Jin 已提交
67
        ioptions_(options_),
I
Igor Canadi 已提交
68 69 70 71 72
        raw_table_cache_(
            // TableCache can be small since we expect each table to be opened
            // once.
            NewLRUCache(10, options_.table_cache_numshardbits,
                        options_.table_cache_remove_scan_count_limit)),
J
jorlow@chromium.org 已提交
73
        next_file_number_(1) {
74
    table_cache_ =
L
Lei Jin 已提交
75
        new TableCache(ioptions_, env_options_, raw_table_cache_.get());
76
    edit_ = new VersionEdit();
J
jorlow@chromium.org 已提交
77 78 79 80
  }

  ~Repairer() {
    delete table_cache_;
I
Igor Canadi 已提交
81
    raw_table_cache_.reset();
82
    delete edit_;
J
jorlow@chromium.org 已提交
83 84 85 86 87 88 89 90 91 92
  }

  Status Run() {
    Status status = FindFiles();
    if (status.ok()) {
      ConvertLogFilesToTables();
      ExtractMetaData();
      status = WriteDescriptor();
    }
    if (status.ok()) {
93
      uint64_t bytes = 0;
D
dgrogan@chromium.org 已提交
94
      for (size_t i = 0; i < tables_.size(); i++) {
95
        bytes += tables_[i].meta.fd.GetFileSize();
J
jorlow@chromium.org 已提交
96
      }
97
      Log(options_.info_log,
98
          "**** Repaired rocksdb %s; "
99 100
          "recovered %zu files; %" PRIu64
          "bytes. "
J
jorlow@chromium.org 已提交
101 102
          "Some data may have been lost. "
          "****",
103
          dbname_.c_str(), tables_.size(), bytes);
J
jorlow@chromium.org 已提交
104 105 106 107 108 109 110
    }
    return status;
  }

 private:
  struct TableInfo {
    FileMetaData meta;
111
    SequenceNumber min_sequence;
J
jorlow@chromium.org 已提交
112 113 114 115 116
    SequenceNumber max_sequence;
  };

  std::string const dbname_;
  Env* const env_;
L
Lei Jin 已提交
117 118 119
  const InternalKeyComparator icmp_;
  const Options options_;
  const ImmutableCFOptions ioptions_;
I
Igor Canadi 已提交
120
  std::shared_ptr<Cache> raw_table_cache_;
J
jorlow@chromium.org 已提交
121
  TableCache* table_cache_;
122
  VersionEdit* edit_;
J
jorlow@chromium.org 已提交
123 124

  std::vector<std::string> manifests_;
125
  std::vector<FileDescriptor> table_fds_;
J
jorlow@chromium.org 已提交
126 127 128
  std::vector<uint64_t> logs_;
  std::vector<TableInfo> tables_;
  uint64_t next_file_number_;
L
Lei Jin 已提交
129
  const EnvOptions env_options_;
J
jorlow@chromium.org 已提交
130 131 132

  Status FindFiles() {
    std::vector<std::string> filenames;
133 134
    bool found_file = false;
    for (uint32_t path_id = 0; path_id < options_.db_paths.size(); path_id++) {
135 136
      Status status =
          env_->GetChildren(options_.db_paths[path_id].path, &filenames);
137 138 139 140 141 142
      if (!status.ok()) {
        return status;
      }
      if (!filenames.empty()) {
        found_file = true;
      }
J
jorlow@chromium.org 已提交
143

144 145 146 147 148 149 150
      uint64_t number;
      FileType type;
      for (size_t i = 0; i < filenames.size(); i++) {
        if (ParseFileName(filenames[i], &number, &type)) {
          if (type == kDescriptorFile) {
            assert(path_id == 0);
            manifests_.push_back(filenames[i]);
J
jorlow@chromium.org 已提交
151
          } else {
152 153 154 155 156 157 158 159 160 161 162
            if (number + 1 > next_file_number_) {
              next_file_number_ = number + 1;
            }
            if (type == kLogFile) {
              assert(path_id == 0);
              logs_.push_back(number);
            } else if (type == kTableFile) {
              table_fds_.emplace_back(number, path_id, 0);
            } else {
              // Ignore other files
            }
J
jorlow@chromium.org 已提交
163 164 165 166
          }
        }
      }
    }
167 168 169 170
    if (!found_file) {
      return Status::Corruption(dbname_, "repair found no files");
    }
    return Status::OK();
J
jorlow@chromium.org 已提交
171 172 173
  }

  void ConvertLogFilesToTables() {
D
dgrogan@chromium.org 已提交
174
    for (size_t i = 0; i < logs_.size(); i++) {
J
jorlow@chromium.org 已提交
175 176 177
      std::string logname = LogFileName(dbname_, logs_[i]);
      Status status = ConvertLogToTable(logs_[i]);
      if (!status.ok()) {
178 179
        Log(options_.info_log,
            "Log #%" PRIu64 ": ignoring conversion error: %s", logs_[i],
J
jorlow@chromium.org 已提交
180 181 182 183 184 185 186 187 188
            status.ToString().c_str());
      }
      ArchiveFile(logname);
    }
  }

  Status ConvertLogToTable(uint64_t log) {
    struct LogReporter : public log::Reader::Reporter {
      Env* env;
189
      std::shared_ptr<Logger> info_log;
J
jorlow@chromium.org 已提交
190 191 192
      uint64_t lognum;
      virtual void Corruption(size_t bytes, const Status& s) {
        // We print error messages for corruption, but continue repairing.
193 194
        Log(info_log, "Log #%" PRIu64 ": dropping %d bytes; %s", lognum,
            static_cast<int>(bytes), s.ToString().c_str());
J
jorlow@chromium.org 已提交
195 196 197 198 199
      }
    };

    // Open the log file
    std::string logname = LogFileName(dbname_, log);
200
    unique_ptr<SequentialFile> lfile;
L
Lei Jin 已提交
201
    Status status = env_->NewSequentialFile(logname, &lfile, env_options_);
J
jorlow@chromium.org 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214
    if (!status.ok()) {
      return status;
    }

    // Create the log reader.
    LogReporter reporter;
    reporter.env = env_;
    reporter.info_log = options_.info_log;
    reporter.lognum = log;
    // We intentially make log::Reader do checksumming so that
    // corruptions cause entire commits to be skipped instead of
    // propagating bad information (like overly large sequence
    // numbers).
215
    log::Reader reader(std::move(lfile), &reporter, false/*do not checksum*/,
216
                       0/*initial_offset*/);
J
jorlow@chromium.org 已提交
217 218 219 220 221

    // Read all the records and add to a memtable
    std::string scratch;
    Slice record;
    WriteBatch batch;
222
    MemTable* mem = new MemTable(icmp_, options_);
223
    auto cf_mems_default = new ColumnFamilyMemTablesDefault(mem, &options_);
224
    mem->Ref();
J
jorlow@chromium.org 已提交
225 226 227 228 229 230 231 232
    int counter = 0;
    while (reader.ReadRecord(&record, &scratch)) {
      if (record.size() < 12) {
        reporter.Corruption(
            record.size(), Status::Corruption("log record too small"));
        continue;
      }
      WriteBatchInternal::SetContents(&batch, record);
233
      status = WriteBatchInternal::InsertInto(&batch, cf_mems_default);
J
jorlow@chromium.org 已提交
234 235 236
      if (status.ok()) {
        counter += WriteBatchInternal::Count(&batch);
      } else {
237
        Log(options_.info_log, "Log #%" PRIu64 ": ignoring %s", log,
J
jorlow@chromium.org 已提交
238 239 240 241 242
            status.ToString().c_str());
        status = Status::OK();  // Keep going with rest of file
      }
    }

243
    // Do not record a version edit for this conversion to a Table
J
jorlow@chromium.org 已提交
244 245
    // since ExtractMetaData() will also generate edits.
    FileMetaData meta;
246
    meta.fd = FileDescriptor(next_file_number_++, 0, 0);
247 248 249 250 251 252 253 254 255
    {
      ReadOptions ro;
      ro.total_order_seek = true;
      Arena arena;
      ScopedArenaIterator iter(mem->NewIterator(ro, &arena));
      status = BuildTable(dbname_, env_, ioptions_, env_options_, table_cache_,
                          iter.get(), &meta, icmp_, 0, 0, kNoCompression,
                          CompressionOptions());
    }
256
    delete mem->Unref();
257
    delete cf_mems_default;
A
Abhishek Kona 已提交
258
    mem = nullptr;
J
jorlow@chromium.org 已提交
259
    if (status.ok()) {
260
      if (meta.fd.GetFileSize() > 0) {
261
        table_fds_.push_back(meta.fd);
J
jorlow@chromium.org 已提交
262 263
      }
    }
264 265 266
    Log(options_.info_log,
        "Log #%" PRIu64 ": %d ops saved to Table #%" PRIu64 " %s", log, counter,
        meta.fd.GetNumber(), status.ToString().c_str());
J
jorlow@chromium.org 已提交
267 268 269 270
    return status;
  }

  void ExtractMetaData() {
271
    for (size_t i = 0; i < table_fds_.size(); i++) {
J
jorlow@chromium.org 已提交
272
      TableInfo t;
273
      t.meta.fd = table_fds_[i];
J
jorlow@chromium.org 已提交
274 275
      Status status = ScanTable(&t);
      if (!status.ok()) {
276 277
        std::string fname = TableFileName(
            options_.db_paths, t.meta.fd.GetNumber(), t.meta.fd.GetPathId());
278 279 280 281
        char file_num_buf[kFormatFileNumberBufSize];
        FormatFileNumber(t.meta.fd.GetNumber(), t.meta.fd.GetPathId(),
                         file_num_buf, sizeof(file_num_buf));
        Log(options_.info_log, "Table #%s: ignoring %s", file_num_buf,
282
            status.ToString().c_str());
J
jorlow@chromium.org 已提交
283 284 285 286 287 288 289 290
        ArchiveFile(fname);
      } else {
        tables_.push_back(t);
      }
    }
  }

  Status ScanTable(TableInfo* t) {
291 292
    std::string fname = TableFileName(options_.db_paths, t->meta.fd.GetNumber(),
                                      t->meta.fd.GetPathId());
J
jorlow@chromium.org 已提交
293
    int counter = 0;
294 295 296 297
    uint64_t file_size;
    Status status = env_->GetFileSize(fname, &file_size);
    t->meta.fd = FileDescriptor(t->meta.fd.GetNumber(), t->meta.fd.GetPathId(),
                                file_size);
J
jorlow@chromium.org 已提交
298 299
    if (status.ok()) {
      Iterator* iter = table_cache_->NewIterator(
L
Lei Jin 已提交
300
          ReadOptions(), env_options_, icmp_, t->meta.fd);
J
jorlow@chromium.org 已提交
301 302
      bool empty = true;
      ParsedInternalKey parsed;
303
      t->min_sequence = 0;
J
jorlow@chromium.org 已提交
304 305 306 307
      t->max_sequence = 0;
      for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
        Slice key = iter->key();
        if (!ParseInternalKey(key, &parsed)) {
308 309
          Log(options_.info_log, "Table #%" PRIu64 ": unparsable key %s",
              t->meta.fd.GetNumber(), EscapeString(key).c_str());
J
jorlow@chromium.org 已提交
310 311 312 313 314 315 316 317 318
          continue;
        }

        counter++;
        if (empty) {
          empty = false;
          t->meta.smallest.DecodeFrom(key);
        }
        t->meta.largest.DecodeFrom(key);
319 320 321
        if (parsed.sequence < t->min_sequence) {
          t->min_sequence = parsed.sequence;
        }
J
jorlow@chromium.org 已提交
322 323 324 325 326 327 328 329 330
        if (parsed.sequence > t->max_sequence) {
          t->max_sequence = parsed.sequence;
        }
      }
      if (!iter->status().ok()) {
        status = iter->status();
      }
      delete iter;
    }
331 332
    Log(options_.info_log, "Table #%" PRIu64 ": %d entries %s",
        t->meta.fd.GetNumber(), counter, status.ToString().c_str());
J
jorlow@chromium.org 已提交
333 334 335 336 337
    return status;
  }

  Status WriteDescriptor() {
    std::string tmp = TempFileName(dbname_, 1);
338
    unique_ptr<WritableFile> file;
I
Igor Canadi 已提交
339
    Status status = env_->NewWritableFile(
L
Lei Jin 已提交
340
        tmp, &file, env_->OptimizeForManifestWrite(env_options_));
J
jorlow@chromium.org 已提交
341 342 343 344 345
    if (!status.ok()) {
      return status;
    }

    SequenceNumber max_sequence = 0;
D
dgrogan@chromium.org 已提交
346
    for (size_t i = 0; i < tables_.size(); i++) {
J
jorlow@chromium.org 已提交
347 348 349 350 351
      if (max_sequence < tables_[i].max_sequence) {
        max_sequence = tables_[i].max_sequence;
      }
    }

352 353 354 355
    edit_->SetComparatorName(icmp_.user_comparator()->Name());
    edit_->SetLogNumber(0);
    edit_->SetNextFile(next_file_number_);
    edit_->SetLastSequence(max_sequence);
J
jorlow@chromium.org 已提交
356

D
dgrogan@chromium.org 已提交
357
    for (size_t i = 0; i < tables_.size(); i++) {
J
jorlow@chromium.org 已提交
358 359
      // TODO(opt): separate out into multiple levels
      const TableInfo& t = tables_[i];
360 361 362
      edit_->AddFile(0, t.meta.fd.GetNumber(), t.meta.fd.GetPathId(),
                     t.meta.fd.GetFileSize(), t.meta.smallest, t.meta.largest,
                     t.min_sequence, t.max_sequence);
J
jorlow@chromium.org 已提交
363 364 365 366
    }

    //fprintf(stderr, "NewDescriptor:\n%s\n", edit_.DebugString().c_str());
    {
367
      log::Writer log(std::move(file));
J
jorlow@chromium.org 已提交
368
      std::string record;
369
      edit_->EncodeTo(&record);
J
jorlow@chromium.org 已提交
370 371 372 373 374 375 376
      status = log.AddRecord(record);
    }

    if (!status.ok()) {
      env_->DeleteFile(tmp);
    } else {
      // Discard older manifests
D
dgrogan@chromium.org 已提交
377
      for (size_t i = 0; i < manifests_.size(); i++) {
J
jorlow@chromium.org 已提交
378 379 380 381 382 383
        ArchiveFile(dbname_ + "/" + manifests_[i]);
      }

      // Install new manifest
      status = env_->RenameFile(tmp, DescriptorFileName(dbname_, 1));
      if (status.ok()) {
384
        status = SetCurrentFile(env_, dbname_, 1, nullptr);
J
jorlow@chromium.org 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398
      } else {
        env_->DeleteFile(tmp);
      }
    }
    return status;
  }

  void ArchiveFile(const std::string& fname) {
    // Move into another directory.  E.g., for
    //    dir/foo
    // rename to
    //    dir/lost/foo
    const char* slash = strrchr(fname.c_str(), '/');
    std::string new_dir;
A
Abhishek Kona 已提交
399
    if (slash != nullptr) {
J
jorlow@chromium.org 已提交
400 401 402 403 404 405
      new_dir.assign(fname.data(), slash - fname.data());
    }
    new_dir.append("/lost");
    env_->CreateDir(new_dir);  // Ignore error
    std::string new_file = new_dir;
    new_file.append("/");
A
Abhishek Kona 已提交
406
    new_file.append((slash == nullptr) ? fname.c_str() : slash + 1);
J
jorlow@chromium.org 已提交
407
    Status s = env_->RenameFile(fname, new_file);
408
    Log(options_.info_log, "Archiving %s: %s\n",
J
jorlow@chromium.org 已提交
409 410 411
        fname.c_str(), s.ToString().c_str());
  }
};
H
Hans Wennborg 已提交
412
}  // namespace
J
jorlow@chromium.org 已提交
413 414 415 416 417 418

Status RepairDB(const std::string& dbname, const Options& options) {
  Repairer repairer(dbname, options);
  return repairer.Run();
}

419
}  // namespace rocksdb
I
Igor Canadi 已提交
420 421

#endif  // ROCKSDB_LITE