ldb_cmd.cc 94.1 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 3 4
//  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.
5 6
//  This source code is also licensed under the GPLv2 license found in the
//  COPYING file in the root directory of this source tree.
7
//
I
Igor Canadi 已提交
8
#ifndef ROCKSDB_LITE
A
Arun Sharma 已提交
9
#include "rocksdb/utilities/ldb_cmd.h"
A
Abhishek Kona 已提交
10

11 12 13 14 15 16
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <inttypes.h>

17
#include "db/db_impl.h"
A
Andrew Kryczka 已提交
18 19
#include "db/dbformat.h"
#include "db/log_reader.h"
A
Abhishek Kona 已提交
20
#include "db/write_batch_internal.h"
A
Andrew Kryczka 已提交
21
#include "port/dirent.h"
I
Igor Canadi 已提交
22
#include "rocksdb/cache.h"
23
#include "rocksdb/table_properties.h"
W
Wanning Jiang 已提交
24
#include "rocksdb/utilities/backupable_db.h"
A
Aaron Gao 已提交
25
#include "rocksdb/utilities/checkpoint.h"
A
Andrew Kryczka 已提交
26
#include "rocksdb/utilities/debug.h"
27
#include "rocksdb/utilities/object_registry.h"
28
#include "rocksdb/utilities/options_util.h"
A
Andrew Kryczka 已提交
29
#include "rocksdb/write_batch.h"
30
#include "rocksdb/write_buffer_manager.h"
S
sdong 已提交
31
#include "table/scoped_arena_iterator.h"
A
Arun Sharma 已提交
32
#include "tools/ldb_cmd_impl.h"
33
#include "tools/sst_dump_tool_imp.h"
34
#include "util/coding.h"
35
#include "util/filename.h"
A
Andrew Kryczka 已提交
36
#include "util/stderr_logger.h"
S
sdong 已提交
37
#include "util/string_util.h"
38
#include "utilities/ttl/db_ttl_impl.h"
39

S
sdong 已提交
40
#include <cstdlib>
41
#include <ctime>
42 43
#include <fstream>
#include <functional>
A
Arun Sharma 已提交
44
#include <iostream>
45 46 47
#include <limits>
#include <sstream>
#include <stdexcept>
A
Arun Sharma 已提交
48
#include <string>
49

50
namespace rocksdb {
51

52 53 54 55 56 57 58 59 60 61
const std::string LDBCommand::ARG_DB = "db";
const std::string LDBCommand::ARG_PATH = "path";
const std::string LDBCommand::ARG_HEX = "hex";
const std::string LDBCommand::ARG_KEY_HEX = "key_hex";
const std::string LDBCommand::ARG_VALUE_HEX = "value_hex";
const std::string LDBCommand::ARG_CF_NAME = "column_family";
const std::string LDBCommand::ARG_TTL = "ttl";
const std::string LDBCommand::ARG_TTL_START = "start_time";
const std::string LDBCommand::ARG_TTL_END = "end_time";
const std::string LDBCommand::ARG_TIMESTAMP = "timestamp";
62
const std::string LDBCommand::ARG_TRY_LOAD_OPTIONS = "try_load_options";
63 64 65 66 67 68 69
const std::string LDBCommand::ARG_FROM = "from";
const std::string LDBCommand::ARG_TO = "to";
const std::string LDBCommand::ARG_MAX_KEYS = "max_keys";
const std::string LDBCommand::ARG_BLOOM_BITS = "bloom_bits";
const std::string LDBCommand::ARG_FIX_PREFIX_LEN = "fix_prefix_len";
const std::string LDBCommand::ARG_COMPRESSION_TYPE = "compression_type";
const std::string LDBCommand::ARG_COMPRESSION_MAX_DICT_BYTES =
70
    "compression_max_dict_bytes";
71 72 73 74 75 76 77
const std::string LDBCommand::ARG_BLOCK_SIZE = "block_size";
const std::string LDBCommand::ARG_AUTO_COMPACTION = "auto_compaction";
const std::string LDBCommand::ARG_DB_WRITE_BUFFER_SIZE = "db_write_buffer_size";
const std::string LDBCommand::ARG_WRITE_BUFFER_SIZE = "write_buffer_size";
const std::string LDBCommand::ARG_FILE_SIZE = "file_size";
const std::string LDBCommand::ARG_CREATE_IF_MISSING = "create_if_missing";
const std::string LDBCommand::ARG_NO_VALUE = "no_value";
78

79
const char* LDBCommand::DELIM = " ==> ";
80

81 82 83 84 85 86 87 88
namespace {

void DumpWalFile(std::string wal_file, bool print_header, bool print_values,
                 LDBCommandExecuteResult* exec_state);

void DumpSstFile(std::string filename, bool output_hex, bool show_properties);
};

89
LDBCommand* LDBCommand::InitFromCmdLineArgs(
S
sdong 已提交
90 91 92
    int argc, char** argv, const Options& options,
    const LDBOptions& ldb_options,
    const std::vector<ColumnFamilyDescriptor>* column_families) {
93
  std::vector<std::string> args;
94 95 96
  for (int i = 1; i < argc; i++) {
    args.push_back(argv[i]);
  }
A
Arun Sharma 已提交
97 98
  return InitFromCmdLineArgs(args, options, ldb_options, column_families,
                             SelectCommand);
99 100 101 102 103 104
}

/**
 * Parse the command-line arguments and create the appropriate LDBCommand2
 * instance.
 * The command line arguments must be in the following format:
105 106
 * ./ldb --db=PATH_TO_DB [--commonOpt1=commonOpt1Val] ..
 *        COMMAND <PARAM1> <PARAM2> ... [-cmdSpecificOpt1=cmdSpecificOpt1Val] ..
107 108
 * This is similar to the command line format used by HBaseClientTool.
 * Command name is not included in args.
109
 * Returns nullptr if the command-line cannot be parsed.
110
 */
111
LDBCommand* LDBCommand::InitFromCmdLineArgs(
112
    const std::vector<std::string>& args, const Options& options,
S
sdong 已提交
113
    const LDBOptions& ldb_options,
A
Arun Sharma 已提交
114
    const std::vector<ColumnFamilyDescriptor>* column_families,
115 116 117 118 119 120 121
    const std::function<LDBCommand*(const ParsedParams&)>& selector) {
  // --x=y command line arguments are added as x->y map entries in
  // parsed_params.option_map.
  //
  // Command-line arguments of the form --hex end up in this array as hex to
  // parsed_params.flags
  ParsedParams parsed_params;
122

123
  // Everything other than option_map and flags. Represents commands
124
  // and their parameters.  For eg: put key1 value1 go into this vector.
125
  std::vector<std::string> cmdTokens;
126

127
  const std::string OPTION_PREFIX = "--";
128

129
  for (const auto& arg : args) {
130
    if (arg[0] == '-' && arg[1] == '-'){
131
      std::vector<std::string> splits = StringSplit(arg, '=');
132
      if (splits.size() == 2) {
133
        std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
134
        parsed_params.option_map[optionKey] = splits[1];
135
      } else {
136
        std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
137
        parsed_params.flags.push_back(optionKey);
138
      }
139
    } else {
140
      cmdTokens.push_back(arg);
141 142 143 144 145
    }
  }

  if (cmdTokens.size() < 1) {
    fprintf(stderr, "Command not specified!");
146
    return nullptr;
147 148
  }

149 150 151 152
  parsed_params.cmd = cmdTokens[0];
  parsed_params.cmd_params.assign(cmdTokens.begin() + 1, cmdTokens.end());

  LDBCommand* command = selector(parsed_params);
153 154

  if (command) {
155 156
    command->SetDBOptions(options);
    command->SetLDBOptions(ldb_options);
157 158 159 160
  }
  return command;
}

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
LDBCommand* LDBCommand::SelectCommand(const ParsedParams& parsed_params) {
  if (parsed_params.cmd == GetCommand::Name()) {
    return new GetCommand(parsed_params.cmd_params, parsed_params.option_map,
                          parsed_params.flags);
  } else if (parsed_params.cmd == PutCommand::Name()) {
    return new PutCommand(parsed_params.cmd_params, parsed_params.option_map,
                          parsed_params.flags);
  } else if (parsed_params.cmd == BatchPutCommand::Name()) {
    return new BatchPutCommand(parsed_params.cmd_params,
                               parsed_params.option_map, parsed_params.flags);
  } else if (parsed_params.cmd == ScanCommand::Name()) {
    return new ScanCommand(parsed_params.cmd_params, parsed_params.option_map,
                           parsed_params.flags);
  } else if (parsed_params.cmd == DeleteCommand::Name()) {
    return new DeleteCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
A
Andrew Kryczka 已提交
177 178 179 180
  } else if (parsed_params.cmd == DeleteRangeCommand::Name()) {
    return new DeleteRangeCommand(parsed_params.cmd_params,
                                  parsed_params.option_map,
                                  parsed_params.flags);
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
  } else if (parsed_params.cmd == ApproxSizeCommand::Name()) {
    return new ApproxSizeCommand(parsed_params.cmd_params,
                                 parsed_params.option_map, parsed_params.flags);
  } else if (parsed_params.cmd == DBQuerierCommand::Name()) {
    return new DBQuerierCommand(parsed_params.cmd_params,
                                parsed_params.option_map, parsed_params.flags);
  } else if (parsed_params.cmd == CompactorCommand::Name()) {
    return new CompactorCommand(parsed_params.cmd_params,
                                parsed_params.option_map, parsed_params.flags);
  } else if (parsed_params.cmd == WALDumperCommand::Name()) {
    return new WALDumperCommand(parsed_params.cmd_params,
                                parsed_params.option_map, parsed_params.flags);
  } else if (parsed_params.cmd == ReduceDBLevelsCommand::Name()) {
    return new ReduceDBLevelsCommand(parsed_params.cmd_params,
                                     parsed_params.option_map,
                                     parsed_params.flags);
  } else if (parsed_params.cmd == ChangeCompactionStyleCommand::Name()) {
    return new ChangeCompactionStyleCommand(parsed_params.cmd_params,
                                            parsed_params.option_map,
                                            parsed_params.flags);
  } else if (parsed_params.cmd == DBDumperCommand::Name()) {
    return new DBDumperCommand(parsed_params.cmd_params,
                               parsed_params.option_map, parsed_params.flags);
  } else if (parsed_params.cmd == DBLoaderCommand::Name()) {
    return new DBLoaderCommand(parsed_params.cmd_params,
                               parsed_params.option_map, parsed_params.flags);
  } else if (parsed_params.cmd == ManifestDumpCommand::Name()) {
    return new ManifestDumpCommand(parsed_params.cmd_params,
                                   parsed_params.option_map,
                                   parsed_params.flags);
  } else if (parsed_params.cmd == ListColumnFamiliesCommand::Name()) {
    return new ListColumnFamiliesCommand(parsed_params.cmd_params,
                                         parsed_params.option_map,
                                         parsed_params.flags);
  } else if (parsed_params.cmd == CreateColumnFamilyCommand::Name()) {
    return new CreateColumnFamilyCommand(parsed_params.cmd_params,
                                         parsed_params.option_map,
                                         parsed_params.flags);
  } else if (parsed_params.cmd == DBFileDumperCommand::Name()) {
    return new DBFileDumperCommand(parsed_params.cmd_params,
                                   parsed_params.option_map,
                                   parsed_params.flags);
  } else if (parsed_params.cmd == InternalDumpCommand::Name()) {
    return new InternalDumpCommand(parsed_params.cmd_params,
                                   parsed_params.option_map,
                                   parsed_params.flags);
  } else if (parsed_params.cmd == CheckConsistencyCommand::Name()) {
    return new CheckConsistencyCommand(parsed_params.cmd_params,
                                       parsed_params.option_map,
                                       parsed_params.flags);
A
Aaron Gao 已提交
231 232 233 234
  } else if (parsed_params.cmd == CheckPointCommand::Name()) {
    return new CheckPointCommand(parsed_params.cmd_params,
                                 parsed_params.option_map,
                                 parsed_params.flags);
235 236 237
  } else if (parsed_params.cmd == RepairCommand::Name()) {
    return new RepairCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
W
Wanning Jiang 已提交
238 239 240
  } else if (parsed_params.cmd == BackupCommand::Name()) {
    return new BackupCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
A
Andrew Kryczka 已提交
241 242 243
  } else if (parsed_params.cmd == RestoreCommand::Name()) {
    return new RestoreCommand(parsed_params.cmd_params,
                              parsed_params.option_map, parsed_params.flags);
244
  }
245
  return nullptr;
246 247
}

A
Arun Sharma 已提交
248 249 250 251 252 253 254 255
/* Run the command, and return the execute result. */
void LDBCommand::Run() {
  if (!exec_state_.IsNotStarted()) {
    return;
  }

  if (db_ == nullptr && !NoDBOpen()) {
    OpenDB();
256 257 258 259 260 261
    if (exec_state_.IsFailed() && try_load_options_) {
      // We don't always return if there is a failure because a WAL file or
      // manifest file can be given to "dump" command so we should continue.
      // --try_load_options is not valid in those cases.
      return;
    }
A
Arun Sharma 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  }

  // We'll intentionally proceed even if the DB can't be opened because users
  // can also specify a filename, not just a directory.
  DoCommand();

  if (exec_state_.IsNotStarted()) {
    exec_state_ = LDBCommandExecuteResult::Succeed("");
  }

  if (db_ != nullptr) {
    CloseDB();
  }
}

277 278 279
LDBCommand::LDBCommand(const std::map<std::string, std::string>& options,
                       const std::vector<std::string>& flags, bool is_read_only,
                       const std::vector<std::string>& valid_cmd_line_options)
A
Arun Sharma 已提交
280 281 282 283 284 285
    : db_(nullptr),
      is_read_only_(is_read_only),
      is_key_hex_(false),
      is_value_hex_(false),
      is_db_ttl_(false),
      timestamp_(false),
286 287
      try_load_options_(false),
      create_if_missing_(false),
A
Arun Sharma 已提交
288 289 290
      option_map_(options),
      flags_(flags),
      valid_cmd_line_options_(valid_cmd_line_options) {
291
  std::map<std::string, std::string>::const_iterator itr = options.find(ARG_DB);
A
Arun Sharma 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  if (itr != options.end()) {
    db_path_ = itr->second;
  }

  itr = options.find(ARG_CF_NAME);
  if (itr != options.end()) {
    column_family_name_ = itr->second;
  } else {
    column_family_name_ = kDefaultColumnFamilyName;
  }

  is_key_hex_ = IsKeyHex(options, flags);
  is_value_hex_ = IsValueHex(options, flags);
  is_db_ttl_ = IsFlagPresent(flags, ARG_TTL);
  timestamp_ = IsFlagPresent(flags, ARG_TIMESTAMP);
307
  try_load_options_ = IsFlagPresent(flags, ARG_TRY_LOAD_OPTIONS);
A
Arun Sharma 已提交
308 309 310
}

void LDBCommand::OpenDB() {
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
  Options opt;
  bool opt_set = false;
  if (!create_if_missing_ && try_load_options_) {
    Status s =
        LoadLatestOptions(db_path_, Env::Default(), &opt, &column_families_);
    if (s.ok()) {
      opt_set = true;
    } else if (!s.IsNotFound()) {
      // Option file exists but load option file error.
      std::string msg = s.ToString();
      exec_state_ = LDBCommandExecuteResult::Failed(msg);
      db_ = nullptr;
      return;
    }
  }
  if (!opt_set) {
    opt = PrepareOptionsForOpenDB();
  }
A
Arun Sharma 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
  if (!exec_state_.IsNotStarted()) {
    return;
  }
  // Open the DB.
  Status st;
  std::vector<ColumnFamilyHandle*> handles_opened;
  if (is_db_ttl_) {
    // ldb doesn't yet support TTL DB with multiple column families
    if (!column_family_name_.empty() || !column_families_.empty()) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "ldb doesn't support TTL DB with multiple column families");
    }
    if (is_read_only_) {
      st = DBWithTTL::Open(opt, db_path_, &db_ttl_, 0, true);
    } else {
      st = DBWithTTL::Open(opt, db_path_, &db_ttl_);
    }
    db_ = db_ttl_;
  } else {
348
    if (!opt_set && column_families_.empty()) {
A
Arun Sharma 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
      // Try to figure out column family lists
      std::vector<std::string> cf_list;
      st = DB::ListColumnFamilies(DBOptions(), db_path_, &cf_list);
      // There is possible the DB doesn't exist yet, for "create if not
      // "existing case". The failure is ignored here. We rely on DB::Open()
      // to give us the correct error message for problem with opening
      // existing DB.
      if (st.ok() && cf_list.size() > 1) {
        // Ignore single column family DB.
        for (auto cf_name : cf_list) {
          column_families_.emplace_back(cf_name, opt);
        }
      }
    }
    if (is_read_only_) {
      if (column_families_.empty()) {
        st = DB::OpenForReadOnly(opt, db_path_, &db_);
      } else {
        st = DB::OpenForReadOnly(opt, db_path_, column_families_,
                                 &handles_opened, &db_);
      }
    } else {
      if (column_families_.empty()) {
        st = DB::Open(opt, db_path_, &db_);
      } else {
        st = DB::Open(opt, db_path_, column_families_, &handles_opened, &db_);
      }
    }
  }
  if (!st.ok()) {
379
    std::string msg = st.ToString();
A
Arun Sharma 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    exec_state_ = LDBCommandExecuteResult::Failed(msg);
  } else if (!handles_opened.empty()) {
    assert(handles_opened.size() == column_families_.size());
    bool found_cf_name = false;
    for (size_t i = 0; i < handles_opened.size(); i++) {
      cf_handles_[column_families_[i].name] = handles_opened[i];
      if (column_family_name_ == column_families_[i].name) {
        found_cf_name = true;
      }
    }
    if (!found_cf_name) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Non-existing column family " + column_family_name_);
      CloseDB();
    }
  } else {
    // We successfully opened DB in single column family mode.
    assert(column_families_.empty());
    if (column_family_name_ != kDefaultColumnFamilyName) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Non-existing column family " + column_family_name_);
      CloseDB();
    }
  }

  options_ = opt;
}

void LDBCommand::CloseDB() {
  if (db_ != nullptr) {
    for (auto& pair : cf_handles_) {
      delete pair.second;
    }
    delete db_;
    db_ = nullptr;
  }
}

ColumnFamilyHandle* LDBCommand::GetCfHandle() {
  if (!cf_handles_.empty()) {
    auto it = cf_handles_.find(column_family_name_);
    if (it == cf_handles_.end()) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Cannot find column family " + column_family_name_);
    } else {
      return it->second;
    }
  }
  return db_->DefaultColumnFamily();
}

431 432 433 434 435 436 437 438 439 440 441
std::vector<std::string> LDBCommand::BuildCmdLineOptions(
    std::vector<std::string> options) {
  std::vector<std::string> ret = {ARG_DB,
                                  ARG_BLOOM_BITS,
                                  ARG_BLOCK_SIZE,
                                  ARG_AUTO_COMPACTION,
                                  ARG_COMPRESSION_TYPE,
                                  ARG_COMPRESSION_MAX_DICT_BYTES,
                                  ARG_WRITE_BUFFER_SIZE,
                                  ARG_FILE_SIZE,
                                  ARG_FIX_PREFIX_LEN,
442
                                  ARG_TRY_LOAD_OPTIONS,
443
                                  ARG_CF_NAME};
A
Arun Sharma 已提交
444 445 446
  ret.insert(ret.end(), options.begin(), options.end());
  return ret;
}
447

448 449 450 451 452 453 454
/**
 * Parses the specific integer option and fills in the value.
 * Returns true if the option is found.
 * Returns false if the option is not found or if there is an error parsing the
 * value.  If there is an error, the specified exec_state is also
 * updated.
 */
455 456 457 458 459 460
bool LDBCommand::ParseIntOption(
    const std::map<std::string, std::string>& options,
    const std::string& option, int& value,
    LDBCommandExecuteResult& exec_state) {
  std::map<std::string, std::string>::const_iterator itr =
      option_map_.find(option);
461
  if (itr != option_map_.end()) {
462
    try {
S
sdong 已提交
463 464 465
#if defined(CYGWIN)
      value = strtol(itr->second.c_str(), 0, 10);
#else
466
      value = std::stoi(itr->second);
S
sdong 已提交
467
#endif
468
      return true;
469
    } catch (const std::invalid_argument&) {
470 471
      exec_state =
          LDBCommandExecuteResult::Failed(option + " has an invalid value.");
472
    } catch (const std::out_of_range&) {
473 474
      exec_state = LDBCommandExecuteResult::Failed(
          option + " has a value out-of-range.");
475 476
    }
  }
477
  return false;
478 479
}

480 481 482 483 484
/**
 * Parses the specified option and fills in the value.
 * Returns true if the option is found.
 * Returns false otherwise.
 */
485 486 487
bool LDBCommand::ParseStringOption(
    const std::map<std::string, std::string>& options,
    const std::string& option, std::string* value) {
488 489 490 491 492 493 494 495
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
    *value = itr->second;
    return true;
  }
  return false;
}

496
Options LDBCommand::PrepareOptionsForOpenDB() {
497

498
  Options opt = options_;
499
  opt.create_if_missing = false;
500

501
  std::map<std::string, std::string>::const_iterator itr;
502

503
  BlockBasedTableOptions table_options;
S
sdong 已提交
504
  bool use_table_options = false;
505
  int bits;
506
  if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
507
    if (bits > 0) {
S
sdong 已提交
508
      use_table_options = true;
509
      table_options.filter_policy.reset(NewBloomFilterPolicy(bits));
510
    } else {
511 512
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOOM_BITS + " must be > 0.");
513 514 515 516
    }
  }

  int block_size;
517
  if (ParseIntOption(option_map_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
518
    if (block_size > 0) {
S
sdong 已提交
519
      use_table_options = true;
520
      table_options.block_size = block_size;
521
    } else {
522 523
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOCK_SIZE + " must be > 0.");
524 525 526
    }
  }

S
sdong 已提交
527 528 529 530
  if (use_table_options) {
    opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  }

531 532
  itr = option_map_.find(ARG_AUTO_COMPACTION);
  if (itr != option_map_.end()) {
533 534 535
    opt.disable_auto_compactions = ! StringToBool(itr->second);
  }

536 537
  itr = option_map_.find(ARG_COMPRESSION_TYPE);
  if (itr != option_map_.end()) {
538
    std::string comp = itr->second;
539
    if (comp == "no") {
540
      opt.compression = kNoCompression;
541
    } else if (comp == "snappy") {
542
      opt.compression = kSnappyCompression;
543
    } else if (comp == "zlib") {
544
      opt.compression = kZlibCompression;
545
    } else if (comp == "bzip2") {
546
      opt.compression = kBZip2Compression;
A
Albert Strasheim 已提交
547 548 549 550
    } else if (comp == "lz4") {
      opt.compression = kLZ4Compression;
    } else if (comp == "lz4hc") {
      opt.compression = kLZ4HCCompression;
551 552
    } else if (comp == "xpress") {
      opt.compression = kXpressCompression;
553
    } else if (comp == "zstd") {
S
sdong 已提交
554
      opt.compression = kZSTD;
555 556
    } else {
      // Unknown compression.
557 558
      exec_state_ =
          LDBCommandExecuteResult::Failed("Unknown compression level: " + comp);
559 560 561
    }
  }

562 563 564 565 566 567 568 569 570 571 572
  int compression_max_dict_bytes;
  if (ParseIntOption(option_map_, ARG_COMPRESSION_MAX_DICT_BYTES,
                     compression_max_dict_bytes, exec_state_)) {
    if (compression_max_dict_bytes >= 0) {
      opt.compression_opts.max_dict_bytes = compression_max_dict_bytes;
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_COMPRESSION_MAX_DICT_BYTES + " must be >= 0.");
    }
  }

573 574 575 576 577 578
  int db_write_buffer_size;
  if (ParseIntOption(option_map_, ARG_DB_WRITE_BUFFER_SIZE,
        db_write_buffer_size, exec_state_)) {
    if (db_write_buffer_size >= 0) {
      opt.db_write_buffer_size = db_write_buffer_size;
    } else {
579
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_DB_WRITE_BUFFER_SIZE +
580
                                                    " must be >= 0.");
581 582 583
    }
  }

584
  int write_buffer_size;
585 586
  if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
        exec_state_)) {
587
    if (write_buffer_size > 0) {
588
      opt.write_buffer_size = write_buffer_size;
589
    } else {
590
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_WRITE_BUFFER_SIZE +
591
                                                    " must be > 0.");
592 593 594 595
    }
  }

  int file_size;
596
  if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
597
    if (file_size > 0) {
598 599
      opt.target_file_size_base = file_size;
    } else {
600 601
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_FILE_SIZE + " must be > 0.");
602 603 604
    }
  }

605
  if (opt.db_paths.size() == 0) {
606
    opt.db_paths.emplace_back(db_path_, std::numeric_limits<uint64_t>::max());
607 608
  }

S
sdong 已提交
609
  int fix_prefix_len;
610 611
  if (ParseIntOption(option_map_, ARG_FIX_PREFIX_LEN, fix_prefix_len,
                     exec_state_)) {
S
sdong 已提交
612 613 614 615
    if (fix_prefix_len > 0) {
      opt.prefix_extractor.reset(
          NewFixedPrefixTransform(static_cast<size_t>(fix_prefix_len)));
    } else {
616
      exec_state_ =
617
          LDBCommandExecuteResult::Failed(ARG_FIX_PREFIX_LEN + " must be > 0.");
S
sdong 已提交
618 619 620
    }
  }

621 622 623
  return opt;
}

624 625 626
bool LDBCommand::ParseKeyValue(const std::string& line, std::string* key,
                               std::string* value, bool is_key_hex,
                               bool is_value_hex) {
627
  size_t pos = line.find(DELIM);
628
  if (pos != std::string::npos) {
629 630 631 632 633 634 635 636 637 638 639 640 641
    *key = line.substr(0, pos);
    *value = line.substr(pos + strlen(DELIM));
    if (is_key_hex) {
      *key = HexToString(*key);
    }
    if (is_value_hex) {
      *value = HexToString(*value);
    }
    return true;
  } else {
    return false;
  }
}
642

643 644 645 646 647 648 649 650
/**
 * Make sure that ONLY the command-line options and flags expected by this
 * command are specified on the command-line.  Extraneous options are usually
 * the result of user error.
 * Returns true if all checks pass.  Else returns false, and prints an
 * appropriate error msg to stderr.
 */
bool LDBCommand::ValidateCmdLineOptions() {
651 652 653 654 655 656
  for (std::map<std::string, std::string>::const_iterator itr =
           option_map_.begin();
       itr != option_map_.end(); ++itr) {
    if (std::find(valid_cmd_line_options_.begin(),
                  valid_cmd_line_options_.end(),
                  itr->first) == valid_cmd_line_options_.end()) {
657 658 659 660
      fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
      return false;
    }
  }
661

662 663 664 665 666
  for (std::vector<std::string>::const_iterator itr = flags_.begin();
       itr != flags_.end(); ++itr) {
    if (std::find(valid_cmd_line_options_.begin(),
                  valid_cmd_line_options_.end(),
                  *itr) == valid_cmd_line_options_.end()) {
667 668
      fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
      return false;
669 670 671
    }
  }

672 673 674 675
  if (!NoDBOpen() && option_map_.find(ARG_DB) == option_map_.end() &&
      option_map_.find(ARG_PATH) == option_map_.end()) {
    fprintf(stderr, "Either %s or %s must be specified.\n", ARG_DB.c_str(),
            ARG_PATH.c_str());
676 677 678 679 680 681
    return false;
  }

  return true;
}

682 683
std::string LDBCommand::HexToString(const std::string& str) {
  std::string result;
A
Arun Sharma 已提交
684 685 686 687 688 689 690 691 692 693 694
  std::string::size_type len = str.length();
  if (len < 2 || str[0] != '0' || str[1] != 'x') {
    fprintf(stderr, "Invalid hex input %s.  Must start with 0x\n", str.c_str());
    throw "Invalid hex input";
  }
  if (!Slice(str.data() + 2, len - 2).DecodeHex(&result)) {
    throw "Invalid hex input";
  }
  return result;
}

695 696
std::string LDBCommand::StringToHex(const std::string& str) {
  std::string result("0x");
A
Arun Sharma 已提交
697 698 699 700
  result.append(Slice(str).ToString(true));
  return result;
}

701 702 703 704
std::string LDBCommand::PrintKeyValue(const std::string& key,
                                      const std::string& value, bool is_key_hex,
                                      bool is_value_hex) {
  std::string result;
A
Arun Sharma 已提交
705 706 707 708 709 710
  result.append(is_key_hex ? StringToHex(key) : key);
  result.append(DELIM);
  result.append(is_value_hex ? StringToHex(value) : value);
  return result;
}

711 712
std::string LDBCommand::PrintKeyValue(const std::string& key,
                                      const std::string& value, bool is_hex) {
A
Arun Sharma 已提交
713 714 715
  return PrintKeyValue(key, value, is_hex, is_hex);
}

716
std::string LDBCommand::HelpRangeCmdArgs() {
A
Arun Sharma 已提交
717 718 719 720 721 722 723
  std::ostringstream str_stream;
  str_stream << " ";
  str_stream << "[--" << ARG_FROM << "] ";
  str_stream << "[--" << ARG_TO << "] ";
  return str_stream.str();
}

724 725
bool LDBCommand::IsKeyHex(const std::map<std::string, std::string>& options,
                          const std::vector<std::string>& flags) {
A
Arun Sharma 已提交
726 727 728 729 730
  return (IsFlagPresent(flags, ARG_HEX) || IsFlagPresent(flags, ARG_KEY_HEX) ||
          ParseBooleanOption(options, ARG_HEX, false) ||
          ParseBooleanOption(options, ARG_KEY_HEX, false));
}

731 732
bool LDBCommand::IsValueHex(const std::map<std::string, std::string>& options,
                            const std::vector<std::string>& flags) {
A
Arun Sharma 已提交
733 734 735 736 737 738
  return (IsFlagPresent(flags, ARG_HEX) ||
          IsFlagPresent(flags, ARG_VALUE_HEX) ||
          ParseBooleanOption(options, ARG_HEX, false) ||
          ParseBooleanOption(options, ARG_VALUE_HEX, false));
}

739 740 741 742
bool LDBCommand::ParseBooleanOption(
    const std::map<std::string, std::string>& options,
    const std::string& option, bool default_val) {
  std::map<std::string, std::string>::const_iterator itr = options.find(option);
A
Arun Sharma 已提交
743
  if (itr != options.end()) {
744
    std::string option_val = itr->second;
A
Arun Sharma 已提交
745 746 747 748 749
    return StringToBool(itr->second);
  }
  return default_val;
}

750
bool LDBCommand::StringToBool(std::string val) {
A
Arun Sharma 已提交
751 752 753 754 755 756 757 758 759 760 761 762
  std::transform(val.begin(), val.end(), val.begin(),
                 [](char ch) -> char { return (char)::tolower(ch); });

  if (val == "true") {
    return true;
  } else if (val == "false") {
    return false;
  } else {
    throw "Invalid value for boolean argument";
  }
}

763 764 765 766 767 768 769 770 771 772 773
CompactorCommand::CompactorCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions({ARG_FROM, ARG_TO, ARG_HEX, ARG_KEY_HEX,
                                      ARG_VALUE_HEX, ARG_TTL})),
      null_from_(true),
      null_to_(true) {
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_FROM);
774 775 776 777 778 779 780 781 782 783 784 785
  if (itr != options.end()) {
    null_from_ = false;
    from_ = itr->second;
  }

  itr = options.find(ARG_TO);
  if (itr != options.end()) {
    null_to_ = false;
    to_ = itr->second;
  }

  if (is_key_hex_) {
786 787 788 789 790 791 792 793 794
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

795
void CompactorCommand::Help(std::string& ret) {
796 797 798 799
  ret.append("  ");
  ret.append(CompactorCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
800 801
}

802
void CompactorCommand::DoCommand() {
S
sdong 已提交
803 804 805 806
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
807

808 809
  Slice* begin = nullptr;
  Slice* end = nullptr;
810
  if (!null_from_) {
811
    begin = new Slice(from_);
812 813
  }
  if (!null_to_) {
814
    end = new Slice(to_);
815 816
  }

817 818 819
  CompactRangeOptions cro;
  cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;

820
  db_->CompactRange(cro, GetCfHandle(), begin, end);
821
  exec_state_ = LDBCommandExecuteResult::Succeed("");
822 823 824 825 826

  delete begin;
  delete end;
}

827 828
// ----------------------------------------------------------------------------

829 830 831
const std::string DBLoaderCommand::ARG_DISABLE_WAL = "disable_wal";
const std::string DBLoaderCommand::ARG_BULK_LOAD = "bulk_load";
const std::string DBLoaderCommand::ARG_COMPACT = "compact";
832

833 834 835 836 837 838 839 840 841 842 843 844
DBLoaderCommand::DBLoaderCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(
          options, flags, false,
          BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
                               ARG_TO, ARG_CREATE_IF_MISSING, ARG_DISABLE_WAL,
                               ARG_BULK_LOAD, ARG_COMPACT})),
      disable_wal_(false),
      bulk_load_(false),
      compact_(false) {
845 846
  create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
847 848
  bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  compact_ = IsFlagPresent(flags, ARG_COMPACT);
Z
Zheng Shao 已提交
849 850
}

851
void DBLoaderCommand::Help(std::string& ret) {
852 853 854 855 856 857 858
  ret.append("  ");
  ret.append(DBLoaderCommand::Name());
  ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
  ret.append(" [--" + ARG_DISABLE_WAL + "]");
  ret.append(" [--" + ARG_BULK_LOAD + "]");
  ret.append(" [--" + ARG_COMPACT + "]");
  ret.append("\n");
Z
Zheng Shao 已提交
859 860
}

861 862
Options DBLoaderCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
Z
Zheng Shao 已提交
863
  opt.create_if_missing = create_if_missing_;
864 865 866
  if (bulk_load_) {
    opt.PrepareForBulkLoad();
  }
Z
Zheng Shao 已提交
867 868 869
  return opt;
}

870
void DBLoaderCommand::DoCommand() {
Z
Zheng Shao 已提交
871
  if (!db_) {
S
sdong 已提交
872
    assert(GetExecuteState().IsFailed());
Z
Zheng Shao 已提交
873 874 875 876 877 878 879 880 881
    return;
  }

  WriteOptions write_options;
  if (disable_wal_) {
    write_options.disableWAL = true;
  }

  int bad_lines = 0;
882
  std::string line;
883 884 885 886
  // prefer ifstream getline performance vs that from std::cin istream
  std::ifstream ifs_stdin("/dev/stdin");
  std::istream* istream_p = ifs_stdin.is_open() ? &ifs_stdin : &std::cin;
  while (getline(*istream_p, line, '\n')) {
887 888
    std::string key;
    std::string value;
889
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
S
sdong 已提交
890
      db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
Z
Zheng Shao 已提交
891 892 893 894 895 896 897 898
    } else if (0 == line.find("Keys in range:")) {
      // ignore this line
    } else if (0 == line.find("Created bg thread 0x")) {
      // ignore this line
    } else {
      bad_lines ++;
    }
  }
899

Z
Zheng Shao 已提交
900
  if (bad_lines > 0) {
901
    std::cout << "Warning: " << bad_lines << " bad lines ignored." << std::endl;
Z
Zheng Shao 已提交
902
  }
903
  if (compact_) {
S
sdong 已提交
904
    db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);
905
  }
Z
Zheng Shao 已提交
906 907
}

908 909
// ----------------------------------------------------------------------------

910 911
namespace {

912
void DumpManifestFile(std::string file, bool verbose, bool hex, bool json) {
913 914 915
  Options options;
  EnvOptions sopt;
  std::string dbname("dummy");
916 917
  std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
                                        options.table_cache_numshardbits));
918 919 920 921
  // Notice we are using the default options not through SanitizeOptions(),
  // if VersionSet::DumpManifest() depends on any option done by
  // SanitizeOptions(), we need to initialize it manually.
  options.db_paths.emplace_back("dummy", 0);
922
  options.num_levels = 64;
S
sdong 已提交
923
  WriteController wc(options.delayed_write_rate);
924
  WriteBufferManager wb(options.db_write_buffer_size);
925 926
  ImmutableDBOptions immutable_db_options(options);
  VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc);
927
  Status s = versions.DumpManifest(options, file, verbose, hex, json);
928 929 930 931 932 933 934 935
  if (!s.ok()) {
    printf("Error in processing file %s %s\n", file.c_str(),
           s.ToString().c_str());
  }
}

}  // namespace

936 937 938
const std::string ManifestDumpCommand::ARG_VERBOSE = "verbose";
const std::string ManifestDumpCommand::ARG_JSON = "json";
const std::string ManifestDumpCommand::ARG_PATH = "path";
939

940
void ManifestDumpCommand::Help(std::string& ret) {
941 942 943
  ret.append("  ");
  ret.append(ManifestDumpCommand::Name());
  ret.append(" [--" + ARG_VERBOSE + "]");
944
  ret.append(" [--" + ARG_JSON + "]");
945 946
  ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  ret.append("\n");
947 948
}

949 950 951 952 953 954 955 956 957 958
ManifestDumpCommand::ManifestDumpCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(
          options, flags, false,
          BuildCmdLineOptions({ARG_VERBOSE, ARG_PATH, ARG_HEX, ARG_JSON})),
      verbose_(false),
      json_(false),
      path_("") {
959
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
960
  json_ = IsFlagPresent(flags, ARG_JSON);
961

962 963
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_PATH);
964 965 966
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
967
      exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
968 969 970 971 972 973 974 975 976 977 978 979 980 981
    }
  }
}

void ManifestDumpCommand::DoCommand() {

  std::string manifestfile;

  if (!path_.empty()) {
    manifestfile = path_;
  } else {
    bool found = false;
    // We need to find the manifest file by searching the directory
    // containing the db for files of the form MANIFEST_[0-9]+
D
Dmitri Smirnov 已提交
982 983

    auto CloseDir = [](DIR* p) { closedir(p); };
S
sdong 已提交
984 985
    std::unique_ptr<DIR, decltype(CloseDir)> d(opendir(db_path_.c_str()),
                                               CloseDir);
D
Dmitri Smirnov 已提交
986

987
    if (d == nullptr) {
988 989
      exec_state_ =
          LDBCommandExecuteResult::Failed(db_path_ + " is not a directory");
990 991 992
      return;
    }
    struct dirent* entry;
D
Dmitri Smirnov 已提交
993
    while ((entry = readdir(d.get())) != nullptr) {
994
      unsigned int match;
995
      uint64_t num;
996
      if (sscanf(entry->d_name, "MANIFEST-%" PRIu64 "%n", &num, &match) &&
997
          match == strlen(entry->d_name)) {
998 999 1000 1001
        if (!found) {
          manifestfile = db_path_ + "/" + std::string(entry->d_name);
          found = true;
        } else {
1002
          exec_state_ = LDBCommandExecuteResult::Failed(
1003
              "Multiple MANIFEST files found; use --path to select one");
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
          return;
        }
      }
    }
  }

  if (verbose_) {
    printf("Processing Manifest file %s\n", manifestfile.c_str());
  }

1014 1015
  DumpManifestFile(manifestfile, verbose_, is_key_hex_, json_);

1016 1017 1018 1019 1020 1021
  if (verbose_) {
    printf("Processing Manifest file %s done\n", manifestfile.c_str());
  }
}

// ----------------------------------------------------------------------------
1022

1023
void ListColumnFamiliesCommand::Help(std::string& ret) {
1024 1025 1026 1027
  ret.append("  ");
  ret.append(ListColumnFamiliesCommand::Name());
  ret.append(" full_path_to_db_directory ");
  ret.append("\n");
1028 1029 1030
}

ListColumnFamiliesCommand::ListColumnFamiliesCommand(
1031 1032 1033
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1034 1035
    : LDBCommand(options, flags, false, {}) {
  if (params.size() != 1) {
1036
    exec_state_ = LDBCommandExecuteResult::Failed(
1037 1038 1039 1040 1041 1042 1043
        "dbname must be specified for the list_column_families command");
  } else {
    dbname_ = params[0];
  }
}

void ListColumnFamiliesCommand::DoCommand() {
1044
  std::vector<std::string> column_families;
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  Status s = DB::ListColumnFamilies(DBOptions(), dbname_, &column_families);
  if (!s.ok()) {
    printf("Error in processing db %s %s\n", dbname_.c_str(),
           s.ToString().c_str());
  } else {
    printf("Column families in %s: \n{", dbname_.c_str());
    bool first = true;
    for (auto cf : column_families) {
      if (!first) {
        printf(", ");
      }
      first = false;
      printf("%s", cf.c_str());
    }
    printf("}\n");
  }
}

1063
void CreateColumnFamilyCommand::Help(std::string& ret) {
S
sdong 已提交
1064 1065 1066 1067 1068 1069 1070
  ret.append("  ");
  ret.append(CreateColumnFamilyCommand::Name());
  ret.append(" --db=<db_path> <new_column_family_name>");
  ret.append("\n");
}

CreateColumnFamilyCommand::CreateColumnFamilyCommand(
1071 1072 1073
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
S
sdong 已提交
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    : LDBCommand(options, flags, true, {ARG_DB}) {
  if (params.size() != 1) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "new column family name must be specified");
  } else {
    new_cf_name_ = params[0];
  }
}

void CreateColumnFamilyCommand::DoCommand() {
  ColumnFamilyHandle* new_cf_handle;
  Status st = db_->CreateColumnFamily(options_, new_cf_name_, &new_cf_handle);
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "Fail to create new column family: " + st.ToString());
  }
  delete new_cf_handle;
  CloseDB();
}

1096
// ----------------------------------------------------------------------------
1097

I
Igor Canadi 已提交
1098 1099
namespace {

1100
std::string ReadableTime(int unixtime) {
1101 1102
  char time_buffer [80];
  time_t rawtime = unixtime;
1103 1104 1105
  struct tm tInfo;
  struct tm* timeinfo = localtime_r(&rawtime, &tInfo);
  assert(timeinfo == &tInfo);
1106
  strftime(time_buffer, 80, "%c", timeinfo);
1107
  return std::string(time_buffer);
1108 1109 1110 1111
}

// This function only called when it's the sane case of >1 buckets in time-range
// Also called only when timekv falls between ttl_start and ttl_end provided
1112 1113 1114
void IncBucketCounts(std::vector<uint64_t>& bucket_counts, int ttl_start,
                     int time_range, int bucket_size, int timekv,
                     int num_buckets) {
1115 1116 1117
  assert(time_range > 0 && timekv >= ttl_start && bucket_size > 0 &&
    timekv < (ttl_start + time_range) && num_buckets > 1);
  int bucket = (timekv - ttl_start) / bucket_size;
1118
  bucket_counts[bucket]++;
1119 1120
}

1121 1122 1123
void PrintBucketCounts(const std::vector<uint64_t>& bucket_counts,
                       int ttl_start, int ttl_end, int bucket_size,
                       int num_buckets) {
1124
  int time_point = ttl_start;
1125 1126
  for(int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
    fprintf(stdout, "Keys in range %s to %s : %lu\n",
1127
            ReadableTime(time_point).c_str(),
K
Kai Liu 已提交
1128
            ReadableTime(time_point + bucket_size).c_str(),
1129
            (unsigned long)bucket_counts[i]);
1130
  }
1131
  fprintf(stdout, "Keys in range %s to %s : %lu\n",
1132
          ReadableTime(time_point).c_str(),
K
Kai Liu 已提交
1133
          ReadableTime(ttl_end).c_str(),
1134
          (unsigned long)bucket_counts[num_buckets - 1]);
1135 1136
}

I
Igor Canadi 已提交
1137 1138
}  // namespace

1139 1140 1141 1142
const std::string InternalDumpCommand::ARG_COUNT_ONLY = "count_only";
const std::string InternalDumpCommand::ARG_COUNT_DELIM = "count_delim";
const std::string InternalDumpCommand::ARG_STATS = "stats";
const std::string InternalDumpCommand::ARG_INPUT_KEY_HEX = "input_key_hex";
1143

1144 1145 1146 1147
InternalDumpCommand::InternalDumpCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    : LDBCommand(
          options, flags, true,
          BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
                               ARG_TO, ARG_MAX_KEYS, ARG_COUNT_ONLY,
                               ARG_COUNT_DELIM, ARG_STATS, ARG_INPUT_KEY_HEX})),
      has_from_(false),
      has_to_(false),
      max_keys_(-1),
      delim_("."),
      count_only_(false),
      count_delim_(false),
      print_stats_(false),
      is_input_key_hex_(false) {
1161 1162 1163
  has_from_ = ParseStringOption(options, ARG_FROM, &from_);
  has_to_ = ParseStringOption(options, ARG_TO, &to_);

1164
  ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
1165 1166
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_COUNT_DELIM);
1167 1168 1169
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
1170
   // fprintf(stdout,"delim = %c\n",delim_[0]);
1171 1172
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
1173
    delim_=".";
1174
  }
1175 1176 1177

  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
1178
  is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
1179

1180
  if (is_input_key_hex_) {
1181 1182 1183 1184 1185 1186 1187 1188 1189
    if (has_from_) {
      from_ = HexToString(from_);
    }
    if (has_to_) {
      to_ = HexToString(to_);
    }
  }
}

1190
void InternalDumpCommand::Help(std::string& ret) {
1191 1192 1193 1194 1195 1196 1197 1198 1199
  ret.append("  ");
  ret.append(InternalDumpCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append(" [--" + ARG_INPUT_KEY_HEX + "]");
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  ret.append(" [--" + ARG_COUNT_ONLY + "]");
  ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
  ret.append(" [--" + ARG_STATS + "]");
  ret.append("\n");
1200 1201 1202 1203
}

void InternalDumpCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
1204
    assert(GetExecuteState().IsFailed());
1205 1206 1207 1208
    return;
  }

  if (print_stats_) {
1209
    std::string stats;
S
sdong 已提交
1210
    if (db_->GetProperty(GetCfHandle(), "rocksdb.stats", &stats)) {
1211 1212 1213 1214 1215
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Cast as DBImpl to get internal iterator
A
Andrew Kryczka 已提交
1216 1217 1218 1219
  std::vector<KeyVersion> key_versions;
  Status st = GetAllKeyVersions(db_, from_, to_, &key_versions);
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1220 1221
    return;
  }
1222
  std::string rtype1, rtype2, row, val;
1223
  rtype2 = "";
1224 1225
  uint64_t c=0;
  uint64_t s1=0,s2=0;
1226

1227
  long long count = 0;
A
Andrew Kryczka 已提交
1228 1229 1230 1231 1232 1233
  for (auto& key_version : key_versions) {
    InternalKey ikey(key_version.user_key, key_version.sequence,
                     static_cast<ValueType>(key_version.type));
    if (has_to_ && ikey.user_key() == to_) {
      // GetAllKeyVersions() includes keys with user key `to_`, but idump has
      // traditionally excluded such keys.
1234 1235 1236
      break;
    }
    ++count;
1237 1238 1239
    int k;
    if (count_delim_) {
      rtype1 = "";
1240
      s1=0;
A
Andrew Kryczka 已提交
1241 1242
      row = ikey.Encode().ToString();
      val = key_version.value;
1243
      for(k=0;row[k]!='\x01' && row[k]!='\0';k++)
1244
        s1++;
1245
      for(k=0;val[k]!='\x01' && val[k]!='\0';k++)
1246
        s1++;
1247 1248 1249 1250 1251 1252 1253
      for(int j=0;row[j]!=delim_[0] && row[j]!='\0' && row[j]!='\x01';j++)
        rtype1+=row[j];
      if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
        fprintf(stdout,"%s => count:%lld\tsize:%lld\n",rtype2.c_str(),
            (long long)c,(long long)s2);
        c=1;
        s2=s1;
1254 1255 1256
        rtype2 = rtype1;
      } else {
        c++;
1257 1258
        s2+=s1;
        rtype2=rtype1;
A
Andrew Kryczka 已提交
1259
      }
1260
    }
1261

1262
    if (!count_only_ && !count_delim_) {
1263
      std::string key = ikey.DebugString(is_key_hex_);
A
Andrew Kryczka 已提交
1264
      std::string value = Slice(key_version.value).ToString(is_value_hex_);
1265
      std::cout << key << " => " << value << "\n";
1266 1267 1268
    }

    // Terminate if maximum number of keys have been dumped
1269
    if (max_keys_ > 0 && count >= max_keys_) break;
1270
  }
1271 1272 1273
  if(count_delim_) {
    fprintf(stdout,"%s => count:%lld\tsize:%lld\n", rtype2.c_str(),
        (long long)c,(long long)s2);
1274
  } else
1275
  fprintf(stdout, "Internal keys in range: %lld\n", (long long) count);
1276 1277
}

1278 1279 1280 1281
const std::string DBDumperCommand::ARG_COUNT_ONLY = "count_only";
const std::string DBDumperCommand::ARG_COUNT_DELIM = "count_delim";
const std::string DBDumperCommand::ARG_STATS = "stats";
const std::string DBDumperCommand::ARG_TTL_BUCKET = "bucket";
1282

1283 1284 1285 1286
DBDumperCommand::DBDumperCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
    : LDBCommand(options, flags, true,
                 BuildCmdLineOptions(
                     {ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
                      ARG_TO, ARG_MAX_KEYS, ARG_COUNT_ONLY, ARG_COUNT_DELIM,
                      ARG_STATS, ARG_TTL_START, ARG_TTL_END, ARG_TTL_BUCKET,
                      ARG_TIMESTAMP, ARG_PATH})),
      null_from_(true),
      null_to_(true),
      max_keys_(-1),
      count_only_(false),
      count_delim_(false),
      print_stats_(false) {
1299 1300
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_FROM);
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
  if (itr != options.end()) {
    null_from_ = false;
    from_ = itr->second;
  }

  itr = options.find(ARG_TO);
  if (itr != options.end()) {
    null_to_ = false;
    to_ = itr->second;
  }

  itr = options.find(ARG_MAX_KEYS);
  if (itr != options.end()) {
    try {
S
sdong 已提交
1315 1316 1317
#if defined(CYGWIN)
      max_keys_ = strtol(itr->second.c_str(), 0, 10);
#else
1318
      max_keys_ = std::stoi(itr->second);
S
sdong 已提交
1319
#endif
1320
    } catch (const std::invalid_argument&) {
1321
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
1322
                                                    " has an invalid value");
1323
    } catch (const std::out_of_range&) {
1324 1325
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
1326 1327
    }
  }
1328 1329 1330 1331 1332 1333
  itr = options.find(ARG_COUNT_DELIM);
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
1334
    delim_=".";
1335
  }
1336

1337 1338 1339 1340
  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);

  if (is_key_hex_) {
1341 1342 1343 1344 1345 1346 1347
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
1348 1349 1350 1351 1352

  itr = options.find(ARG_PATH);
  if (itr != options.end()) {
    path_ = itr->second;
  }
1353 1354
}

1355
void DBDumperCommand::Help(std::string& ret) {
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
  ret.append("  ");
  ret.append(DBDumperCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append(" [--" + ARG_TTL + "]");
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  ret.append(" [--" + ARG_TIMESTAMP + "]");
  ret.append(" [--" + ARG_COUNT_ONLY + "]");
  ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
  ret.append(" [--" + ARG_STATS + "]");
  ret.append(" [--" + ARG_TTL_BUCKET + "=<N>]");
  ret.append(" [--" + ARG_TTL_START + "=<N>:- is inclusive]");
  ret.append(" [--" + ARG_TTL_END + "=<N>:- is exclusive]");
1368
  ret.append(" [--" + ARG_PATH + "=<path_to_a_file>]");
1369
  ret.append("\n");
1370 1371
}

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
/**
 * Handles two separate cases:
 *
 * 1) --db is specified - just dump the database.
 *
 * 2) --path is specified - determine based on file extension what dumping
 *    function to call. Please note that we intentionally use the extension
 *    and avoid probing the file contents under the assumption that renaming
 *    the files is not a supported scenario.
 *
 */
1383
void DBDumperCommand::DoCommand() {
1384
  if (!db_) {
1385
    assert(!path_.empty());
1386
    std::string fileName = GetFileNameFromPath(path_);
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
    uint64_t number;
    FileType type;

    exec_state_ = LDBCommandExecuteResult::Succeed("");

    if (!ParseFileName(fileName, &number, &type)) {
      exec_state_ =
          LDBCommandExecuteResult::Failed("Can't parse file type: " + path_);
      return;
    }

    switch (type) {
      case kLogFile:
        DumpWalFile(path_, /* print_header_ */ true, /* print_values_ */ true,
                    &exec_state_);
        break;
      case kTableFile:
        DumpSstFile(path_, is_key_hex_, /* show_properties */ true);
        break;
      case kDescriptorFile:
        DumpManifestFile(path_, /* verbose_ */ false, is_key_hex_,
                         /*  json_ */ false);
        break;
      default:
        exec_state_ = LDBCommandExecuteResult::Failed(
            "File type not supported: " + path_);
        break;
    }

  } else {
    DoDumpCommand();
1418
  }
1419 1420 1421 1422 1423 1424
}

void DBDumperCommand::DoDumpCommand() {
  assert(nullptr != db_);
  assert(path_.empty());

1425 1426 1427
  // Parse command line args
  uint64_t count = 0;
  if (print_stats_) {
1428
    std::string stats;
1429
    if (db_->GetProperty("rocksdb.stats", &stats)) {
1430 1431 1432 1433 1434
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Setup key iterator
S
sdong 已提交
1435
  Iterator* iter = db_->NewIterator(ReadOptions(), GetCfHandle());
1436
  Status st = iter->status();
1437
  if (!st.ok()) {
1438 1439
    exec_state_ =
        LDBCommandExecuteResult::Failed("Iterator error." + st.ToString());
1440 1441 1442 1443 1444 1445 1446 1447 1448
  }

  if (!null_from_) {
    iter->Seek(from_);
  } else {
    iter->SeekToFirst();
  }

  int max_keys = max_keys_;
1449
  int ttl_start;
1450
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
1451
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
1452 1453
  }
  int ttl_end;
1454
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
1455
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
1456 1457 1458 1459 1460 1461 1462 1463
  }
  if (ttl_end < ttl_start) {
    fprintf(stderr, "Error: End time can't be less than start time\n");
    delete iter;
    return;
  }
  int time_range = ttl_end - ttl_start;
  int bucket_size;
1464
  if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
1465 1466 1467
      bucket_size <= 0) {
    bucket_size = time_range; // Will have just 1 bucket by default
  }
1468
  //cretaing variables for row count of each type
1469
  std::string rtype1, rtype2, row, val;
1470
  rtype2 = "";
1471 1472
  uint64_t c=0;
  uint64_t s1=0,s2=0;
1473

1474
  // At this point, bucket_size=0 => time_range=0
1475 1476 1477
  int num_buckets = (bucket_size >= time_range)
                        ? 1
                        : ((time_range + bucket_size - 1) / bucket_size);
1478
  std::vector<uint64_t> bucket_counts(num_buckets, 0);
1479
  if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
1480 1481 1482 1483
    fprintf(stdout, "Dumping key-values from %s to %s\n",
            ReadableTime(ttl_start).c_str(), ReadableTime(ttl_end).c_str());
  }

1484
  for (; iter->Valid(); iter->Next()) {
1485
    int rawtime = 0;
1486 1487 1488 1489 1490 1491
    // If end marker was specified, we stop before it
    if (!null_to_ && (iter->key().ToString() >= to_))
      break;
    // Terminate if maximum number of keys have been dumped
    if (max_keys == 0)
      break;
1492
    if (is_db_ttl_) {
1493 1494
      TtlIterator* it_ttl = dynamic_cast<TtlIterator*>(iter);
      assert(it_ttl);
1495 1496
      rawtime = it_ttl->timestamp();
      if (rawtime < ttl_start || rawtime >= ttl_end) {
1497 1498 1499
        continue;
      }
    }
1500 1501 1502
    if (max_keys > 0) {
      --max_keys;
    }
1503
    if (is_db_ttl_ && num_buckets > 1) {
1504
      IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
1505 1506
                      rawtime, num_buckets);
    }
1507
    ++count;
1508 1509 1510 1511 1512
    if (count_delim_) {
      rtype1 = "";
      row = iter->key().ToString();
      val = iter->value().ToString();
      s1 = row.size()+val.size();
1513 1514 1515 1516 1517 1518 1519
      for(int j=0;row[j]!=delim_[0] && row[j]!='\0';j++)
        rtype1+=row[j];
      if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
        fprintf(stdout,"%s => count:%lld\tsize:%lld\n",rtype2.c_str(),
            (long long )c,(long long)s2);
        c=1;
        s2=s1;
1520 1521
        rtype2 = rtype1;
      } else {
1522 1523 1524
          c++;
          s2+=s1;
          rtype2=rtype1;
1525
      }
1526

1527 1528
    }

1529 1530


1531
    if (!count_only_ && !count_delim_) {
1532 1533 1534
      if (is_db_ttl_ && timestamp_) {
        fprintf(stdout, "%s ", ReadableTime(rawtime).c_str());
      }
1535 1536 1537
      std::string str =
          PrintKeyValue(iter->key().ToString(), iter->value().ToString(),
                        is_key_hex_, is_value_hex_);
1538
      fprintf(stdout, "%s\n", str.c_str());
1539 1540
    }
  }
1541

1542
  if (num_buckets > 1 && is_db_ttl_) {
1543
    PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
1544
                      num_buckets);
1545 1546 1547
  } else if(count_delim_) {
    fprintf(stdout,"%s => count:%lld\tsize:%lld\n",rtype2.c_str(),
        (long long )c,(long long)s2);
1548
  } else {
1549
    fprintf(stdout, "Keys in range: %lld\n", (long long) count);
1550
  }
1551 1552 1553 1554
  // Clean up
  delete iter;
}

1555 1556 1557
const std::string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
const std::string ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS =
    "print_old_levels";
1558

1559 1560 1561 1562 1563 1564 1565 1566 1567
ReduceDBLevelsCommand::ReduceDBLevelsCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions({ARG_NEW_LEVELS, ARG_PRINT_OLD_LEVELS})),
      old_levels_(1 << 7),
      new_levels_(-1),
      print_old_levels_(false) {
1568
  ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
1569
  print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
1570

1571
  if(new_levels_ <= 0) {
1572
    exec_state_ = LDBCommandExecuteResult::Failed(
1573
        " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
1574 1575 1576
  }
}

1577 1578 1579
std::vector<std::string> ReduceDBLevelsCommand::PrepareArgs(
    const std::string& db_path, int new_levels, bool print_old_level) {
  std::vector<std::string> ret;
1580
  ret.push_back("reduce_levels");
1581
  ret.push_back("--" + ARG_DB + "=" + db_path);
S
sdong 已提交
1582
  ret.push_back("--" + ARG_NEW_LEVELS + "=" + rocksdb::ToString(new_levels));
1583
  if(print_old_level) {
1584
    ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
1585 1586 1587 1588
  }
  return ret;
}

1589
void ReduceDBLevelsCommand::Help(std::string& ret) {
1590 1591 1592 1593 1594
  ret.append("  ");
  ret.append(ReduceDBLevelsCommand::Name());
  ret.append(" --" + ARG_NEW_LEVELS + "=<New number of levels>");
  ret.append(" [--" + ARG_PRINT_OLD_LEVELS + "]");
  ret.append("\n");
1595 1596
}

1597 1598
Options ReduceDBLevelsCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1599
  opt.num_levels = old_levels_;
1600
  opt.max_bytes_for_level_multiplier_additional.resize(opt.num_levels, 1);
1601
  // Disable size compaction
I
Igor Canadi 已提交
1602
  opt.max_bytes_for_level_base = 1ULL << 50;
1603
  opt.max_bytes_for_level_multiplier = 1;
1604 1605 1606
  return opt;
}

1607
Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt,
1608
    int* levels) {
1609
  ImmutableDBOptions db_options(opt);
H
Haobo Xu 已提交
1610
  EnvOptions soptions;
I
Igor Canadi 已提交
1611
  std::shared_ptr<Cache> tc(
1612
      NewLRUCache(opt.max_open_files - 10, opt.table_cache_numshardbits));
1613
  const InternalKeyComparator cmp(opt.comparator);
S
sdong 已提交
1614
  WriteController wc(opt.delayed_write_rate);
1615
  WriteBufferManager wb(opt.db_write_buffer_size);
1616
  VersionSet versions(db_path_, &db_options, soptions, tc.get(), &wb, &wc);
I
Igor Canadi 已提交
1617
  std::vector<ColumnFamilyDescriptor> dummy;
1618
  ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName,
I
Igor Canadi 已提交
1619 1620
                                          ColumnFamilyOptions(opt));
  dummy.push_back(dummy_descriptor);
1621 1622 1623
  // We rely the VersionSet::Recover to tell us the internal data structures
  // in the db. And the Recover() should never do any change
  // (like LogAndApply) to the manifest file.
I
Igor Canadi 已提交
1624
  Status st = versions.Recover(dummy);
1625 1626 1627 1628
  if (!st.ok()) {
    return st;
  }
  int max = -1;
1629
  auto default_cfd = versions.GetColumnFamilySet()->GetDefault();
I
Igor Canadi 已提交
1630
  for (int i = 0; i < default_cfd->NumberLevels(); i++) {
S
sdong 已提交
1631
    if (default_cfd->current()->storage_info()->NumLevelFiles(i)) {
1632 1633 1634 1635 1636 1637 1638 1639
      max = i;
    }
  }

  *levels = max + 1;
  return st;
}

1640
void ReduceDBLevelsCommand::DoCommand() {
1641
  if (new_levels_ <= 1) {
1642 1643
    exec_state_ =
        LDBCommandExecuteResult::Failed("Invalid number of levels.\n");
1644 1645 1646
    return;
  }

1647 1648
  Status st;
  Options opt = PrepareOptionsForOpenDB();
1649 1650 1651
  int old_level_num = -1;
  st = GetOldNumOfLevels(opt, &old_level_num);
  if (!st.ok()) {
1652
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1653 1654 1655
    return;
  }

1656
  if (print_old_levels_) {
1657
    fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
1658
  }
1659

1660 1661
  if (old_level_num <= new_levels_) {
    return;
1662 1663
  }

1664 1665 1666
  old_levels_ = old_level_num;

  OpenDB();
1667
  if (exec_state_.IsFailed()) {
1668 1669
    return;
  }
1670
  // Compact the whole DB to put all files to the highest level.
1671
  fprintf(stdout, "Compacting the db...\n");
S
sdong 已提交
1672
  db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);
1673 1674
  CloseDB();

H
Haobo Xu 已提交
1675
  EnvOptions soptions;
1676
  st = VersionSet::ReduceNumberOfLevels(db_path_, &opt, soptions, new_levels_);
1677
  if (!st.ok()) {
1678
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1679 1680 1681 1682
    return;
  }
}

1683 1684 1685 1686
const std::string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
    "old_compaction_style";
const std::string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
    "new_compaction_style";
1687 1688

ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
1689 1690 1691 1692 1693 1694 1695 1696
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions(
                     {ARG_OLD_COMPACTION_STYLE, ARG_NEW_COMPACTION_STYLE})),
      old_compaction_style_(-1),
      new_compaction_style_(-1) {
1697 1698
  ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
    exec_state_);
1699 1700
  if (old_compaction_style_ != kCompactionStyleLevel &&
     old_compaction_style_ != kCompactionStyleUniversal) {
1701
    exec_state_ = LDBCommandExecuteResult::Failed(
1702 1703
        "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
        "style. Check ldb help for proper compaction style value.\n");
1704 1705 1706
    return;
  }

1707 1708
  ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
    exec_state_);
1709 1710
  if (new_compaction_style_ != kCompactionStyleLevel &&
     new_compaction_style_ != kCompactionStyleUniversal) {
1711
    exec_state_ = LDBCommandExecuteResult::Failed(
1712 1713
        "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
        "style. Check ldb help for proper compaction style value.\n");
1714 1715 1716 1717
    return;
  }

  if (new_compaction_style_ == old_compaction_style_) {
1718
    exec_state_ = LDBCommandExecuteResult::Failed(
1719 1720
        "Old compaction style is the same as new compaction style. "
        "Nothing to do.\n");
1721 1722 1723 1724 1725
    return;
  }

  if (old_compaction_style_ == kCompactionStyleUniversal &&
      new_compaction_style_ == kCompactionStyleLevel) {
1726
    exec_state_ = LDBCommandExecuteResult::Failed(
1727 1728
        "Convert from universal compaction to level compaction. "
        "Nothing to do.\n");
1729 1730 1731 1732
    return;
  }
}

1733
void ChangeCompactionStyleCommand::Help(std::string& ret) {
1734 1735 1736 1737 1738 1739 1740
  ret.append("  ");
  ret.append(ChangeCompactionStyleCommand::Name());
  ret.append(" --" + ARG_OLD_COMPACTION_STYLE + "=<Old compaction style: 0 " +
             "for level compaction, 1 for universal compaction>");
  ret.append(" --" + ARG_NEW_COMPACTION_STYLE + "=<New compaction style: 0 " +
             "for level compaction, 1 for universal compaction>");
  ret.append("\n");
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
}

Options ChangeCompactionStyleCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();

  if (old_compaction_style_ == kCompactionStyleLevel &&
      new_compaction_style_ == kCompactionStyleUniversal) {
    // In order to convert from level compaction to universal compaction, we
    // need to compact all data into a single file and move it to level 0.
    opt.disable_auto_compactions = true;
    opt.target_file_size_base = INT_MAX;
    opt.target_file_size_multiplier = 1;
    opt.max_bytes_for_level_base = INT_MAX;
    opt.max_bytes_for_level_multiplier = 1;
  }

  return opt;
}

void ChangeCompactionStyleCommand::DoCommand() {
  // print db stats before we have made any change
  std::string property;
  std::string files_per_level;
S
sdong 已提交
1764 1765 1766
  for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
    db_->GetProperty(GetCfHandle(),
                     "rocksdb.num-files-at-level" + NumberToString(i),
1767 1768
                     &property);

1769
    // format print string
1770
    char buf[100];
1771
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
1772 1773 1774 1775 1776 1777
    files_per_level += buf;
  }
  fprintf(stdout, "files per level before compaction: %s\n",
          files_per_level.c_str());

  // manual compact into a single file and move the file to level 0
1778 1779 1780
  CompactRangeOptions compact_options;
  compact_options.change_level = true;
  compact_options.target_level = 0;
S
sdong 已提交
1781
  db_->CompactRange(compact_options, GetCfHandle(), nullptr, nullptr);
1782 1783 1784 1785

  // verify compaction result
  files_per_level = "";
  int num_files = 0;
1786
  for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
S
sdong 已提交
1787 1788
    db_->GetProperty(GetCfHandle(),
                     "rocksdb.num-files-at-level" + NumberToString(i),
1789 1790
                     &property);

1791
    // format print string
1792
    char buf[100];
1793
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
1794 1795 1796 1797 1798 1799
    files_per_level += buf;

    num_files = atoi(property.c_str());

    // level 0 should have only 1 file
    if (i == 0 && num_files != 1) {
1800 1801 1802 1803
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level 0 after compaction is " +
          ToString(num_files) + ", not 1.\n");
1804 1805 1806 1807
      return;
    }
    // other levels should have no file
    if (i > 0 && num_files != 0) {
1808 1809 1810 1811 1812
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level " +
          ToString(i) + " after compaction is " + ToString(num_files) +
          ", not 0.\n");
1813 1814 1815 1816 1817 1818 1819 1820
      return;
    }
  }

  fprintf(stdout, "files per level after compaction: %s\n",
          files_per_level.c_str());
}

1821 1822 1823 1824 1825
// ----------------------------------------------------------------------------

namespace {

struct StdErrReporter : public log::Reader::Reporter {
I
Igor Sugak 已提交
1826
  virtual void Corruption(size_t bytes, const Status& s) override {
1827
    std::cerr << "Corruption detected in log file " << s.ToString() << "\n";
1828 1829 1830
  }
};

1831 1832
class InMemoryHandler : public WriteBatch::Handler {
 public:
1833 1834
  InMemoryHandler(std::stringstream& row, bool print_values)
      : Handler(), row_(row) {
1835 1836
    print_values_ = print_values;
  }
1837

1838
  void commonPutMerge(const Slice& key, const Slice& value) {
1839
    std::string k = LDBCommand::StringToHex(key.ToString());
1840
    if (print_values_) {
1841
      std::string v = LDBCommand::StringToHex(value.ToString());
1842 1843 1844 1845 1846
      row_ << k << " : ";
      row_ << v << " ";
    } else {
      row_ << k << " ";
    }
1847
  }
1848

R
Reid Horuff 已提交
1849 1850 1851
  virtual Status PutCF(uint32_t cf, const Slice& key,
                       const Slice& value) override {
    row_ << "PUT(" << cf << ") : ";
1852
    commonPutMerge(key, value);
R
Reid Horuff 已提交
1853
    return Status::OK();
1854 1855
  }

R
Reid Horuff 已提交
1856 1857 1858
  virtual Status MergeCF(uint32_t cf, const Slice& key,
                         const Slice& value) override {
    row_ << "MERGE(" << cf << ") : ";
1859
    commonPutMerge(key, value);
R
Reid Horuff 已提交
1860
    return Status::OK();
1861
  }
1862

R
Reid Horuff 已提交
1863 1864
  virtual Status DeleteCF(uint32_t cf, const Slice& key) override {
    row_ << "DELETE(" << cf << ") : ";
1865
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
R
Reid Horuff 已提交
1866 1867 1868 1869 1870 1871 1872 1873 1874
    return Status::OK();
  }

  virtual Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
    row_ << "SINGLE_DELETE(" << cf << ") : ";
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
    return Status::OK();
  }

A
Andrew Kryczka 已提交
1875 1876 1877 1878 1879 1880 1881 1882
  virtual Status DeleteRangeCF(uint32_t cf, const Slice& begin_key,
                               const Slice& end_key) override {
    row_ << "DELETE_RANGE(" << cf << ") : ";
    row_ << LDBCommand::StringToHex(begin_key.ToString()) << " ";
    row_ << LDBCommand::StringToHex(end_key.ToString()) << " ";
    return Status::OK();
  }

1883
  virtual Status MarkBeginPrepare() override {
R
Reid Horuff 已提交
1884 1885 1886 1887
    row_ << "BEGIN_PREARE ";
    return Status::OK();
  }

1888
  virtual Status MarkEndPrepare(const Slice& xid) override {
R
Reid Horuff 已提交
1889 1890 1891 1892 1893
    row_ << "END_PREPARE(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
  }

1894
  virtual Status MarkRollback(const Slice& xid) override {
R
Reid Horuff 已提交
1895 1896 1897 1898 1899
    row_ << "ROLLBACK(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
  }

1900
  virtual Status MarkCommit(const Slice& xid) override {
R
Reid Horuff 已提交
1901 1902 1903
    row_ << "COMMIT(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
1904 1905
  }

1906
  virtual ~InMemoryHandler() {}
1907

1908
 private:
1909
  std::stringstream& row_;
1910
  bool print_values_;
1911 1912
};

1913 1914 1915 1916
void DumpWalFile(std::string wal_file, bool print_header, bool print_values,
                 LDBCommandExecuteResult* exec_state) {
  Env* env_ = Env::Default();
  EnvOptions soptions;
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
  unique_ptr<SequentialFileReader> wal_file_reader;

  Status status;
  {
    unique_ptr<SequentialFile> file;
    status = env_->NewSequentialFile(wal_file, &file, soptions);
    if (status.ok()) {
      wal_file_reader.reset(new SequentialFileReader(std::move(file)));
    }
  }
1927 1928
  if (!status.ok()) {
    if (exec_state) {
1929
      *exec_state = LDBCommandExecuteResult::Failed("Failed to open WAL file " +
1930 1931
                                                    status.ToString());
    } else {
1932 1933
      std::cerr << "Error: Failed to open WAL file " << status.ToString()
                << std::endl;
1934 1935 1936
    }
  } else {
    StdErrReporter reporter;
1937 1938 1939 1940
    uint64_t log_number;
    FileType type;

    // we need the log number, but ParseFilename expects dbname/NNN.log.
1941
    std::string sanitized = wal_file;
1942 1943 1944 1945 1946 1947 1948 1949
    size_t lastslash = sanitized.rfind('/');
    if (lastslash != std::string::npos)
      sanitized = sanitized.substr(lastslash + 1);
    if (!ParseFileName(sanitized, &log_number, &type)) {
      // bogus input, carry on as best we can
      log_number = 0;
    }
    DBOptions db_options;
1950 1951 1952
    log::Reader reader(db_options.info_log, std::move(wal_file_reader),
                       &reporter, true, 0, log_number);
    std::string scratch;
1953 1954
    WriteBatch batch;
    Slice record;
1955
    std::stringstream row;
1956
    if (print_header) {
1957
      std::cout << "Sequence,Count,ByteSize,Physical Offset,Key(s)";
1958
      if (print_values) {
1959
        std::cout << " : value ";
1960
      }
1961
      std::cout << "\n";
1962 1963 1964
    }
    while (reader.ReadRecord(&record, &scratch)) {
      row.str("");
1965
      if (record.size() < WriteBatchInternal::kHeader) {
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
        reporter.Corruption(record.size(),
                            Status::Corruption("log record too small"));
      } else {
        WriteBatchInternal::SetContents(&batch, record);
        row << WriteBatchInternal::Sequence(&batch) << ",";
        row << WriteBatchInternal::Count(&batch) << ",";
        row << WriteBatchInternal::ByteSize(&batch) << ",";
        row << reader.LastRecordOffset() << ",";
        InMemoryHandler handler(row, print_values);
        batch.Iterate(&handler);
        row << "\n";
      }
1978
      std::cout << row.str();
1979 1980 1981 1982 1983 1984
    }
  }
}

}  // namespace

1985 1986 1987
const std::string WALDumperCommand::ARG_WAL_FILE = "walfile";
const std::string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
const std::string WALDumperCommand::ARG_PRINT_HEADER = "header";
1988

1989 1990 1991 1992 1993 1994 1995 1996 1997
WALDumperCommand::WALDumperCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, true,
                 BuildCmdLineOptions(
                     {ARG_WAL_FILE, ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
      print_header_(false),
      print_values_(false) {
A
Abhishek Kona 已提交
1998
  wal_file_.clear();
1999

2000 2001
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_WAL_FILE);
2002 2003
  if (itr != options.end()) {
    wal_file_ = itr->second;
A
Abhishek Kona 已提交
2004
  }
2005 2006


2007 2008
  print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
A
Abhishek Kona 已提交
2009
  if (wal_file_.empty()) {
2010 2011
    exec_state_ = LDBCommandExecuteResult::Failed("Argument " + ARG_WAL_FILE +
                                                  " must be specified.");
A
Abhishek Kona 已提交
2012 2013 2014
  }
}

2015
void WALDumperCommand::Help(std::string& ret) {
2016 2017 2018 2019 2020 2021
  ret.append("  ");
  ret.append(WALDumperCommand::Name());
  ret.append(" --" + ARG_WAL_FILE + "=<write_ahead_log_file_path>");
  ret.append(" [--" + ARG_PRINT_HEADER + "] ");
  ret.append(" [--" + ARG_PRINT_VALUE + "] ");
  ret.append("\n");
A
Abhishek Kona 已提交
2022 2023
}

2024
void WALDumperCommand::DoCommand() {
2025
  DumpWalFile(wal_file_, print_header_, print_values_, &exec_state_);
A
Abhishek Kona 已提交
2026 2027
}

2028
// ----------------------------------------------------------------------------
2029

2030 2031 2032 2033 2034 2035
GetCommand::GetCommand(const std::vector<std::string>& params,
                       const std::map<std::string, std::string>& options,
                       const std::vector<std::string>& flags)
    : LDBCommand(
          options, flags, true,
          BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
2036
  if (params.size() != 1) {
2037
    exec_state_ = LDBCommandExecuteResult::Failed(
2038
        "<key> must be specified for the get command");
2039 2040 2041 2042 2043 2044 2045 2046 2047
  } else {
    key_ = params.at(0);
  }

  if (is_key_hex_) {
    key_ = HexToString(key_);
  }
}

2048
void GetCommand::Help(std::string& ret) {
2049 2050 2051 2052 2053
  ret.append("  ");
  ret.append(GetCommand::Name());
  ret.append(" <key>");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2054 2055 2056
}

void GetCommand::DoCommand() {
S
sdong 已提交
2057 2058 2059 2060
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2061
  std::string value;
S
sdong 已提交
2062
  Status st = db_->Get(ReadOptions(), GetCfHandle(), key_, &value);
2063 2064 2065 2066
  if (st.ok()) {
    fprintf(stdout, "%s\n",
              (is_value_hex_ ? StringToHex(value) : value).c_str());
  } else {
2067
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2068 2069 2070
  }
}

2071
// ----------------------------------------------------------------------------
2072

2073 2074 2075 2076 2077 2078 2079
ApproxSizeCommand::ApproxSizeCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, true,
                 BuildCmdLineOptions(
                     {ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM, ARG_TO})) {
2080 2081 2082
  if (options.find(ARG_FROM) != options.end()) {
    start_key_ = options.find(ARG_FROM)->second;
  } else {
2083 2084
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_FROM + " must be specified for approxsize command");
2085 2086 2087 2088 2089 2090
    return;
  }

  if (options.find(ARG_TO) != options.end()) {
    end_key_ = options.find(ARG_TO)->second;
  } else {
2091 2092
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_TO + " must be specified for approxsize command");
2093 2094 2095 2096 2097 2098 2099 2100 2101
    return;
  }

  if (is_key_hex_) {
    start_key_ = HexToString(start_key_);
    end_key_ = HexToString(end_key_);
  }
}

2102
void ApproxSizeCommand::Help(std::string& ret) {
2103 2104 2105 2106
  ret.append("  ");
  ret.append(ApproxSizeCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
2107 2108 2109
}

void ApproxSizeCommand::DoCommand() {
S
sdong 已提交
2110 2111 2112 2113
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2114 2115
  Range ranges[1];
  ranges[0] = Range(start_key_, end_key_);
2116
  uint64_t sizes[1];
S
sdong 已提交
2117
  db_->GetApproximateSizes(GetCfHandle(), ranges, 1, sizes);
K
Kai Liu 已提交
2118
  fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
2119
  /* Weird that GetApproximateSizes() returns void, although documentation
2120 2121
   * says that it returns a Status object.
  if (!st.ok()) {
2122
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2123 2124 2125 2126
  }
  */
}

2127
// ----------------------------------------------------------------------------
2128

2129 2130 2131 2132 2133 2134 2135
BatchPutCommand::BatchPutCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
                                      ARG_VALUE_HEX, ARG_CREATE_IF_MISSING})) {
2136
  if (params.size() < 2) {
2137
    exec_state_ = LDBCommandExecuteResult::Failed(
2138
        "At least one <key> <value> pair must be specified batchput.");
2139
  } else if (params.size() % 2 != 0) {
2140
    exec_state_ = LDBCommandExecuteResult::Failed(
2141 2142 2143
        "Equal number of <key>s and <value>s must be specified for batchput.");
  } else {
    for (size_t i = 0; i < params.size(); i += 2) {
2144 2145 2146 2147 2148
      std::string key = params.at(i);
      std::string value = params.at(i + 1);
      key_values_.push_back(std::pair<std::string, std::string>(
          is_key_hex_ ? HexToString(key) : key,
          is_value_hex_ ? HexToString(value) : value));
2149 2150
    }
  }
2151
  create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
2152 2153
}

2154
void BatchPutCommand::Help(std::string& ret) {
2155 2156 2157 2158 2159
  ret.append("  ");
  ret.append(BatchPutCommand::Name());
  ret.append(" <key> <value> [<key> <value>] [..]");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2160 2161 2162
}

void BatchPutCommand::DoCommand() {
S
sdong 已提交
2163 2164 2165 2166
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2167
  WriteBatch batch;
2168

2169 2170 2171
  for (std::vector<std::pair<std::string, std::string>>::const_iterator itr =
           key_values_.begin();
       itr != key_values_.end(); ++itr) {
S
sdong 已提交
2172
    batch.Put(GetCfHandle(), itr->first, itr->second);
2173
  }
2174
  Status st = db_->Write(WriteOptions(), &batch);
2175 2176 2177
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2178
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2179 2180 2181
  }
}

2182 2183
Options BatchPutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
2184
  opt.create_if_missing = create_if_missing_;
2185 2186 2187
  return opt;
}

2188
// ----------------------------------------------------------------------------
2189

2190 2191 2192 2193 2194 2195 2196 2197
ScanCommand::ScanCommand(const std::vector<std::string>& params,
                         const std::map<std::string, std::string>& options,
                         const std::vector<std::string>& flags)
    : LDBCommand(
          options, flags, true,
          BuildCmdLineOptions({ARG_TTL, ARG_NO_VALUE, ARG_HEX, ARG_KEY_HEX,
                               ARG_TO, ARG_VALUE_HEX, ARG_FROM, ARG_TIMESTAMP,
                               ARG_MAX_KEYS, ARG_TTL_START, ARG_TTL_END})),
A
Alexander Fenster 已提交
2198 2199 2200 2201
      start_key_specified_(false),
      end_key_specified_(false),
      max_keys_scanned_(-1),
      no_value_(false) {
2202 2203
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_FROM);
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
  if (itr != options.end()) {
    start_key_ = itr->second;
    if (is_key_hex_) {
      start_key_ = HexToString(start_key_);
    }
    start_key_specified_ = true;
  }
  itr = options.find(ARG_TO);
  if (itr != options.end()) {
    end_key_ = itr->second;
    if (is_key_hex_) {
      end_key_ = HexToString(end_key_);
    }
    end_key_specified_ = true;
  }

2220
  std::vector<std::string>::const_iterator vitr =
A
Alexander Fenster 已提交
2221
      std::find(flags.begin(), flags.end(), ARG_NO_VALUE);
2222 2223 2224 2225
  if (vitr != flags.end()) {
    no_value_ = true;
  }

2226 2227 2228
  itr = options.find(ARG_MAX_KEYS);
  if (itr != options.end()) {
    try {
S
sdong 已提交
2229 2230 2231
#if defined(CYGWIN)
      max_keys_scanned_ = strtol(itr->second.c_str(), 0, 10);
#else
2232
      max_keys_scanned_ = std::stoi(itr->second);
S
sdong 已提交
2233
#endif
2234
    } catch (const std::invalid_argument&) {
2235
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
2236
                                                    " has an invalid value");
2237
    } catch (const std::out_of_range&) {
2238 2239
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
2240 2241 2242 2243
    }
  }
}

2244
void ScanCommand::Help(std::string& ret) {
2245 2246 2247 2248 2249 2250 2251 2252
  ret.append("  ");
  ret.append(ScanCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append(" [--" + ARG_TTL + "]");
  ret.append(" [--" + ARG_TIMESTAMP + "]");
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>q] ");
  ret.append(" [--" + ARG_TTL_START + "=<N>:- is inclusive]");
  ret.append(" [--" + ARG_TTL_END + "=<N>:- is exclusive]");
2253
  ret.append(" [--" + ARG_NO_VALUE + "]");
2254
  ret.append("\n");
2255 2256 2257
}

void ScanCommand::DoCommand() {
S
sdong 已提交
2258 2259 2260 2261
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2262 2263

  int num_keys_scanned = 0;
S
sdong 已提交
2264
  Iterator* it = db_->NewIterator(ReadOptions(), GetCfHandle());
2265 2266 2267 2268 2269
  if (start_key_specified_) {
    it->Seek(start_key_);
  } else {
    it->SeekToFirst();
  }
2270
  int ttl_start;
2271
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
2272
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
2273 2274
  }
  int ttl_end;
2275
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
2276
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
  }
  if (ttl_end < ttl_start) {
    fprintf(stderr, "Error: End time can't be less than start time\n");
    delete it;
    return;
  }
  if (is_db_ttl_ && timestamp_) {
    fprintf(stdout, "Scanning key-values from %s to %s\n",
            ReadableTime(ttl_start).c_str(), ReadableTime(ttl_end).c_str());
  }
2287
  for ( ;
2288 2289
        it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
        it->Next()) {
2290
    if (is_db_ttl_) {
2291 2292
      TtlIterator* it_ttl = dynamic_cast<TtlIterator*>(it);
      assert(it_ttl);
2293 2294
      int rawtime = it_ttl->timestamp();
      if (rawtime < ttl_start || rawtime >= ttl_end) {
2295 2296 2297 2298 2299 2300
        continue;
      }
      if (timestamp_) {
        fprintf(stdout, "%s ", ReadableTime(rawtime).c_str());
      }
    }
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312

    Slice key_slice = it->key();

    std::string formatted_key;
    if (is_key_hex_) {
      formatted_key = "0x" + key_slice.ToString(true /* hex */);
      key_slice = formatted_key;
    } else if (ldb_options_.key_formatter) {
      formatted_key = ldb_options_.key_formatter->Format(key_slice);
      key_slice = formatted_key;
    }

2313
    if (no_value_) {
A
Alexander Fenster 已提交
2314 2315
      fprintf(stdout, "%.*s\n", static_cast<int>(key_slice.size()),
              key_slice.data());
2316
    } else {
A
Alexander Fenster 已提交
2317 2318 2319 2320 2321 2322 2323 2324 2325
      Slice val_slice = it->value();
      std::string formatted_value;
      if (is_value_hex_) {
        formatted_value = "0x" + val_slice.ToString(true /* hex */);
        val_slice = formatted_value;
      }
      fprintf(stdout, "%.*s : %.*s\n", static_cast<int>(key_slice.size()),
              key_slice.data(), static_cast<int>(val_slice.size()),
              val_slice.data());
2326 2327
    }

2328 2329 2330 2331 2332 2333
    num_keys_scanned++;
    if (max_keys_scanned_ >= 0 && num_keys_scanned >= max_keys_scanned_) {
      break;
    }
  }
  if (!it->status().ok()) {  // Check for any errors found during the scan
2334
    exec_state_ = LDBCommandExecuteResult::Failed(it->status().ToString());
2335 2336 2337 2338
  }
  delete it;
}

2339
// ----------------------------------------------------------------------------
2340

2341 2342 2343 2344 2345
DeleteCommand::DeleteCommand(const std::vector<std::string>& params,
                             const std::map<std::string, std::string>& options,
                             const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
2346
  if (params.size() != 1) {
2347
    exec_state_ = LDBCommandExecuteResult::Failed(
2348
        "KEY must be specified for the delete command");
2349 2350 2351 2352 2353 2354 2355 2356
  } else {
    key_ = params.at(0);
    if (is_key_hex_) {
      key_ = HexToString(key_);
    }
  }
}

2357
void DeleteCommand::Help(std::string& ret) {
2358 2359 2360
  ret.append("  ");
  ret.append(DeleteCommand::Name() + " <key>");
  ret.append("\n");
2361 2362 2363
}

void DeleteCommand::DoCommand() {
S
sdong 已提交
2364 2365 2366 2367 2368
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st = db_->Delete(WriteOptions(), GetCfHandle(), key_);
2369 2370 2371
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2372
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2373 2374 2375
  }
}

A
Andrew Kryczka 已提交
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
DeleteRangeCommand::DeleteRangeCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
  if (params.size() != 2) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "begin and end keys must be specified for the delete command");
  } else {
    begin_key_ = params.at(0);
    end_key_ = params.at(1);
    if (is_key_hex_) {
      begin_key_ = HexToString(begin_key_);
      end_key_ = HexToString(end_key_);
    }
  }
}

void DeleteRangeCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(DeleteRangeCommand::Name() + " <begin key> <end key>");
  ret.append("\n");
}

void DeleteRangeCommand::DoCommand() {
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st =
      db_->DeleteRange(WriteOptions(), GetCfHandle(), begin_key_, end_key_);
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  }
}

2415 2416 2417 2418 2419 2420
PutCommand::PutCommand(const std::vector<std::string>& params,
                       const std::map<std::string, std::string>& options,
                       const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
                                      ARG_VALUE_HEX, ARG_CREATE_IF_MISSING})) {
2421
  if (params.size() != 2) {
2422
    exec_state_ = LDBCommandExecuteResult::Failed(
2423
        "<key> and <value> must be specified for the put command");
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
  } else {
    key_ = params.at(0);
    value_ = params.at(1);
  }

  if (is_key_hex_) {
    key_ = HexToString(key_);
  }

  if (is_value_hex_) {
    value_ = HexToString(value_);
  }
2436
  create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
2437 2438
}

2439
void PutCommand::Help(std::string& ret) {
2440 2441 2442 2443 2444
  ret.append("  ");
  ret.append(PutCommand::Name());
  ret.append(" <key> <value> ");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2445 2446 2447
}

void PutCommand::DoCommand() {
S
sdong 已提交
2448 2449 2450 2451 2452
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st = db_->Put(WriteOptions(), GetCfHandle(), key_, value_);
2453 2454 2455
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2456
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2457 2458 2459
  }
}

2460 2461
Options PutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
2462
  opt.create_if_missing = create_if_missing_;
2463 2464 2465
  return opt;
}

2466
// ----------------------------------------------------------------------------
2467 2468 2469 2470 2471 2472

const char* DBQuerierCommand::HELP_CMD = "help";
const char* DBQuerierCommand::GET_CMD = "get";
const char* DBQuerierCommand::PUT_CMD = "put";
const char* DBQuerierCommand::DELETE_CMD = "delete";

2473 2474 2475 2476 2477 2478 2479
DBQuerierCommand::DBQuerierCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(
          options, flags, false,
          BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {
2480 2481 2482

}

2483
void DBQuerierCommand::Help(std::string& ret) {
2484 2485 2486 2487 2488
  ret.append("  ");
  ret.append(DBQuerierCommand::Name());
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
  ret.append("    Starts a REPL shell.  Type help for list of available "
2489
             "commands.");
2490
  ret.append("\n");
2491 2492 2493 2494
}

void DBQuerierCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
2495
    assert(GetExecuteState().IsFailed());
2496 2497
    return;
  }
2498

2499 2500
  ReadOptions read_options;
  WriteOptions write_options;
2501

2502 2503 2504 2505 2506 2507
  std::string line;
  std::string key;
  std::string value;
  while (getline(std::cin, line, '\n')) {
    // Parse line into std::vector<std::string>
    std::vector<std::string> tokens;
2508 2509 2510
    size_t pos = 0;
    while (true) {
      size_t pos2 = line.find(' ', pos);
2511
      if (pos2 == std::string::npos) {
2512 2513 2514 2515 2516 2517 2518
        break;
      }
      tokens.push_back(line.substr(pos, pos2-pos));
      pos = pos2 + 1;
    }
    tokens.push_back(line.substr(pos));

2519
    const std::string& cmd = tokens[0];
2520 2521 2522 2523 2524 2525 2526 2527

    if (cmd == HELP_CMD) {
      fprintf(stdout,
              "get <key>\n"
              "put <key> <value>\n"
              "delete <key>\n");
    } else if (cmd == DELETE_CMD && tokens.size() == 2) {
      key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
S
sdong 已提交
2528
      db_->Delete(write_options, GetCfHandle(), Slice(key));
2529 2530 2531 2532
      fprintf(stdout, "Successfully deleted %s\n", tokens[1].c_str());
    } else if (cmd == PUT_CMD && tokens.size() == 3) {
      key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
      value = (is_value_hex_ ? HexToString(tokens[2]) : tokens[2]);
S
sdong 已提交
2533
      db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
2534 2535 2536 2537
      fprintf(stdout, "Successfully put %s %s\n",
              tokens[1].c_str(), tokens[2].c_str());
    } else if (cmd == GET_CMD && tokens.size() == 2) {
      key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
S
sdong 已提交
2538
      if (db_->Get(read_options, GetCfHandle(), Slice(key), &value).ok()) {
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
        fprintf(stdout, "%s\n", PrintKeyValue(key, value,
              is_key_hex_, is_value_hex_).c_str());
      } else {
        fprintf(stdout, "Not found %s\n", tokens[1].c_str());
      }
    } else {
      fprintf(stdout, "Unknown command %s\n", line.c_str());
    }
  }
}

2550 2551
// ----------------------------------------------------------------------------

2552 2553 2554 2555 2556
CheckConsistencyCommand::CheckConsistencyCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}
Y
Yiting Li 已提交
2557

2558
void CheckConsistencyCommand::Help(std::string& ret) {
2559 2560 2561
  ret.append("  ");
  ret.append(CheckConsistencyCommand::Name());
  ret.append("\n");
Y
Yiting Li 已提交
2562
}
2563

Y
Yiting Li 已提交
2564 2565
void CheckConsistencyCommand::DoCommand() {
  Options opt = PrepareOptionsForOpenDB();
I
Igor Canadi 已提交
2566
  opt.paranoid_checks = true;
Y
Yiting Li 已提交
2567 2568 2569
  if (!exec_state_.IsNotStarted()) {
    return;
  }
I
Igor Canadi 已提交
2570 2571 2572
  DB* db;
  Status st = DB::OpenForReadOnly(opt, db_path_, &db, false);
  delete db;
Y
Yiting Li 已提交
2573 2574 2575
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2576
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
Y
Yiting Li 已提交
2577
  }
2578
}
Y
Yiting Li 已提交
2579

2580
// ----------------------------------------------------------------------------
A
Andrew Kryczka 已提交
2581

A
Aaron Gao 已提交
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
const std::string CheckPointCommand::ARG_CHECKPOINT_DIR = "checkpoint_dir";

CheckPointCommand::CheckPointCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false /* is_read_only */,
                 BuildCmdLineOptions({ARG_CHECKPOINT_DIR})) {
  auto itr = options.find(ARG_CHECKPOINT_DIR);
  if (itr == options.end()) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "--" + ARG_CHECKPOINT_DIR + ": missing checkpoint directory");
  } else {
    checkpoint_dir_ = itr->second;
  }
}

void CheckPointCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(CheckPointCommand::Name());
  ret.append(" [--" + ARG_CHECKPOINT_DIR + "] ");
  ret.append("\n");
}

void CheckPointCommand::DoCommand() {
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Checkpoint* checkpoint;
  Status status = Checkpoint::Create(db_, &checkpoint);
  status = checkpoint->CreateCheckpoint(checkpoint_dir_);
  if (status.ok()) {
    printf("OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

// ----------------------------------------------------------------------------

2623 2624 2625
RepairCommand::RepairCommand(const std::vector<std::string>& params,
                             const std::map<std::string, std::string>& options,
                             const std::vector<std::string>& flags)
A
Andrew Kryczka 已提交
2626 2627
    : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}

2628
void RepairCommand::Help(std::string& ret) {
A
Andrew Kryczka 已提交
2629 2630 2631 2632 2633 2634 2635
  ret.append("  ");
  ret.append(RepairCommand::Name());
  ret.append("\n");
}

void RepairCommand::DoCommand() {
  Options options = PrepareOptionsForOpenDB();
A
Andrew Kryczka 已提交
2636
  options.info_log.reset(new StderrLogger(InfoLogLevel::WARN_LEVEL));
A
Andrew Kryczka 已提交
2637 2638 2639 2640 2641 2642 2643 2644 2645
  Status status = RepairDB(db_path_, options);
  if (status.ok()) {
    printf("OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

// ----------------------------------------------------------------------------
W
Wanning Jiang 已提交
2646

2647 2648 2649 2650
const std::string BackupableCommand::ARG_NUM_THREADS = "num_threads";
const std::string BackupableCommand::ARG_BACKUP_ENV_URI = "backup_env_uri";
const std::string BackupableCommand::ARG_BACKUP_DIR = "backup_dir";
const std::string BackupableCommand::ARG_STDERR_LOG_LEVEL = "stderr_log_level";
W
Wanning Jiang 已提交
2651

2652 2653 2654 2655 2656 2657 2658 2659 2660
BackupableCommand::BackupableCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false /* is_read_only */,
                 BuildCmdLineOptions({ARG_BACKUP_ENV_URI, ARG_BACKUP_DIR,
                                      ARG_NUM_THREADS, ARG_STDERR_LOG_LEVEL})),
      num_threads_(1) {
  auto itr = options.find(ARG_NUM_THREADS);
W
Wanning Jiang 已提交
2661
  if (itr != options.end()) {
2662
    num_threads_ = std::stoi(itr->second);
W
Wanning Jiang 已提交
2663
  }
2664
  itr = options.find(ARG_BACKUP_ENV_URI);
A
Andrew Kryczka 已提交
2665
  if (itr != options.end()) {
2666
    backup_env_uri_ = itr->second;
W
Wanning Jiang 已提交
2667 2668 2669 2670 2671 2672
  }
  itr = options.find(ARG_BACKUP_DIR);
  if (itr == options.end()) {
    exec_state_ = LDBCommandExecuteResult::Failed("--" + ARG_BACKUP_DIR +
                                                  ": missing backup directory");
  } else {
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
    backup_dir_ = itr->second;
  }

  itr = options.find(ARG_STDERR_LOG_LEVEL);
  if (itr != options.end()) {
    int stderr_log_level = std::stoi(itr->second);
    if (stderr_log_level < 0 ||
        stderr_log_level >= InfoLogLevel::NUM_INFO_LOG_LEVELS) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_STDERR_LOG_LEVEL + " must be >= 0 and < " +
          std::to_string(InfoLogLevel::NUM_INFO_LOG_LEVELS) + ".");
    } else {
      logger_.reset(
          new StderrLogger(static_cast<InfoLogLevel>(stderr_log_level)));
    }
W
Wanning Jiang 已提交
2688 2689 2690
  }
}

2691
void BackupableCommand::Help(const std::string& name, std::string& ret) {
W
Wanning Jiang 已提交
2692
  ret.append("  ");
2693 2694
  ret.append(name);
  ret.append(" [--" + ARG_BACKUP_ENV_URI + "] ");
W
Wanning Jiang 已提交
2695
  ret.append(" [--" + ARG_BACKUP_DIR + "] ");
2696 2697
  ret.append(" [--" + ARG_NUM_THREADS + "] ");
  ret.append(" [--" + ARG_STDERR_LOG_LEVEL + "=<int (InfoLogLevel)>] ");
W
Wanning Jiang 已提交
2698 2699 2700
  ret.append("\n");
}

2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
// ----------------------------------------------------------------------------

BackupCommand::BackupCommand(const std::vector<std::string>& params,
                             const std::map<std::string, std::string>& options,
                             const std::vector<std::string>& flags)
    : BackupableCommand(params, options, flags) {}

void BackupCommand::Help(std::string& ret) {
  BackupableCommand::Help(Name(), ret);
}

W
Wanning Jiang 已提交
2712 2713 2714 2715 2716 2717 2718 2719 2720
void BackupCommand::DoCommand() {
  BackupEngine* backup_engine;
  Status status;
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  printf("open db OK\n");
  std::unique_ptr<Env> custom_env_guard;
2721
  Env* custom_env = NewCustomObject<Env>(backup_env_uri_, &custom_env_guard);
W
Wanning Jiang 已提交
2722
  BackupableDBOptions backup_options =
2723 2724 2725
      BackupableDBOptions(backup_dir_, custom_env);
  backup_options.info_log = logger_.get();
  backup_options.max_background_operations = num_threads_;
W
Wanning Jiang 已提交
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
  status = BackupEngine::Open(Env::Default(), backup_options, &backup_engine);
  if (status.ok()) {
    printf("open backup engine OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
    return;
  }
  status = backup_engine->CreateNewBackup(db_);
  if (status.ok()) {
    printf("create new backup OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
    return;
  }
}

// ----------------------------------------------------------------------------
A
Andrew Kryczka 已提交
2743 2744 2745 2746 2747

RestoreCommand::RestoreCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
2748
    : BackupableCommand(params, options, flags) {}
A
Andrew Kryczka 已提交
2749 2750

void RestoreCommand::Help(std::string& ret) {
2751
  BackupableCommand::Help(Name(), ret);
A
Andrew Kryczka 已提交
2752 2753 2754 2755
}

void RestoreCommand::DoCommand() {
  std::unique_ptr<Env> custom_env_guard;
2756
  Env* custom_env = NewCustomObject<Env>(backup_env_uri_, &custom_env_guard);
A
Andrew Kryczka 已提交
2757 2758 2759 2760
  std::unique_ptr<BackupEngineReadOnly> restore_engine;
  Status status;
  {
    BackupableDBOptions opts(backup_dir_, custom_env);
2761
    opts.info_log = logger_.get();
A
Andrew Kryczka 已提交
2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
    opts.max_background_operations = num_threads_;
    BackupEngineReadOnly* raw_restore_engine_ptr;
    status = BackupEngineReadOnly::Open(Env::Default(), opts,
                                        &raw_restore_engine_ptr);
    if (status.ok()) {
      restore_engine.reset(raw_restore_engine_ptr);
    }
  }
  if (status.ok()) {
    printf("open restore engine OK\n");
    status = restore_engine->RestoreDBFromLatestBackup(db_path_, db_path_);
  }
  if (status.ok()) {
    printf("restore from backup OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

// ----------------------------------------------------------------------------
2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829

namespace {

void DumpSstFile(std::string filename, bool output_hex, bool show_properties) {
  std::string from_key;
  std::string to_key;
  if (filename.length() <= 4 ||
      filename.rfind(".sst") != filename.length() - 4) {
    std::cout << "Invalid sst file name." << std::endl;
    return;
  }
  // no verification
  rocksdb::SstFileReader reader(filename, false, output_hex);
  Status st = reader.ReadSequential(true, -1, false,  // has_from
                                    from_key, false,  // has_to
                                    to_key);
  if (!st.ok()) {
    std::cerr << "Error in reading SST file " << filename << st.ToString()
              << std::endl;
    return;
  }

  if (show_properties) {
    const rocksdb::TableProperties* table_properties;

    std::shared_ptr<const rocksdb::TableProperties>
        table_properties_from_reader;
    st = reader.ReadTableProperties(&table_properties_from_reader);
    if (!st.ok()) {
      std::cerr << filename << ": " << st.ToString()
                << ". Try to use initial table properties" << std::endl;
      table_properties = reader.GetInitTableProperties();
    } else {
      table_properties = table_properties_from_reader.get();
    }
    if (table_properties != nullptr) {
      std::cout << std::endl << "Table Properties:" << std::endl;
      std::cout << table_properties->ToString("\n") << std::endl;
      std::cout << "# deleted keys: "
                << rocksdb::GetDeletedKeys(
                       table_properties->user_collected_properties)
                << std::endl;
    }
  }
}

}  // namespace

2830 2831 2832 2833
DBFileDumperCommand::DBFileDumperCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
2834 2835
    : LDBCommand(options, flags, true, BuildCmdLineOptions({})) {}

2836
void DBFileDumperCommand::Help(std::string& ret) {
2837 2838 2839 2840 2841 2842 2843
  ret.append("  ");
  ret.append(DBFileDumperCommand::Name());
  ret.append("\n");
}

void DBFileDumperCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
2844
    assert(GetExecuteState().IsFailed());
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
    return;
  }
  Status s;

  std::cout << "Manifest File" << std::endl;
  std::cout << "==============================" << std::endl;
  std::string manifest_filename;
  s = ReadFileToString(db_->GetEnv(), CurrentFileName(db_->GetName()),
                       &manifest_filename);
  if (!s.ok() || manifest_filename.empty() ||
      manifest_filename.back() != '\n') {
    std::cerr << "Error when reading CURRENT file "
              << CurrentFileName(db_->GetName()) << std::endl;
  }
  // remove the trailing '\n'
  manifest_filename.resize(manifest_filename.size() - 1);
2861
  std::string manifest_filepath = db_->GetName() + "/" + manifest_filename;
2862
  std::cout << manifest_filepath << std::endl;
2863
  DumpManifestFile(manifest_filepath, false, false, false);
2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
  std::cout << std::endl;

  std::cout << "SST Files" << std::endl;
  std::cout << "==============================" << std::endl;
  std::vector<LiveFileMetaData> metadata;
  db_->GetLiveFilesMetaData(&metadata);
  for (auto& fileMetadata : metadata) {
    std::string filename = fileMetadata.db_path + fileMetadata.name;
    std::cout << filename << " level:" << fileMetadata.level << std::endl;
    std::cout << "------------------------------" << std::endl;
    DumpSstFile(filename, false, true);
    std::cout << std::endl;
  }
  std::cout << std::endl;

  std::cout << "Write Ahead Log Files" << std::endl;
  std::cout << "==============================" << std::endl;
  rocksdb::VectorLogPtr wal_files;
  s = db_->GetSortedWalFiles(wal_files);
  if (!s.ok()) {
    std::cerr << "Error when getting WAL files" << std::endl;
  } else {
    for (auto& wal : wal_files) {
      // TODO(qyang): option.wal_dir should be passed into ldb command
      std::string filename = db_->GetOptions().wal_dir + wal->PathName();
      std::cout << filename << std::endl;
      DumpWalFile(filename, true, true, &exec_state_);
    }
  }
}

Y
Yiting Li 已提交
2895
}   // namespace rocksdb
I
Igor Canadi 已提交
2896
#endif  // ROCKSDB_LITE