ldb_cmd.cc 121.0 KB
Newer Older
1

2
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
3 4 5
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
6
//
I
Igor Canadi 已提交
7
#ifndef ROCKSDB_LITE
A
Arun Sharma 已提交
8
#include "rocksdb/utilities/ldb_cmd.h"
A
Abhishek Kona 已提交
9

10
#include <cinttypes>
11 12 13 14 15 16 17 18 19
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <functional>
#include <iostream>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
20

21
#include "db/db_impl/db_impl.h"
A
Andrew Kryczka 已提交
22 23
#include "db/dbformat.h"
#include "db/log_reader.h"
A
Abhishek Kona 已提交
24
#include "db/write_batch_internal.h"
25
#include "env/composite_env_wrapper.h"
26
#include "file/filename.h"
I
Igor Canadi 已提交
27
#include "rocksdb/cache.h"
28
#include "rocksdb/file_checksum.h"
29
#include "rocksdb/table_properties.h"
W
Wanning Jiang 已提交
30
#include "rocksdb/utilities/backupable_db.h"
A
Aaron Gao 已提交
31
#include "rocksdb/utilities/checkpoint.h"
A
Andrew Kryczka 已提交
32
#include "rocksdb/utilities/debug.h"
33
#include "rocksdb/utilities/options_util.h"
A
Andrew Kryczka 已提交
34
#include "rocksdb/write_batch.h"
35
#include "rocksdb/write_buffer_manager.h"
S
sdong 已提交
36
#include "table/scoped_arena_iterator.h"
37
#include "table/sst_file_dumper.h"
A
Arun Sharma 已提交
38
#include "tools/ldb_cmd_impl.h"
S
Siying Dong 已提交
39
#include "util/cast_util.h"
40
#include "util/coding.h"
41
#include "util/file_checksum_helper.h"
A
Andrew Kryczka 已提交
42
#include "util/stderr_logger.h"
S
sdong 已提交
43
#include "util/string_util.h"
44
#include "utilities/merge_operators.h"
45
#include "utilities/ttl/db_ttl_impl.h"
46

47
namespace ROCKSDB_NAMESPACE {
48

49 50
class FileChecksumGenCrc32c;
class FileChecksumGenCrc32cFactory;
51

52
const std::string LDBCommand::ARG_ENV_URI = "env_uri";
53 54
const std::string LDBCommand::ARG_DB = "db";
const std::string LDBCommand::ARG_PATH = "path";
55
const std::string LDBCommand::ARG_SECONDARY_PATH = "secondary_path";
56 57 58 59 60 61 62 63
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";
64
const std::string LDBCommand::ARG_TRY_LOAD_OPTIONS = "try_load_options";
S
sdong 已提交
65 66
const std::string LDBCommand::ARG_DISABLE_CONSISTENCY_CHECKS =
    "disable_consistency_checks";
67 68
const std::string LDBCommand::ARG_IGNORE_UNKNOWN_OPTIONS =
    "ignore_unknown_options";
69 70 71 72 73 74 75
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 =
76
    "compression_max_dict_bytes";
77 78 79 80 81 82 83
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";
84

85
const char* LDBCommand::DELIM = " ==> ";
86

87 88
namespace {

89 90 91
void DumpWalFile(Options options, std::string wal_file, bool print_header,
                 bool print_values, bool is_write_committed,
                 LDBCommandExecuteResult* exec_state);
92

93 94
void DumpSstFile(Options options, std::string filename, bool output_hex,
                 bool show_properties);
95 96
};

97
LDBCommand* LDBCommand::InitFromCmdLineArgs(
98
    int argc, char const* const* argv, const Options& options,
S
sdong 已提交
99 100
    const LDBOptions& ldb_options,
    const std::vector<ColumnFamilyDescriptor>* column_families) {
101
  std::vector<std::string> args;
102 103 104
  for (int i = 1; i < argc; i++) {
    args.push_back(argv[i]);
  }
A
Arun Sharma 已提交
105 106
  return InitFromCmdLineArgs(args, options, ldb_options, column_families,
                             SelectCommand);
107 108 109 110 111 112
}

/**
 * Parse the command-line arguments and create the appropriate LDBCommand2
 * instance.
 * The command line arguments must be in the following format:
113 114
 * ./ldb --db=PATH_TO_DB [--commonOpt1=commonOpt1Val] ..
 *        COMMAND <PARAM1> <PARAM2> ... [-cmdSpecificOpt1=cmdSpecificOpt1Val] ..
115 116
 * This is similar to the command line format used by HBaseClientTool.
 * Command name is not included in args.
117
 * Returns nullptr if the command-line cannot be parsed.
118
 */
119
LDBCommand* LDBCommand::InitFromCmdLineArgs(
120
    const std::vector<std::string>& args, const Options& options,
S
sdong 已提交
121
    const LDBOptions& ldb_options,
A
Andrew Kryczka 已提交
122
    const std::vector<ColumnFamilyDescriptor>* /*column_families*/,
123 124 125 126 127 128 129
    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;
130

131
  // Everything other than option_map and flags. Represents commands
132
  // and their parameters.  For eg: put key1 value1 go into this vector.
133
  std::vector<std::string> cmdTokens;
134

135
  const std::string OPTION_PREFIX = "--";
136

137
  for (const auto& arg : args) {
138
    if (arg[0] == '-' && arg[1] == '-'){
139
      std::vector<std::string> splits = StringSplit(arg, '=');
140
      // --option_name=option_value
141
      if (splits.size() == 2) {
142
        std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
143
        parsed_params.option_map[optionKey] = splits[1];
144 145
      } else if (splits.size() == 1) {
        // --flag_name
146
        std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
147
        parsed_params.flags.push_back(optionKey);
148 149 150 151 152
      } else {
        // --option_name=option_value, option_value contains '='
        std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
        parsed_params.option_map[optionKey] =
            arg.substr(splits[0].length() + 1);
153
      }
154
    } else {
155
      cmdTokens.push_back(arg);
156 157 158 159 160
    }
  }

  if (cmdTokens.size() < 1) {
    fprintf(stderr, "Command not specified!");
161
    return nullptr;
162 163
  }

164 165 166 167
  parsed_params.cmd = cmdTokens[0];
  parsed_params.cmd_params.assign(cmdTokens.begin() + 1, cmdTokens.end());

  LDBCommand* command = selector(parsed_params);
168 169

  if (command) {
170 171
    command->SetDBOptions(options);
    command->SetLDBOptions(ldb_options);
172 173 174 175
  }
  return command;
}

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
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 已提交
192 193 194 195
  } else if (parsed_params.cmd == DeleteRangeCommand::Name()) {
    return new DeleteRangeCommand(parsed_params.cmd_params,
                                  parsed_params.option_map,
                                  parsed_params.flags);
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
  } 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);
226 227 228 229
  } else if (parsed_params.cmd == FileChecksumDumpCommand::Name()) {
    return new FileChecksumDumpCommand(parsed_params.cmd_params,
                                       parsed_params.option_map,
                                       parsed_params.flags);
230 231 232 233
  } else if (parsed_params.cmd == GetPropertyCommand::Name()) {
    return new GetPropertyCommand(parsed_params.cmd_params,
                                  parsed_params.option_map,
                                  parsed_params.flags);
234 235 236 237 238 239 240 241
  } 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);
242 243
  } else if (parsed_params.cmd == DropColumnFamilyCommand::Name()) {
    return new DropColumnFamilyCommand(parsed_params.cmd_params,
244 245
                                       parsed_params.option_map,
                                       parsed_params.flags);
246 247 248 249 250 251 252 253 254 255 256 257
  } 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 已提交
258 259 260 261
  } else if (parsed_params.cmd == CheckPointCommand::Name()) {
    return new CheckPointCommand(parsed_params.cmd_params,
                                 parsed_params.option_map,
                                 parsed_params.flags);
262 263 264
  } else if (parsed_params.cmd == RepairCommand::Name()) {
    return new RepairCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
W
Wanning Jiang 已提交
265 266 267
  } else if (parsed_params.cmd == BackupCommand::Name()) {
    return new BackupCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
A
Andrew Kryczka 已提交
268 269 270
  } else if (parsed_params.cmd == RestoreCommand::Name()) {
    return new RestoreCommand(parsed_params.cmd_params,
                              parsed_params.option_map, parsed_params.flags);
Y
Yanqin Jin 已提交
271 272 273 274 275 276 277 278
  } else if (parsed_params.cmd == WriteExternalSstFilesCommand::Name()) {
    return new WriteExternalSstFilesCommand(parsed_params.cmd_params,
                                            parsed_params.option_map,
                                            parsed_params.flags);
  } else if (parsed_params.cmd == IngestExternalSstFilesCommand::Name()) {
    return new IngestExternalSstFilesCommand(parsed_params.cmd_params,
                                             parsed_params.option_map,
                                             parsed_params.flags);
279 280 281
  } else if (parsed_params.cmd == ListFileRangeDeletesCommand::Name()) {
    return new ListFileRangeDeletesCommand(parsed_params.option_map,
                                           parsed_params.flags);
282 283 284 285
  } else if (parsed_params.cmd == UnsafeRemoveSstFileCommand::Name()) {
    return new UnsafeRemoveSstFileCommand(parsed_params.cmd_params,
                                          parsed_params.option_map,
                                          parsed_params.flags);
286
  }
287
  return nullptr;
288 289
}

A
Arun Sharma 已提交
290 291 292 293 294 295
/* Run the command, and return the execute result. */
void LDBCommand::Run() {
  if (!exec_state_.IsNotStarted()) {
    return;
  }

296 297 298 299 300 301 302 303 304 305 306
  if (!options_.env || options_.env == Env::Default()) {
    Env* env = Env::Default();
    Status s = Env::LoadEnv(env_uri_, &env, &env_guard_);
    if (!s.ok() && !s.IsNotFound()) {
      fprintf(stderr, "LoadEnv: %s\n", s.ToString().c_str());
      exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
      return;
    }
    options_.env = env;
  }

A
Arun Sharma 已提交
307 308
  if (db_ == nullptr && !NoDBOpen()) {
    OpenDB();
309 310 311 312 313 314
    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 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  }

  // 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();
  }
}

330 331 332
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 已提交
333
    : db_(nullptr),
P
Prashant D 已提交
334
      db_ttl_(nullptr),
A
Arun Sharma 已提交
335 336 337 338 339
      is_read_only_(is_read_only),
      is_key_hex_(false),
      is_value_hex_(false),
      is_db_ttl_(false),
      timestamp_(false),
340 341
      try_load_options_(false),
      create_if_missing_(false),
A
Arun Sharma 已提交
342 343 344
      option_map_(options),
      flags_(flags),
      valid_cmd_line_options_(valid_cmd_line_options) {
345
  std::map<std::string, std::string>::const_iterator itr = options.find(ARG_DB);
A
Arun Sharma 已提交
346 347 348 349
  if (itr != options.end()) {
    db_path_ = itr->second;
  }

350 351 352 353 354
  itr = options.find(ARG_ENV_URI);
  if (itr != options.end()) {
    env_uri_ = itr->second;
  }

A
Arun Sharma 已提交
355 356 357 358 359 360 361
  itr = options.find(ARG_CF_NAME);
  if (itr != options.end()) {
    column_family_name_ = itr->second;
  } else {
    column_family_name_ = kDefaultColumnFamilyName;
  }

362 363 364 365 366 367
  itr = options.find(ARG_SECONDARY_PATH);
  secondary_path_ = "";
  if (itr != options.end()) {
    secondary_path_ = itr->second;
  }

A
Arun Sharma 已提交
368 369 370 371
  is_key_hex_ = IsKeyHex(options, flags);
  is_value_hex_ = IsValueHex(options, flags);
  is_db_ttl_ = IsFlagPresent(flags, ARG_TTL);
  timestamp_ = IsFlagPresent(flags, ARG_TIMESTAMP);
372
  try_load_options_ = IsFlagPresent(flags, ARG_TRY_LOAD_OPTIONS);
S
sdong 已提交
373 374
  force_consistency_checks_ =
      !IsFlagPresent(flags, ARG_DISABLE_CONSISTENCY_CHECKS);
375 376
  config_options_.ignore_unknown_options =
      IsFlagPresent(flags, ARG_IGNORE_UNKNOWN_OPTIONS);
A
Arun Sharma 已提交
377 378 379
}

void LDBCommand::OpenDB() {
380
  PrepareOptions();
A
Arun Sharma 已提交
381 382 383
  if (!exec_state_.IsNotStarted()) {
    return;
  }
384 385 386 387
  if (column_families_.empty() && !options_.merge_operator) {
    // No harm to add a general merge operator if it is not specified.
    options_.merge_operator = MergeOperators::CreateStringAppendOperator(':');
  }
A
Arun Sharma 已提交
388 389 390 391 392 393 394 395 396
  // 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");
    }
397 398 399 400
    if (!secondary_path_.empty()) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Open as secondary is not supported for TTL DB yet.");
    }
A
Arun Sharma 已提交
401
    if (is_read_only_) {
A
Andrew Kryczka 已提交
402
      st = DBWithTTL::Open(options_, db_path_, &db_ttl_, 0, true);
A
Arun Sharma 已提交
403
    } else {
A
Andrew Kryczka 已提交
404
      st = DBWithTTL::Open(options_, db_path_, &db_ttl_);
A
Arun Sharma 已提交
405 406 407
    }
    db_ = db_ttl_;
  } else {
408
    if (is_read_only_ && secondary_path_.empty()) {
A
Arun Sharma 已提交
409
      if (column_families_.empty()) {
A
Andrew Kryczka 已提交
410
        st = DB::OpenForReadOnly(options_, db_path_, &db_);
A
Arun Sharma 已提交
411
      } else {
A
Andrew Kryczka 已提交
412
        st = DB::OpenForReadOnly(options_, db_path_, column_families_,
A
Arun Sharma 已提交
413 414 415 416
                                 &handles_opened, &db_);
      }
    } else {
      if (column_families_.empty()) {
417 418 419 420 421
        if (secondary_path_.empty()) {
          st = DB::Open(options_, db_path_, &db_);
        } else {
          st = DB::OpenAsSecondary(options_, db_path_, secondary_path_, &db_);
        }
A
Arun Sharma 已提交
422
      } else {
423 424 425 426 427 428 429
        if (secondary_path_.empty()) {
          st = DB::Open(options_, db_path_, column_families_, &handles_opened,
                        &db_);
        } else {
          st = DB::OpenAsSecondary(options_, db_path_, secondary_path_,
                                   column_families_, &handles_opened, &db_);
        }
A
Arun Sharma 已提交
430 431 432 433
      }
    }
  }
  if (!st.ok()) {
434
    std::string msg = st.ToString();
A
Arun Sharma 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    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();
    }
  }
}

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();
}

484 485
std::vector<std::string> LDBCommand::BuildCmdLineOptions(
    std::vector<std::string> options) {
486 487
  std::vector<std::string> ret = {ARG_ENV_URI,
                                  ARG_DB,
488
                                  ARG_SECONDARY_PATH,
489 490 491 492 493 494 495 496
                                  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,
497
                                  ARG_TRY_LOAD_OPTIONS,
S
sdong 已提交
498
                                  ARG_DISABLE_CONSISTENCY_CHECKS,
499
                                  ARG_IGNORE_UNKNOWN_OPTIONS,
500
                                  ARG_CF_NAME};
A
Arun Sharma 已提交
501 502 503
  ret.insert(ret.end(), options.begin(), options.end());
  return ret;
}
504

505 506 507 508 509 510 511
/**
 * 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.
 */
512
bool LDBCommand::ParseIntOption(
A
Andrew Kryczka 已提交
513
    const std::map<std::string, std::string>& /*options*/,
514 515 516 517
    const std::string& option, int& value,
    LDBCommandExecuteResult& exec_state) {
  std::map<std::string, std::string>::const_iterator itr =
      option_map_.find(option);
518
  if (itr != option_map_.end()) {
519
    try {
S
sdong 已提交
520 521 522
#if defined(CYGWIN)
      value = strtol(itr->second.c_str(), 0, 10);
#else
523
      value = std::stoi(itr->second);
S
sdong 已提交
524
#endif
525
      return true;
526
    } catch (const std::invalid_argument&) {
527 528
      exec_state =
          LDBCommandExecuteResult::Failed(option + " has an invalid value.");
529
    } catch (const std::out_of_range&) {
530 531
      exec_state = LDBCommandExecuteResult::Failed(
          option + " has a value out-of-range.");
532 533
    }
  }
534
  return false;
535 536
}

537 538 539 540 541
/**
 * Parses the specified option and fills in the value.
 * Returns true if the option is found.
 * Returns false otherwise.
 */
542
bool LDBCommand::ParseStringOption(
A
Andrew Kryczka 已提交
543
    const std::map<std::string, std::string>& /*options*/,
544
    const std::string& option, std::string* value) {
545 546 547 548 549 550 551 552
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
    *value = itr->second;
    return true;
  }
  return false;
}

553 554
void LDBCommand::OverrideBaseOptions() {
  options_.create_if_missing = false;
555

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
  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) {
      options_.db_write_buffer_size = db_write_buffer_size;
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_DB_WRITE_BUFFER_SIZE +
                                                    " must be >= 0.");
    }
  }

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

  OverrideBaseCFOptions(static_cast<ColumnFamilyOptions*>(&options_));
}

void LDBCommand::OverrideBaseCFOptions(ColumnFamilyOptions* cf_opts) {
576
  BlockBasedTableOptions table_options;
S
sdong 已提交
577
  bool use_table_options = false;
578
  int bits;
579
  if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
580
    if (bits > 0) {
S
sdong 已提交
581
      use_table_options = true;
582
      table_options.filter_policy.reset(NewBloomFilterPolicy(bits));
583
    } else {
584 585
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOOM_BITS + " must be > 0.");
586 587 588 589
    }
  }

  int block_size;
590
  if (ParseIntOption(option_map_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
591
    if (block_size > 0) {
S
sdong 已提交
592
      use_table_options = true;
593
      table_options.block_size = block_size;
594
    } else {
595 596
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOCK_SIZE + " must be > 0.");
597 598 599
    }
  }

600
  cf_opts->force_consistency_checks = force_consistency_checks_;
S
sdong 已提交
601
  if (use_table_options) {
602
    cf_opts->table_factory.reset(NewBlockBasedTableFactory(table_options));
S
sdong 已提交
603 604
  }

605
  auto itr = option_map_.find(ARG_AUTO_COMPACTION);
606
  if (itr != option_map_.end()) {
607
    cf_opts->disable_auto_compactions = !StringToBool(itr->second);
608 609
  }

610 611
  itr = option_map_.find(ARG_COMPRESSION_TYPE);
  if (itr != option_map_.end()) {
612
    std::string comp = itr->second;
613
    if (comp == "no") {
614
      cf_opts->compression = kNoCompression;
615
    } else if (comp == "snappy") {
616
      cf_opts->compression = kSnappyCompression;
617
    } else if (comp == "zlib") {
618
      cf_opts->compression = kZlibCompression;
619
    } else if (comp == "bzip2") {
620
      cf_opts->compression = kBZip2Compression;
A
Albert Strasheim 已提交
621
    } else if (comp == "lz4") {
622
      cf_opts->compression = kLZ4Compression;
A
Albert Strasheim 已提交
623
    } else if (comp == "lz4hc") {
624
      cf_opts->compression = kLZ4HCCompression;
625
    } else if (comp == "xpress") {
626
      cf_opts->compression = kXpressCompression;
627
    } else if (comp == "zstd") {
628
      cf_opts->compression = kZSTD;
629 630
    } else {
      // Unknown compression.
631 632
      exec_state_ =
          LDBCommandExecuteResult::Failed("Unknown compression level: " + comp);
633 634 635
    }
  }

636 637 638 639
  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) {
640
      cf_opts->compression_opts.max_dict_bytes = compression_max_dict_bytes;
641 642 643 644 645 646
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_COMPRESSION_MAX_DICT_BYTES + " must be >= 0.");
    }
  }

647
  int write_buffer_size;
648 649
  if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
        exec_state_)) {
650
    if (write_buffer_size > 0) {
651
      cf_opts->write_buffer_size = write_buffer_size;
652
    } else {
653
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_WRITE_BUFFER_SIZE +
654
                                                    " must be > 0.");
655 656 657 658
    }
  }

  int file_size;
659
  if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
660
    if (file_size > 0) {
661
      cf_opts->target_file_size_base = file_size;
662
    } else {
663 664
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_FILE_SIZE + " must be > 0.");
665 666 667
    }
  }

S
sdong 已提交
668
  int fix_prefix_len;
669 670
  if (ParseIntOption(option_map_, ARG_FIX_PREFIX_LEN, fix_prefix_len,
                     exec_state_)) {
S
sdong 已提交
671
    if (fix_prefix_len > 0) {
672
      cf_opts->prefix_extractor.reset(
S
sdong 已提交
673 674
          NewFixedPrefixTransform(static_cast<size_t>(fix_prefix_len)));
    } else {
675
      exec_state_ =
676
          LDBCommandExecuteResult::Failed(ARG_FIX_PREFIX_LEN + " must be > 0.");
S
sdong 已提交
677 678
    }
  }
679
}
680

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
// First, initializes the options state using the OPTIONS file when enabled.
// Second, overrides the options according to the CLI arguments and the
// specific subcommand being run.
void LDBCommand::PrepareOptions() {
  if (!create_if_missing_ && try_load_options_) {
    config_options_.env = options_.env;
    Status s = LoadLatestOptions(config_options_, db_path_, &options_,
                                 &column_families_);
    if (!s.ok() && !s.IsNotFound()) {
      // Option file exists but load option file error.
      std::string msg = s.ToString();
      exec_state_ = LDBCommandExecuteResult::Failed(msg);
      db_ = nullptr;
      return;
    }
    if (options_.env->FileExists(options_.wal_dir).IsNotFound()) {
      options_.wal_dir = db_path_;
      fprintf(
          stderr,
          "wal_dir loaded from the option file doesn't exist. Ignore it.\n");
    }

    // If merge operator is not set, set a string append operator.
    for (auto& cf_entry : column_families_) {
      if (!cf_entry.options.merge_operator) {
        cf_entry.options.merge_operator =
            MergeOperators::CreateStringAppendOperator(':');
      }
    }
  }

  OverrideBaseOptions();
  if (exec_state_.IsFailed()) {
    return;
  }

  if (column_families_.empty()) {
    // Reads the MANIFEST to figure out what column families exist. In this
    // case, the option overrides from the CLI argument/specific subcommand
    // apply to all column families.
    std::vector<std::string> cf_list;
    Status st = DB::ListColumnFamilies(options_, db_path_, &cf_list);
    // It 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, options_);
      }
    }
  } else {
    // We got column families from the OPTIONS file. In this case, the option
    // overrides from the CLI argument/specific subcommand only apply to the
    // column family specified by `--column_family_name`.
    auto column_families_iter =
        std::find_if(column_families_.begin(), column_families_.end(),
                     [this](const ColumnFamilyDescriptor& cf_desc) {
                       return cf_desc.name == column_family_name_;
                     });
    if (column_families_iter == column_families_.end()) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Non-existing column family " + column_family_name_);
      return;
    }
747
    OverrideBaseCFOptions(&column_families_iter->options);
748
  }
749 750
}

751 752 753
bool LDBCommand::ParseKeyValue(const std::string& line, std::string* key,
                               std::string* value, bool is_key_hex,
                               bool is_value_hex) {
754
  size_t pos = line.find(DELIM);
755
  if (pos != std::string::npos) {
756 757 758 759 760 761 762 763 764 765 766 767 768
    *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;
  }
}
769

770 771 772 773 774 775 776 777
/**
 * 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() {
778 779 780 781 782 783
  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()) {
784 785 786 787
      fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
      return false;
    }
  }
788

789 790 791 792 793
  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()) {
794 795
      fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
      return false;
796 797 798
    }
  }

799 800 801 802
  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());
803 804 805 806 807 808
    return false;
  }

  return true;
}

809 810
std::string LDBCommand::HexToString(const std::string& str) {
  std::string result;
A
Arun Sharma 已提交
811 812 813 814 815 816 817 818 819 820 821
  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;
}

822 823
std::string LDBCommand::StringToHex(const std::string& str) {
  std::string result("0x");
A
Arun Sharma 已提交
824 825 826 827
  result.append(Slice(str).ToString(true));
  return result;
}

828 829 830 831
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 已提交
832 833 834 835 836 837
  result.append(is_key_hex ? StringToHex(key) : key);
  result.append(DELIM);
  result.append(is_value_hex ? StringToHex(value) : value);
  return result;
}

838 839
std::string LDBCommand::PrintKeyValue(const std::string& key,
                                      const std::string& value, bool is_hex) {
A
Arun Sharma 已提交
840 841 842
  return PrintKeyValue(key, value, is_hex, is_hex);
}

843
std::string LDBCommand::HelpRangeCmdArgs() {
A
Arun Sharma 已提交
844 845 846 847 848 849 850
  std::ostringstream str_stream;
  str_stream << " ";
  str_stream << "[--" << ARG_FROM << "] ";
  str_stream << "[--" << ARG_TO << "] ";
  return str_stream.str();
}

851 852
bool LDBCommand::IsKeyHex(const std::map<std::string, std::string>& options,
                          const std::vector<std::string>& flags) {
A
Arun Sharma 已提交
853 854 855 856 857
  return (IsFlagPresent(flags, ARG_HEX) || IsFlagPresent(flags, ARG_KEY_HEX) ||
          ParseBooleanOption(options, ARG_HEX, false) ||
          ParseBooleanOption(options, ARG_KEY_HEX, false));
}

858 859
bool LDBCommand::IsValueHex(const std::map<std::string, std::string>& options,
                            const std::vector<std::string>& flags) {
A
Arun Sharma 已提交
860 861 862 863 864 865
  return (IsFlagPresent(flags, ARG_HEX) ||
          IsFlagPresent(flags, ARG_VALUE_HEX) ||
          ParseBooleanOption(options, ARG_HEX, false) ||
          ParseBooleanOption(options, ARG_VALUE_HEX, false));
}

866 867 868 869
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 已提交
870
  if (itr != options.end()) {
871
    std::string option_val = itr->second;
A
Arun Sharma 已提交
872 873 874 875 876
    return StringToBool(itr->second);
  }
  return default_val;
}

877
bool LDBCommand::StringToBool(std::string val) {
A
Arun Sharma 已提交
878 879 880 881 882 883 884 885 886 887 888 889
  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";
  }
}

890
CompactorCommand::CompactorCommand(
A
Andrew Kryczka 已提交
891
    const std::vector<std::string>& /*params*/,
892 893 894 895 896 897 898 899 900
    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);
901 902 903 904 905 906 907 908 909 910 911 912
  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_) {
913 914 915 916 917 918 919 920 921
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

922
void CompactorCommand::Help(std::string& ret) {
923 924 925 926
  ret.append("  ");
  ret.append(CompactorCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
927 928
}

929
void CompactorCommand::DoCommand() {
S
sdong 已提交
930 931 932 933
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
934

935 936
  Slice* begin = nullptr;
  Slice* end = nullptr;
937
  if (!null_from_) {
938
    begin = new Slice(from_);
939 940
  }
  if (!null_to_) {
941
    end = new Slice(to_);
942 943
  }

944
  CompactRangeOptions cro;
945
  cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
946

947
  db_->CompactRange(cro, GetCfHandle(), begin, end);
948
  exec_state_ = LDBCommandExecuteResult::Succeed("");
949 950 951 952 953

  delete begin;
  delete end;
}

954
// ---------------------------------------------------------------------------
955 956 957
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";
958

959
DBLoaderCommand::DBLoaderCommand(
A
Andrew Kryczka 已提交
960
    const std::vector<std::string>& /*params*/,
961 962 963 964 965 966 967 968 969 970
    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) {
971 972
  create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
973 974
  bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  compact_ = IsFlagPresent(flags, ARG_COMPACT);
Z
Zheng Shao 已提交
975 976
}

977
void DBLoaderCommand::Help(std::string& ret) {
978 979 980 981 982 983 984
  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 已提交
985 986
}

987 988 989
void DBLoaderCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
990
  if (bulk_load_) {
991
    options_.PrepareForBulkLoad();
992
  }
Z
Zheng Shao 已提交
993 994
}

995
void DBLoaderCommand::DoCommand() {
Z
Zheng Shao 已提交
996
  if (!db_) {
S
sdong 已提交
997
    assert(GetExecuteState().IsFailed());
Z
Zheng Shao 已提交
998 999 1000 1001 1002 1003 1004 1005 1006
    return;
  }

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

  int bad_lines = 0;
1007
  std::string line;
1008 1009 1010 1011
  // 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')) {
1012 1013
    std::string key;
    std::string value;
1014
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
S
sdong 已提交
1015
      db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
Z
Zheng Shao 已提交
1016 1017 1018 1019 1020 1021 1022 1023
    } 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 ++;
    }
  }
1024

Z
Zheng Shao 已提交
1025
  if (bad_lines > 0) {
1026
    std::cout << "Warning: " << bad_lines << " bad lines ignored." << std::endl;
Z
Zheng Shao 已提交
1027
  }
1028
  if (compact_) {
S
sdong 已提交
1029
    db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);
1030
  }
Z
Zheng Shao 已提交
1031 1032
}

1033 1034
// ----------------------------------------------------------------------------

1035 1036
namespace {

1037 1038
void DumpManifestFile(Options options, std::string file, bool verbose, bool hex,
                      bool json) {
1039 1040
  EnvOptions sopt;
  std::string dbname("dummy");
1041 1042
  std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
                                        options.table_cache_numshardbits));
1043 1044 1045 1046
  // 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);
1047
  options.num_levels = 64;
S
sdong 已提交
1048
  WriteController wc(options.delayed_write_rate);
1049
  WriteBufferManager wb(options.db_write_buffer_size);
1050
  ImmutableDBOptions immutable_db_options(options);
1051
  VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc,
1052
                      /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr);
1053
  Status s = versions.DumpManifest(options, file, verbose, hex, json);
1054
  if (!s.ok()) {
1055 1056
    fprintf(stderr, "Error in processing file %s %s\n", file.c_str(),
            s.ToString().c_str());
1057 1058 1059 1060 1061
  }
}

}  // namespace

1062 1063 1064
const std::string ManifestDumpCommand::ARG_VERBOSE = "verbose";
const std::string ManifestDumpCommand::ARG_JSON = "json";
const std::string ManifestDumpCommand::ARG_PATH = "path";
1065

1066
void ManifestDumpCommand::Help(std::string& ret) {
1067 1068 1069
  ret.append("  ");
  ret.append(ManifestDumpCommand::Name());
  ret.append(" [--" + ARG_VERBOSE + "]");
1070
  ret.append(" [--" + ARG_JSON + "]");
1071 1072
  ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  ret.append("\n");
1073 1074
}

1075
ManifestDumpCommand::ManifestDumpCommand(
A
Andrew Kryczka 已提交
1076
    const std::vector<std::string>& /*params*/,
1077 1078 1079 1080 1081 1082 1083 1084
    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_("") {
1085
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
1086
  json_ = IsFlagPresent(flags, ARG_JSON);
1087

1088 1089
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_PATH);
1090 1091 1092
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
1093
      exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
    }
  }
}

void ManifestDumpCommand::DoCommand() {

  std::string manifestfile;

  if (!path_.empty()) {
    manifestfile = path_;
  } else {
    // 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 已提交
1107

1108 1109 1110 1111 1112 1113 1114
    std::vector<std::string> files;
    Status s = options_.env->GetChildren(db_path_, &files);
    if (!s.ok()) {
      std::string err_msg = s.ToString();
      err_msg.append(": Failed to list the content of ");
      err_msg.append(db_path_);
      exec_state_ = LDBCommandExecuteResult::Failed(err_msg);
1115 1116
      return;
    }
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    const std::string kManifestNamePrefix = "MANIFEST-";
    std::string matched_file;
#ifdef OS_WIN
    const char kPathDelim = '\\';
#else
    const char kPathDelim = '/';
#endif
    for (const auto& file_path : files) {
      // Some Env::GetChildren() return absolute paths. Some directories' path
      // end with path delim, e.g. '/' or '\\'.
      size_t pos = file_path.find_last_of(kPathDelim);
      if (pos == file_path.size() - 1) {
        continue;
      }
      std::string fname;
      if (pos != std::string::npos) {
        // Absolute path.
        fname.assign(file_path, pos + 1, file_path.size() - pos - 1);
      } else {
        fname = file_path;
      }
      uint64_t file_num = 0;
1139
      FileType file_type = kWalFile;  // Just for initialization
1140 1141 1142
      if (ParseFileName(fname, &file_num, &file_type) &&
          file_type == kDescriptorFile) {
        if (!matched_file.empty()) {
1143
          exec_state_ = LDBCommandExecuteResult::Failed(
1144
              "Multiple MANIFEST files found; use --path to select one");
1145
          return;
1146 1147
        } else {
          matched_file.swap(fname);
1148 1149 1150
        }
      }
    }
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    if (matched_file.empty()) {
      std::string err_msg("No MANIFEST found in ");
      err_msg.append(db_path_);
      exec_state_ = LDBCommandExecuteResult::Failed(err_msg);
      return;
    }
    if (db_path_[db_path_.length() - 1] != '/') {
      db_path_.append("/");
    }
    manifestfile = db_path_ + matched_file;
1161 1162 1163
  }

  if (verbose_) {
1164
    fprintf(stdout, "Processing Manifest file %s\n", manifestfile.c_str());
1165 1166
  }

1167
  DumpManifestFile(options_, manifestfile, verbose_, is_key_hex_, json_);
1168

1169
  if (verbose_) {
1170
    fprintf(stdout, "Processing Manifest file %s done\n", manifestfile.c_str());
1171 1172 1173
  }
}

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
// ----------------------------------------------------------------------------
namespace {

void GetLiveFilesChecksumInfoFromVersionSet(Options options,
                                            const std::string& db_path,
                                            FileChecksumList* checksum_list) {
  EnvOptions sopt;
  Status s;
  std::string dbname(db_path);
  std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
                                        options.table_cache_numshardbits));
  // Notice we are using the default options not through SanitizeOptions(),
  // if VersionSet::GetLiveFilesChecksumInfo depends on any option done by
  // SanitizeOptions(), we need to initialize it manually.
  options.db_paths.emplace_back(db_path, 0);
  options.num_levels = 64;
  WriteController wc(options.delayed_write_rate);
  WriteBufferManager wb(options.db_write_buffer_size);
  ImmutableDBOptions immutable_db_options(options);
  VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc,
1194
                      /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr);
1195 1196
  std::vector<std::string> cf_name_list;
  s = versions.ListColumnFamilies(&cf_name_list, db_path,
1197
                                  immutable_db_options.fs.get());
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
  if (s.ok()) {
    std::vector<ColumnFamilyDescriptor> cf_list;
    for (const auto& name : cf_name_list) {
      cf_list.emplace_back(name, ColumnFamilyOptions(options));
    }
    s = versions.Recover(cf_list, true);
  }
  if (s.ok()) {
    s = versions.GetLiveFilesChecksumInfo(checksum_list);
  }
  if (!s.ok()) {
    fprintf(stderr, "Error Status: %s", s.ToString().c_str());
  }
}

}  // namespace

const std::string FileChecksumDumpCommand::ARG_PATH = "path";

void FileChecksumDumpCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(FileChecksumDumpCommand::Name());
  ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  ret.append("\n");
}

FileChecksumDumpCommand::FileChecksumDumpCommand(
    const std::vector<std::string>& /*params*/,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1228 1229
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions({ARG_PATH, ARG_HEX})),
1230 1231 1232 1233 1234 1235 1236 1237 1238
      path_("") {
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_PATH);
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
      exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
    }
  }
1239
  is_checksum_hex_ = IsFlagPresent(flags, ARG_HEX);
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
}

void FileChecksumDumpCommand::DoCommand() {
  // print out the checksum information in the following format:
  //  sst file number, checksum function name, checksum value
  //  sst file number, checksum function name, checksum value
  //  ......

  std::unique_ptr<FileChecksumList> checksum_list(NewFileChecksumList());
  GetLiveFilesChecksumInfoFromVersionSet(options_, db_path_,
                                         checksum_list.get());
  if (checksum_list != nullptr) {
    std::vector<uint64_t> file_numbers;
    std::vector<std::string> checksums;
    std::vector<std::string> checksum_func_names;
    Status s = checksum_list->GetAllFileChecksums(&file_numbers, &checksums,
                                                  &checksum_func_names);
    if (s.ok()) {
      for (size_t i = 0; i < file_numbers.size(); i++) {
        assert(i < file_numbers.size());
        assert(i < checksums.size());
        assert(i < checksum_func_names.size());
1262 1263 1264 1265 1266 1267
        std::string checksum;
        if (is_checksum_hex_) {
          checksum = StringToHex(checksums[i]);
        } else {
          checksum = std::move(checksums[i]);
        }
1268
        fprintf(stdout, "%" PRId64 ", %s, %s\n", file_numbers[i],
1269
                checksum_func_names[i].c_str(), checksum.c_str());
1270 1271 1272 1273 1274 1275
      }
    }
    fprintf(stdout, "Print SST file checksum information finished \n");
  }
}

1276
// ----------------------------------------------------------------------------
1277

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
void GetPropertyCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(GetPropertyCommand::Name());
  ret.append(" <property_name>");
  ret.append("\n");
}

GetPropertyCommand::GetPropertyCommand(
    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({})) {
  if (params.size() != 1) {
    exec_state_ =
        LDBCommandExecuteResult::Failed("property name must be specified");
  } else {
    property_ = params[0];
  }
}

void GetPropertyCommand::DoCommand() {
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }

  std::map<std::string, std::string> value_map;
  std::string value;

  // Rather than having different ldb command for map properties vs. string
  // properties, we simply try Map property first. (This order only chosen
  // because I prefer the map-style output for
  // "rocksdb.aggregated-table-properties".)
  if (db_->GetMapProperty(GetCfHandle(), property_, &value_map)) {
    if (value_map.empty()) {
      fprintf(stdout, "%s: <empty map>\n", property_.c_str());
    } else {
      for (auto& e : value_map) {
        fprintf(stdout, "%s.%s: %s\n", property_.c_str(), e.first.c_str(),
                e.second.c_str());
      }
    }
  } else if (db_->GetProperty(GetCfHandle(), property_, &value)) {
    fprintf(stdout, "%s: %s\n", property_.c_str(), value.c_str());
  } else {
    exec_state_ =
        LDBCommandExecuteResult::Failed("failed to get property: " + property_);
  }
}

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

1330
void ListColumnFamiliesCommand::Help(std::string& ret) {
1331 1332 1333
  ret.append("  ");
  ret.append(ListColumnFamiliesCommand::Name());
  ret.append("\n");
1334 1335 1336
}

ListColumnFamiliesCommand::ListColumnFamiliesCommand(
1337
    const std::vector<std::string>& /*params*/,
1338 1339
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1340
    : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}
1341 1342

void ListColumnFamiliesCommand::DoCommand() {
1343
  std::vector<std::string> column_families;
1344
  Status s = DB::ListColumnFamilies(options_, db_path_, &column_families);
1345
  if (!s.ok()) {
1346 1347
    fprintf(stderr, "Error in processing db %s %s\n", db_path_.c_str(),
            s.ToString().c_str());
1348
  } else {
1349
    fprintf(stdout, "Column families in %s: \n{", db_path_.c_str());
1350 1351 1352
    bool first = true;
    for (auto cf : column_families) {
      if (!first) {
1353
        fprintf(stdout, ", ");
1354 1355
      }
      first = false;
1356
      fprintf(stdout, "%s", cf.c_str());
1357
    }
1358
    fprintf(stdout, "}\n");
1359 1360 1361
  }
}

1362
void CreateColumnFamilyCommand::Help(std::string& ret) {
S
sdong 已提交
1363 1364 1365 1366 1367 1368 1369
  ret.append("  ");
  ret.append(CreateColumnFamilyCommand::Name());
  ret.append(" --db=<db_path> <new_column_family_name>");
  ret.append("\n");
}

CreateColumnFamilyCommand::CreateColumnFamilyCommand(
1370 1371 1372
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
S
sdong 已提交
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    : 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() {
1383 1384 1385 1386
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
1387
  ColumnFamilyHandle* new_cf_handle = nullptr;
S
sdong 已提交
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
  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();
}

1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
void DropColumnFamilyCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(DropColumnFamilyCommand::Name());
  ret.append(" --db=<db_path> <column_family_name_to_drop>");
  ret.append("\n");
}

DropColumnFamilyCommand::DropColumnFamilyCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1410
    : LDBCommand(options, flags, true, {ARG_DB}) {
1411 1412 1413 1414 1415 1416 1417 1418 1419
  if (params.size() != 1) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "The name of column family to drop must be specified");
  } else {
    cf_name_to_drop_ = params[0];
  }
}

void DropColumnFamilyCommand::DoCommand() {
1420 1421 1422 1423
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
  auto iter = cf_handles_.find(cf_name_to_drop_);
  if (iter == cf_handles_.end()) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "Column family: " + cf_name_to_drop_ + " doesn't exist in db.");
    return;
  }
  ColumnFamilyHandle* cf_handle_to_drop = iter->second;
  Status st = db_->DropColumnFamily(cf_handle_to_drop);
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "Fail to drop column family: " + st.ToString());
  }
  CloseDB();
}

1441
// ----------------------------------------------------------------------------
I
Igor Canadi 已提交
1442 1443
namespace {

1444 1445
// 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
1446 1447 1448
void IncBucketCounts(std::vector<uint64_t>& bucket_counts, int ttl_start,
                     int time_range, int bucket_size, int timekv,
                     int num_buckets) {
1449 1450 1451 1452
#ifdef NDEBUG
  (void)time_range;
  (void)num_buckets;
#endif
1453 1454 1455
  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;
1456
  bucket_counts[bucket]++;
1457 1458
}

1459 1460 1461
void PrintBucketCounts(const std::vector<uint64_t>& bucket_counts,
                       int ttl_start, int ttl_end, int bucket_size,
                       int num_buckets) {
1462
  int time_point = ttl_start;
1463 1464
  for(int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
    fprintf(stdout, "Keys in range %s to %s : %lu\n",
1465 1466
            TimeToHumanString(time_point).c_str(),
            TimeToHumanString(time_point + bucket_size).c_str(),
1467
            (unsigned long)bucket_counts[i]);
1468
  }
1469
  fprintf(stdout, "Keys in range %s to %s : %lu\n",
1470 1471
          TimeToHumanString(time_point).c_str(),
          TimeToHumanString(ttl_end).c_str(),
1472
          (unsigned long)bucket_counts[num_buckets - 1]);
1473 1474
}

I
Igor Canadi 已提交
1475 1476
}  // namespace

1477 1478 1479 1480
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";
1481

1482
InternalDumpCommand::InternalDumpCommand(
A
Andrew Kryczka 已提交
1483
    const std::vector<std::string>& /*params*/,
1484 1485
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
    : 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) {
1499 1500 1501
  has_from_ = ParseStringOption(options, ARG_FROM, &from_);
  has_to_ = ParseStringOption(options, ARG_TO, &to_);

1502
  ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
1503 1504
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_COUNT_DELIM);
1505 1506 1507
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
1508
   // fprintf(stdout,"delim = %c\n",delim_[0]);
1509 1510
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
1511
    delim_=".";
1512
  }
1513 1514 1515

  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
1516
  is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
1517

1518
  if (is_input_key_hex_) {
1519 1520 1521 1522 1523 1524 1525 1526 1527
    if (has_from_) {
      from_ = HexToString(from_);
    }
    if (has_to_) {
      to_ = HexToString(to_);
    }
  }
}

1528
void InternalDumpCommand::Help(std::string& ret) {
1529 1530 1531 1532 1533 1534 1535 1536 1537
  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");
1538 1539 1540 1541
}

void InternalDumpCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
1542
    assert(GetExecuteState().IsFailed());
1543 1544 1545 1546
    return;
  }

  if (print_stats_) {
1547
    std::string stats;
S
sdong 已提交
1548
    if (db_->GetProperty(GetCfHandle(), "rocksdb.stats", &stats)) {
1549 1550 1551 1552 1553
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Cast as DBImpl to get internal iterator
A
Andrew Kryczka 已提交
1554
  std::vector<KeyVersion> key_versions;
1555 1556
  Status st = GetAllKeyVersions(db_, GetCfHandle(), from_, to_, max_keys_,
                                &key_versions);
A
Andrew Kryczka 已提交
1557 1558
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1559 1560
    return;
  }
1561
  std::string rtype1, rtype2, row, val;
1562
  rtype2 = "";
1563 1564
  uint64_t c=0;
  uint64_t s1=0,s2=0;
1565

1566
  long long count = 0;
A
Andrew Kryczka 已提交
1567 1568 1569 1570 1571 1572
  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.
1573 1574 1575
      break;
    }
    ++count;
1576 1577 1578
    int k;
    if (count_delim_) {
      rtype1 = "";
1579
      s1=0;
A
Andrew Kryczka 已提交
1580 1581
      row = ikey.Encode().ToString();
      val = key_version.value;
1582
      for(k=0;row[k]!='\x01' && row[k]!='\0';k++)
1583
        s1++;
1584
      for(k=0;val[k]!='\x01' && val[k]!='\0';k++)
1585
        s1++;
1586 1587 1588
      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) {
1589 1590
        fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
                rtype2.c_str(), c, s2);
1591 1592
        c=1;
        s2=s1;
1593 1594 1595
        rtype2 = rtype1;
      } else {
        c++;
1596 1597
        s2+=s1;
        rtype2=rtype1;
A
Andrew Kryczka 已提交
1598
      }
1599
    }
1600

1601
    if (!count_only_ && !count_delim_) {
1602
      std::string key = ikey.DebugString(is_key_hex_);
A
Andrew Kryczka 已提交
1603
      std::string value = Slice(key_version.value).ToString(is_value_hex_);
1604
      std::cout << key << " => " << value << "\n";
1605 1606 1607
    }

    // Terminate if maximum number of keys have been dumped
1608
    if (max_keys_ > 0 && count >= max_keys_) break;
1609
  }
1610
  if(count_delim_) {
1611 1612 1613 1614 1615
    fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
            rtype2.c_str(), c, s2);
  } else {
    fprintf(stdout, "Internal keys in range: %lld\n", count);
  }
1616 1617
}

1618 1619 1620 1621
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";
1622

1623
DBDumperCommand::DBDumperCommand(
A
Andrew Kryczka 已提交
1624
    const std::vector<std::string>& /*params*/,
1625 1626
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
    : 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) {
1639 1640
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_FROM);
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
  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 已提交
1655 1656 1657
#if defined(CYGWIN)
      max_keys_ = strtol(itr->second.c_str(), 0, 10);
#else
1658
      max_keys_ = std::stoi(itr->second);
S
sdong 已提交
1659
#endif
1660
    } catch (const std::invalid_argument&) {
1661
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
1662
                                                    " has an invalid value");
1663
    } catch (const std::out_of_range&) {
1664 1665
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
1666 1667
    }
  }
1668 1669 1670 1671 1672 1673
  itr = options.find(ARG_COUNT_DELIM);
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
1674
    delim_=".";
1675
  }
1676

1677 1678 1679 1680
  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);

  if (is_key_hex_) {
1681 1682 1683 1684 1685 1686 1687
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
1688 1689 1690 1691

  itr = options.find(ARG_PATH);
  if (itr != options.end()) {
    path_ = itr->second;
1692 1693 1694
    if (db_path_.empty()) {
      db_path_ = path_;
    }
1695
  }
1696 1697
}

1698
void DBDumperCommand::Help(std::string& ret) {
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
  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]");
1711
  ret.append(" [--" + ARG_PATH + "=<path_to_a_file>]");
1712
  ret.append("\n");
1713 1714
}

1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
/**
 * 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.
 *
 */
1726
void DBDumperCommand::DoCommand() {
1727
  if (!db_) {
1728
    assert(!path_.empty());
1729
    std::string fileName = GetFileNameFromPath(path_);
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
    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) {
1742
      case kWalFile:
1743
        // TODO(myabandeh): allow configuring is_write_commited
1744 1745 1746
        DumpWalFile(options_, path_, /* print_header_ */ true,
                    /* print_values_ */ true, true /* is_write_commited */,
                    &exec_state_);
1747 1748
        break;
      case kTableFile:
1749
        DumpSstFile(options_, path_, is_key_hex_, /* show_properties */ true);
1750 1751
        break;
      case kDescriptorFile:
1752
        DumpManifestFile(options_, path_, /* verbose_ */ false, is_key_hex_,
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
                         /*  json_ */ false);
        break;
      default:
        exec_state_ = LDBCommandExecuteResult::Failed(
            "File type not supported: " + path_);
        break;
    }

  } else {
    DoDumpCommand();
1763
  }
1764 1765 1766 1767 1768 1769
}

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

1770 1771 1772
  // Parse command line args
  uint64_t count = 0;
  if (print_stats_) {
1773
    std::string stats;
1774
    if (db_->GetProperty("rocksdb.stats", &stats)) {
1775 1776 1777 1778 1779
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Setup key iterator
1780 1781 1782
  ReadOptions scan_read_opts;
  scan_read_opts.total_order_seek = true;
  Iterator* iter = db_->NewIterator(scan_read_opts, GetCfHandle());
1783
  Status st = iter->status();
1784
  if (!st.ok()) {
1785 1786
    exec_state_ =
        LDBCommandExecuteResult::Failed("Iterator error." + st.ToString());
1787 1788 1789 1790 1791 1792 1793 1794 1795
  }

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

  int max_keys = max_keys_;
1796
  int ttl_start;
1797
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
1798
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
1799 1800
  }
  int ttl_end;
1801
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
1802
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
1803 1804 1805 1806 1807 1808 1809 1810
  }
  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;
1811
  if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
1812 1813 1814
      bucket_size <= 0) {
    bucket_size = time_range; // Will have just 1 bucket by default
  }
1815
  //cretaing variables for row count of each type
1816
  std::string rtype1, rtype2, row, val;
1817
  rtype2 = "";
1818 1819
  uint64_t c=0;
  uint64_t s1=0,s2=0;
1820

1821
  // At this point, bucket_size=0 => time_range=0
1822 1823 1824
  int num_buckets = (bucket_size >= time_range)
                        ? 1
                        : ((time_range + bucket_size - 1) / bucket_size);
1825
  std::vector<uint64_t> bucket_counts(num_buckets, 0);
1826
  if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
1827
    fprintf(stdout, "Dumping key-values from %s to %s\n",
1828 1829
            TimeToHumanString(ttl_start).c_str(),
            TimeToHumanString(ttl_end).c_str());
1830 1831
  }

1832 1833
  HistogramImpl vsize_hist;

1834
  for (; iter->Valid(); iter->Next()) {
1835
    int rawtime = 0;
1836 1837 1838 1839 1840 1841
    // 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;
1842
    if (is_db_ttl_) {
1843
      TtlIterator* it_ttl = static_cast_with_check<TtlIterator>(iter);
Y
Yanqin Jin 已提交
1844
      rawtime = it_ttl->ttl_timestamp();
1845
      if (rawtime < ttl_start || rawtime >= ttl_end) {
1846 1847 1848
        continue;
      }
    }
1849 1850 1851
    if (max_keys > 0) {
      --max_keys;
    }
1852
    if (is_db_ttl_ && num_buckets > 1) {
1853
      IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
1854 1855
                      rawtime, num_buckets);
    }
1856
    ++count;
1857 1858 1859 1860 1861
    if (count_delim_) {
      rtype1 = "";
      row = iter->key().ToString();
      val = iter->value().ToString();
      s1 = row.size()+val.size();
1862 1863 1864
      for(int j=0;row[j]!=delim_[0] && row[j]!='\0';j++)
        rtype1+=row[j];
      if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
1865 1866
        fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
                rtype2.c_str(), c, s2);
1867 1868
        c=1;
        s2=s1;
1869 1870
        rtype2 = rtype1;
      } else {
1871 1872 1873
          c++;
          s2+=s1;
          rtype2=rtype1;
1874
      }
1875

1876 1877
    }

1878 1879 1880
    if (count_only_) {
      vsize_hist.Add(iter->value().size());
    }
1881

1882
    if (!count_only_ && !count_delim_) {
1883
      if (is_db_ttl_ && timestamp_) {
1884
        fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
1885
      }
1886 1887 1888
      std::string str =
          PrintKeyValue(iter->key().ToString(), iter->value().ToString(),
                        is_key_hex_, is_value_hex_);
1889
      fprintf(stdout, "%s\n", str.c_str());
1890 1891
    }
  }
1892

1893
  if (num_buckets > 1 && is_db_ttl_) {
1894
    PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
1895
                      num_buckets);
1896
  } else if(count_delim_) {
1897 1898
    fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
            rtype2.c_str(), c, s2);
1899
  } else {
1900
    fprintf(stdout, "Keys in range: %" PRIu64 "\n", count);
1901
  }
1902 1903 1904 1905 1906

  if (count_only_) {
    fprintf(stdout, "Value size distribution: \n");
    fprintf(stdout, "%s\n", vsize_hist.ToString().c_str());
  }
1907 1908 1909 1910
  // Clean up
  delete iter;
}

1911 1912 1913
const std::string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
const std::string ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS =
    "print_old_levels";
1914

1915
ReduceDBLevelsCommand::ReduceDBLevelsCommand(
A
Andrew Kryczka 已提交
1916
    const std::vector<std::string>& /*params*/,
1917 1918 1919 1920 1921 1922 1923
    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) {
1924
  ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
1925
  print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
1926

1927
  if(new_levels_ <= 0) {
1928
    exec_state_ = LDBCommandExecuteResult::Failed(
1929
        " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
1930 1931 1932
  }
}

1933 1934 1935
std::vector<std::string> ReduceDBLevelsCommand::PrepareArgs(
    const std::string& db_path, int new_levels, bool print_old_level) {
  std::vector<std::string> ret;
1936
  ret.push_back("reduce_levels");
1937
  ret.push_back("--" + ARG_DB + "=" + db_path);
1938 1939
  ret.push_back("--" + ARG_NEW_LEVELS + "=" +
                ROCKSDB_NAMESPACE::ToString(new_levels));
1940
  if(print_old_level) {
1941
    ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
1942 1943 1944 1945
  }
  return ret;
}

1946
void ReduceDBLevelsCommand::Help(std::string& ret) {
1947 1948 1949 1950 1951
  ret.append("  ");
  ret.append(ReduceDBLevelsCommand::Name());
  ret.append(" --" + ARG_NEW_LEVELS + "=<New number of levels>");
  ret.append(" [--" + ARG_PRINT_OLD_LEVELS + "]");
  ret.append("\n");
1952 1953
}

1954 1955 1956 1957 1958
void ReduceDBLevelsCommand::OverrideBaseCFOptions(
    ColumnFamilyOptions* cf_opts) {
  LDBCommand::OverrideBaseCFOptions(cf_opts);
  cf_opts->num_levels = old_levels_;
  cf_opts->max_bytes_for_level_multiplier_additional.resize(cf_opts->num_levels,
1959
                                                            1);
1960
  // Disable size compaction
1961 1962
  cf_opts->max_bytes_for_level_base = 1ULL << 50;
  cf_opts->max_bytes_for_level_multiplier = 1;
1963 1964
}

1965
Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt,
1966
    int* levels) {
1967
  ImmutableDBOptions db_options(opt);
H
Haobo Xu 已提交
1968
  EnvOptions soptions;
I
Igor Canadi 已提交
1969
  std::shared_ptr<Cache> tc(
1970
      NewLRUCache(opt.max_open_files - 10, opt.table_cache_numshardbits));
1971
  const InternalKeyComparator cmp(opt.comparator);
S
sdong 已提交
1972
  WriteController wc(opt.delayed_write_rate);
1973
  WriteBufferManager wb(opt.db_write_buffer_size);
1974
  VersionSet versions(db_path_, &db_options, soptions, tc.get(), &wb, &wc,
1975
                      /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr);
I
Igor Canadi 已提交
1976
  std::vector<ColumnFamilyDescriptor> dummy;
1977
  ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName,
I
Igor Canadi 已提交
1978 1979
                                          ColumnFamilyOptions(opt));
  dummy.push_back(dummy_descriptor);
1980 1981 1982
  // 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 已提交
1983
  Status st = versions.Recover(dummy);
1984 1985 1986 1987
  if (!st.ok()) {
    return st;
  }
  int max = -1;
1988
  auto default_cfd = versions.GetColumnFamilySet()->GetDefault();
I
Igor Canadi 已提交
1989
  for (int i = 0; i < default_cfd->NumberLevels(); i++) {
S
sdong 已提交
1990
    if (default_cfd->current()->storage_info()->NumLevelFiles(i)) {
1991 1992 1993 1994 1995 1996 1997 1998
      max = i;
    }
  }

  *levels = max + 1;
  return st;
}

1999
void ReduceDBLevelsCommand::DoCommand() {
2000
  if (new_levels_ <= 1) {
2001 2002
    exec_state_ =
        LDBCommandExecuteResult::Failed("Invalid number of levels.\n");
2003 2004 2005
    return;
  }

2006
  Status st;
2007
  PrepareOptions();
2008
  int old_level_num = -1;
2009
  st = GetOldNumOfLevels(options_, &old_level_num);
2010
  if (!st.ok()) {
2011
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2012 2013 2014
    return;
  }

2015
  if (print_old_levels_) {
2016
    fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
2017
  }
2018

2019 2020
  if (old_level_num <= new_levels_) {
    return;
2021 2022
  }

2023 2024 2025
  old_levels_ = old_level_num;

  OpenDB();
2026
  if (exec_state_.IsFailed()) {
2027 2028
    return;
  }
2029
  assert(db_ != nullptr);
2030
  // Compact the whole DB to put all files to the highest level.
2031
  fprintf(stdout, "Compacting the db...\n");
2032 2033 2034
  st =
      db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);

2035 2036
  CloseDB();

2037 2038 2039 2040 2041
  if (st.ok()) {
    EnvOptions soptions;
    st = VersionSet::ReduceNumberOfLevels(db_path_, &options_, soptions,
                                          new_levels_);
  }
2042
  if (!st.ok()) {
2043
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2044 2045 2046 2047
    return;
  }
}

2048 2049 2050 2051
const std::string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
    "old_compaction_style";
const std::string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
    "new_compaction_style";
2052 2053

ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
A
Andrew Kryczka 已提交
2054
    const std::vector<std::string>& /*params*/,
2055 2056 2057 2058 2059 2060 2061
    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) {
2062 2063
  ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
    exec_state_);
2064 2065
  if (old_compaction_style_ != kCompactionStyleLevel &&
     old_compaction_style_ != kCompactionStyleUniversal) {
2066
    exec_state_ = LDBCommandExecuteResult::Failed(
2067 2068
        "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
        "style. Check ldb help for proper compaction style value.\n");
2069 2070 2071
    return;
  }

2072 2073
  ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
    exec_state_);
2074 2075
  if (new_compaction_style_ != kCompactionStyleLevel &&
     new_compaction_style_ != kCompactionStyleUniversal) {
2076
    exec_state_ = LDBCommandExecuteResult::Failed(
2077 2078
        "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
        "style. Check ldb help for proper compaction style value.\n");
2079 2080 2081 2082
    return;
  }

  if (new_compaction_style_ == old_compaction_style_) {
2083
    exec_state_ = LDBCommandExecuteResult::Failed(
2084 2085
        "Old compaction style is the same as new compaction style. "
        "Nothing to do.\n");
2086 2087 2088 2089 2090
    return;
  }

  if (old_compaction_style_ == kCompactionStyleUniversal &&
      new_compaction_style_ == kCompactionStyleLevel) {
2091
    exec_state_ = LDBCommandExecuteResult::Failed(
2092 2093
        "Convert from universal compaction to level compaction. "
        "Nothing to do.\n");
2094 2095 2096 2097
    return;
  }
}

2098
void ChangeCompactionStyleCommand::Help(std::string& ret) {
2099 2100 2101 2102 2103 2104 2105
  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");
2106 2107
}

2108 2109 2110
void ChangeCompactionStyleCommand::OverrideBaseCFOptions(
    ColumnFamilyOptions* cf_opts) {
  LDBCommand::OverrideBaseCFOptions(cf_opts);
2111 2112 2113 2114
  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.
2115 2116 2117 2118 2119
    cf_opts->disable_auto_compactions = true;
    cf_opts->target_file_size_base = INT_MAX;
    cf_opts->target_file_size_multiplier = 1;
    cf_opts->max_bytes_for_level_base = INT_MAX;
    cf_opts->max_bytes_for_level_multiplier = 1;
2120 2121 2122 2123
  }
}

void ChangeCompactionStyleCommand::DoCommand() {
2124 2125 2126 2127
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2128 2129 2130
  // print db stats before we have made any change
  std::string property;
  std::string files_per_level;
S
sdong 已提交
2131 2132 2133
  for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
    db_->GetProperty(GetCfHandle(),
                     "rocksdb.num-files-at-level" + NumberToString(i),
2134 2135
                     &property);

2136
    // format print string
2137
    char buf[100];
2138
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
2139 2140 2141 2142 2143 2144
    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
2145 2146 2147
  CompactRangeOptions compact_options;
  compact_options.change_level = true;
  compact_options.target_level = 0;
S
sdong 已提交
2148
  db_->CompactRange(compact_options, GetCfHandle(), nullptr, nullptr);
2149 2150 2151 2152

  // verify compaction result
  files_per_level = "";
  int num_files = 0;
2153
  for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
S
sdong 已提交
2154 2155
    db_->GetProperty(GetCfHandle(),
                     "rocksdb.num-files-at-level" + NumberToString(i),
2156 2157
                     &property);

2158
    // format print string
2159
    char buf[100];
2160
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
2161 2162 2163 2164 2165 2166
    files_per_level += buf;

    num_files = atoi(property.c_str());

    // level 0 should have only 1 file
    if (i == 0 && num_files != 1) {
2167 2168 2169 2170
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level 0 after compaction is " +
          ToString(num_files) + ", not 1.\n");
2171 2172 2173 2174
      return;
    }
    // other levels should have no file
    if (i > 0 && num_files != 0) {
2175 2176 2177 2178 2179
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level " +
          ToString(i) + " after compaction is " + ToString(num_files) +
          ", not 0.\n");
2180 2181 2182 2183 2184 2185 2186 2187
      return;
    }
  }

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

2188 2189 2190 2191 2192
// ----------------------------------------------------------------------------

namespace {

struct StdErrReporter : public log::Reader::Reporter {
2193
  void Corruption(size_t /*bytes*/, const Status& s) override {
2194
    std::cerr << "Corruption detected in log file " << s.ToString() << "\n";
2195 2196 2197
  }
};

2198 2199
class InMemoryHandler : public WriteBatch::Handler {
 public:
2200 2201 2202 2203 2204 2205
  InMemoryHandler(std::stringstream& row, bool print_values,
                  bool write_after_commit = false)
      : Handler(),
        row_(row),
        print_values_(print_values),
        write_after_commit_(write_after_commit) {}
2206

2207
  void commonPutMerge(const Slice& key, const Slice& value) {
2208
    std::string k = LDBCommand::StringToHex(key.ToString());
2209
    if (print_values_) {
2210
      std::string v = LDBCommand::StringToHex(value.ToString());
2211 2212 2213 2214 2215
      row_ << k << " : ";
      row_ << v << " ";
    } else {
      row_ << k << " ";
    }
2216
  }
2217

2218
  Status PutCF(uint32_t cf, const Slice& key, const Slice& value) override {
R
Reid Horuff 已提交
2219
    row_ << "PUT(" << cf << ") : ";
2220
    commonPutMerge(key, value);
R
Reid Horuff 已提交
2221
    return Status::OK();
2222 2223
  }

2224
  Status MergeCF(uint32_t cf, const Slice& key, const Slice& value) override {
R
Reid Horuff 已提交
2225
    row_ << "MERGE(" << cf << ") : ";
2226
    commonPutMerge(key, value);
R
Reid Horuff 已提交
2227
    return Status::OK();
2228
  }
2229

2230
  Status MarkNoop(bool) override {
2231 2232 2233 2234
    row_ << "NOOP ";
    return Status::OK();
  }

2235
  Status DeleteCF(uint32_t cf, const Slice& key) override {
R
Reid Horuff 已提交
2236
    row_ << "DELETE(" << cf << ") : ";
2237
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
R
Reid Horuff 已提交
2238 2239 2240
    return Status::OK();
  }

2241
  Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
R
Reid Horuff 已提交
2242 2243 2244 2245 2246
    row_ << "SINGLE_DELETE(" << cf << ") : ";
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
    return Status::OK();
  }

2247 2248
  Status DeleteRangeCF(uint32_t cf, const Slice& begin_key,
                       const Slice& end_key) override {
A
Andrew Kryczka 已提交
2249 2250 2251 2252 2253 2254
    row_ << "DELETE_RANGE(" << cf << ") : ";
    row_ << LDBCommand::StringToHex(begin_key.ToString()) << " ";
    row_ << LDBCommand::StringToHex(end_key.ToString()) << " ";
    return Status::OK();
  }

2255
  Status MarkBeginPrepare(bool unprepare) override {
2256 2257
    row_ << "BEGIN_PREPARE(";
    row_ << (unprepare ? "true" : "false") << ") ";
R
Reid Horuff 已提交
2258 2259 2260
    return Status::OK();
  }

2261
  Status MarkEndPrepare(const Slice& xid) override {
R
Reid Horuff 已提交
2262 2263 2264 2265 2266
    row_ << "END_PREPARE(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
  }

2267
  Status MarkRollback(const Slice& xid) override {
R
Reid Horuff 已提交
2268 2269 2270 2271 2272
    row_ << "ROLLBACK(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
  }

2273
  Status MarkCommit(const Slice& xid) override {
R
Reid Horuff 已提交
2274 2275 2276
    row_ << "COMMIT(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
2277 2278
  }

2279
  ~InMemoryHandler() override {}
2280

2281
 protected:
2282
  bool WriteAfterCommit() const override { return write_after_commit_; }
2283

2284
 private:
2285
  std::stringstream& row_;
2286
  bool print_values_;
2287
  bool write_after_commit_;
2288 2289
};

2290 2291 2292 2293 2294
void DumpWalFile(Options options, std::string wal_file, bool print_header,
                 bool print_values, bool is_write_committed,
                 LDBCommandExecuteResult* exec_state) {
  Env* env = options.env;
  EnvOptions soptions(options);
2295
  std::unique_ptr<SequentialFileReader> wal_file_reader;
2296 2297 2298

  Status status;
  {
2299
    std::unique_ptr<SequentialFile> file;
2300
    status = env->NewSequentialFile(wal_file, &file, soptions);
2301
    if (status.ok()) {
2302 2303
      wal_file_reader.reset(new SequentialFileReader(
          NewLegacySequentialFileWrapper(file), wal_file));
2304 2305
    }
  }
2306 2307
  if (!status.ok()) {
    if (exec_state) {
2308
      *exec_state = LDBCommandExecuteResult::Failed("Failed to open WAL file " +
2309 2310
                                                    status.ToString());
    } else {
2311 2312
      std::cerr << "Error: Failed to open WAL file " << status.ToString()
                << std::endl;
2313 2314 2315
    }
  } else {
    StdErrReporter reporter;
2316 2317 2318 2319
    uint64_t log_number;
    FileType type;

    // we need the log number, but ParseFilename expects dbname/NNN.log.
2320
    std::string sanitized = wal_file;
2321 2322 2323 2324 2325 2326 2327
    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;
    }
2328
    log::Reader reader(options.info_log, std::move(wal_file_reader), &reporter,
2329
                       true /* checksum */, log_number);
2330
    std::string scratch;
2331 2332
    WriteBatch batch;
    Slice record;
2333
    std::stringstream row;
2334
    if (print_header) {
2335
      std::cout << "Sequence,Count,ByteSize,Physical Offset,Key(s)";
2336
      if (print_values) {
2337
        std::cout << " : value ";
2338
      }
2339
      std::cout << "\n";
2340 2341 2342
    }
    while (reader.ReadRecord(&record, &scratch)) {
      row.str("");
2343
      if (record.size() < WriteBatchInternal::kHeader) {
2344 2345 2346 2347 2348 2349 2350 2351
        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() << ",";
2352
        InMemoryHandler handler(row, print_values, is_write_committed);
2353 2354 2355
        batch.Iterate(&handler);
        row << "\n";
      }
2356
      std::cout << row.str();
2357 2358 2359 2360 2361 2362
    }
  }
}

}  // namespace

2363
const std::string WALDumperCommand::ARG_WAL_FILE = "walfile";
2364
const std::string WALDumperCommand::ARG_WRITE_COMMITTED = "write_committed";
2365 2366
const std::string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
const std::string WALDumperCommand::ARG_PRINT_HEADER = "header";
2367

2368
WALDumperCommand::WALDumperCommand(
A
Andrew Kryczka 已提交
2369
    const std::vector<std::string>& /*params*/,
2370 2371 2372
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, true,
2373 2374
                 BuildCmdLineOptions({ARG_WAL_FILE, ARG_WRITE_COMMITTED,
                                      ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
2375
      print_header_(false),
2376 2377
      print_values_(false),
      is_write_committed_(false) {
A
Abhishek Kona 已提交
2378
  wal_file_.clear();
2379

2380 2381
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_WAL_FILE);
2382 2383
  if (itr != options.end()) {
    wal_file_ = itr->second;
A
Abhishek Kona 已提交
2384
  }
2385 2386


2387 2388
  print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
2389 2390
  is_write_committed_ = ParseBooleanOption(options, ARG_WRITE_COMMITTED, true);

A
Abhishek Kona 已提交
2391
  if (wal_file_.empty()) {
2392 2393
    exec_state_ = LDBCommandExecuteResult::Failed("Argument " + ARG_WAL_FILE +
                                                  " must be specified.");
A
Abhishek Kona 已提交
2394 2395 2396
  }
}

2397
void WALDumperCommand::Help(std::string& ret) {
2398 2399 2400 2401 2402
  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 + "] ");
2403
  ret.append(" [--" + ARG_WRITE_COMMITTED + "=true|false] ");
2404
  ret.append("\n");
A
Abhishek Kona 已提交
2405 2406
}

2407
void WALDumperCommand::DoCommand() {
2408 2409
  DumpWalFile(options_, wal_file_, print_header_, print_values_,
              is_write_committed_, &exec_state_);
A
Abhishek Kona 已提交
2410 2411
}

2412
// ----------------------------------------------------------------------------
2413

2414 2415 2416 2417 2418 2419
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})) {
2420
  if (params.size() != 1) {
2421
    exec_state_ = LDBCommandExecuteResult::Failed(
2422
        "<key> must be specified for the get command");
2423 2424 2425 2426 2427 2428 2429 2430 2431
  } else {
    key_ = params.at(0);
  }

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

2432
void GetCommand::Help(std::string& ret) {
2433 2434 2435 2436 2437
  ret.append("  ");
  ret.append(GetCommand::Name());
  ret.append(" <key>");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2438 2439 2440
}

void GetCommand::DoCommand() {
S
sdong 已提交
2441 2442 2443 2444
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2445
  std::string value;
S
sdong 已提交
2446
  Status st = db_->Get(ReadOptions(), GetCfHandle(), key_, &value);
2447 2448 2449 2450
  if (st.ok()) {
    fprintf(stdout, "%s\n",
              (is_value_hex_ ? StringToHex(value) : value).c_str());
  } else {
2451
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2452 2453 2454
  }
}

2455
// ----------------------------------------------------------------------------
2456

2457
ApproxSizeCommand::ApproxSizeCommand(
A
Andrew Kryczka 已提交
2458
    const std::vector<std::string>& /*params*/,
2459 2460 2461 2462 2463
    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})) {
2464 2465 2466
  if (options.find(ARG_FROM) != options.end()) {
    start_key_ = options.find(ARG_FROM)->second;
  } else {
2467 2468
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_FROM + " must be specified for approxsize command");
2469 2470 2471 2472 2473 2474
    return;
  }

  if (options.find(ARG_TO) != options.end()) {
    end_key_ = options.find(ARG_TO)->second;
  } else {
2475 2476
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_TO + " must be specified for approxsize command");
2477 2478 2479 2480 2481 2482 2483 2484 2485
    return;
  }

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

2486
void ApproxSizeCommand::Help(std::string& ret) {
2487 2488 2489 2490
  ret.append("  ");
  ret.append(ApproxSizeCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
2491 2492 2493
}

void ApproxSizeCommand::DoCommand() {
S
sdong 已提交
2494 2495 2496 2497
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2498 2499
  Range ranges[1];
  ranges[0] = Range(start_key_, end_key_);
2500
  uint64_t sizes[1];
2501 2502 2503 2504 2505
  Status s = db_->GetApproximateSizes(GetCfHandle(), ranges, 1, sizes);
  if (!s.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
  } else {
    fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
2506 2507 2508
  }
}

2509
// ----------------------------------------------------------------------------
2510

2511 2512 2513 2514 2515 2516 2517
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})) {
2518
  if (params.size() < 2) {
2519
    exec_state_ = LDBCommandExecuteResult::Failed(
2520
        "At least one <key> <value> pair must be specified batchput.");
2521
  } else if (params.size() % 2 != 0) {
2522
    exec_state_ = LDBCommandExecuteResult::Failed(
2523 2524 2525
        "Equal number of <key>s and <value>s must be specified for batchput.");
  } else {
    for (size_t i = 0; i < params.size(); i += 2) {
2526 2527 2528 2529 2530
      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));
2531 2532
    }
  }
2533
  create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
2534 2535
}

2536
void BatchPutCommand::Help(std::string& ret) {
2537 2538 2539
  ret.append("  ");
  ret.append(BatchPutCommand::Name());
  ret.append(" <key> <value> [<key> <value>] [..]");
2540
  ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
2541 2542
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2543 2544 2545
}

void BatchPutCommand::DoCommand() {
S
sdong 已提交
2546 2547 2548 2549
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2550
  WriteBatch batch;
2551

2552 2553 2554
  for (std::vector<std::pair<std::string, std::string>>::const_iterator itr =
           key_values_.begin();
       itr != key_values_.end(); ++itr) {
S
sdong 已提交
2555
    batch.Put(GetCfHandle(), itr->first, itr->second);
2556
  }
2557
  Status st = db_->Write(WriteOptions(), &batch);
2558 2559 2560
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2561
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2562 2563 2564
  }
}

2565 2566 2567
void BatchPutCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
2568 2569
}

2570
// ----------------------------------------------------------------------------
2571

A
Andrew Kryczka 已提交
2572
ScanCommand::ScanCommand(const std::vector<std::string>& /*params*/,
2573 2574 2575 2576 2577 2578 2579
                         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 已提交
2580 2581 2582 2583
      start_key_specified_(false),
      end_key_specified_(false),
      max_keys_scanned_(-1),
      no_value_(false) {
2584 2585
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_FROM);
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
  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;
  }

2602
  std::vector<std::string>::const_iterator vitr =
A
Alexander Fenster 已提交
2603
      std::find(flags.begin(), flags.end(), ARG_NO_VALUE);
2604 2605 2606 2607
  if (vitr != flags.end()) {
    no_value_ = true;
  }

2608 2609 2610
  itr = options.find(ARG_MAX_KEYS);
  if (itr != options.end()) {
    try {
S
sdong 已提交
2611 2612 2613
#if defined(CYGWIN)
      max_keys_scanned_ = strtol(itr->second.c_str(), 0, 10);
#else
2614
      max_keys_scanned_ = std::stoi(itr->second);
S
sdong 已提交
2615
#endif
2616
    } catch (const std::invalid_argument&) {
2617
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
2618
                                                    " has an invalid value");
2619
    } catch (const std::out_of_range&) {
2620 2621
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
2622 2623 2624 2625
    }
  }
}

2626
void ScanCommand::Help(std::string& ret) {
2627 2628 2629 2630 2631 2632 2633 2634
  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]");
2635
  ret.append(" [--" + ARG_NO_VALUE + "]");
2636
  ret.append("\n");
2637 2638 2639
}

void ScanCommand::DoCommand() {
S
sdong 已提交
2640 2641 2642 2643
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2644 2645

  int num_keys_scanned = 0;
2646 2647 2648
  ReadOptions scan_read_opts;
  scan_read_opts.total_order_seek = true;
  Iterator* it = db_->NewIterator(scan_read_opts, GetCfHandle());
2649 2650 2651 2652 2653
  if (start_key_specified_) {
    it->Seek(start_key_);
  } else {
    it->SeekToFirst();
  }
2654
  int ttl_start;
2655
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
2656
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
2657 2658
  }
  int ttl_end;
2659
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
2660
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
2661 2662 2663 2664 2665 2666 2667 2668
  }
  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",
2669 2670
            TimeToHumanString(ttl_start).c_str(),
            TimeToHumanString(ttl_end).c_str());
2671
  }
2672
  for ( ;
2673 2674
        it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
        it->Next()) {
2675
    if (is_db_ttl_) {
2676
      TtlIterator* it_ttl = static_cast_with_check<TtlIterator>(it);
Y
Yanqin Jin 已提交
2677
      int rawtime = it_ttl->ttl_timestamp();
2678
      if (rawtime < ttl_start || rawtime >= ttl_end) {
2679 2680 2681
        continue;
      }
      if (timestamp_) {
2682
        fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
2683 2684
      }
    }
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696

    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;
    }

2697
    if (no_value_) {
A
Alexander Fenster 已提交
2698 2699
      fprintf(stdout, "%.*s\n", static_cast<int>(key_slice.size()),
              key_slice.data());
2700
    } else {
A
Alexander Fenster 已提交
2701 2702 2703 2704 2705 2706 2707 2708 2709
      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());
2710 2711
    }

2712 2713 2714 2715 2716 2717
    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
2718
    exec_state_ = LDBCommandExecuteResult::Failed(it->status().ToString());
2719 2720 2721 2722
  }
  delete it;
}

2723
// ----------------------------------------------------------------------------
2724

2725 2726 2727 2728 2729
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})) {
2730
  if (params.size() != 1) {
2731
    exec_state_ = LDBCommandExecuteResult::Failed(
2732
        "KEY must be specified for the delete command");
2733 2734 2735 2736 2737 2738 2739 2740
  } else {
    key_ = params.at(0);
    if (is_key_hex_) {
      key_ = HexToString(key_);
    }
  }
}

2741
void DeleteCommand::Help(std::string& ret) {
2742 2743 2744
  ret.append("  ");
  ret.append(DeleteCommand::Name() + " <key>");
  ret.append("\n");
2745 2746 2747
}

void DeleteCommand::DoCommand() {
S
sdong 已提交
2748 2749 2750 2751 2752
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st = db_->Delete(WriteOptions(), GetCfHandle(), key_);
2753 2754 2755
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2756
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2757 2758 2759
  }
}

A
Andrew Kryczka 已提交
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
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());
  }
}

2799 2800 2801 2802 2803 2804
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})) {
2805
  if (params.size() != 2) {
2806
    exec_state_ = LDBCommandExecuteResult::Failed(
2807
        "<key> and <value> must be specified for the put command");
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
  } else {
    key_ = params.at(0);
    value_ = params.at(1);
  }

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

  if (is_value_hex_) {
    value_ = HexToString(value_);
  }
2820
  create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
2821 2822
}

2823
void PutCommand::Help(std::string& ret) {
2824 2825
  ret.append("  ");
  ret.append(PutCommand::Name());
2826 2827
  ret.append(" <key> <value>");
  ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
2828 2829
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2830 2831 2832
}

void PutCommand::DoCommand() {
S
sdong 已提交
2833 2834 2835 2836 2837
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st = db_->Put(WriteOptions(), GetCfHandle(), key_, value_);
2838 2839 2840
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2841
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2842 2843 2844
  }
}

2845 2846 2847
void PutCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
2848 2849
}

2850
// ----------------------------------------------------------------------------
2851 2852 2853 2854 2855 2856

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

2857
DBQuerierCommand::DBQuerierCommand(
A
Andrew Kryczka 已提交
2858
    const std::vector<std::string>& /*params*/,
2859 2860 2861 2862 2863
    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})) {
2864 2865 2866

}

2867
void DBQuerierCommand::Help(std::string& ret) {
2868 2869 2870 2871 2872
  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 "
2873
             "commands.");
2874
  ret.append("\n");
2875 2876 2877 2878
}

void DBQuerierCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
2879
    assert(GetExecuteState().IsFailed());
2880 2881
    return;
  }
2882

2883 2884
  ReadOptions read_options;
  WriteOptions write_options;
2885

2886 2887 2888 2889 2890 2891
  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;
2892 2893 2894
    size_t pos = 0;
    while (true) {
      size_t pos2 = line.find(' ', pos);
2895
      if (pos2 == std::string::npos) {
2896 2897 2898 2899 2900 2901 2902
        break;
      }
      tokens.push_back(line.substr(pos, pos2-pos));
      pos = pos2 + 1;
    }
    tokens.push_back(line.substr(pos));

2903
    const std::string& cmd = tokens[0];
2904 2905 2906 2907 2908 2909 2910 2911

    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 已提交
2912
      db_->Delete(write_options, GetCfHandle(), Slice(key));
2913 2914 2915 2916
      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 已提交
2917
      db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
2918 2919 2920 2921
      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 已提交
2922
      if (db_->Get(read_options, GetCfHandle(), Slice(key), &value).ok()) {
2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933
        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());
    }
  }
}

2934 2935
// ----------------------------------------------------------------------------

2936
CheckConsistencyCommand::CheckConsistencyCommand(
A
Andrew Kryczka 已提交
2937
    const std::vector<std::string>& /*params*/,
2938 2939
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
S
sdong 已提交
2940
    : LDBCommand(options, flags, true, BuildCmdLineOptions({})) {}
Y
Yiting Li 已提交
2941

2942
void CheckConsistencyCommand::Help(std::string& ret) {
2943 2944 2945
  ret.append("  ");
  ret.append(CheckConsistencyCommand::Name());
  ret.append("\n");
Y
Yiting Li 已提交
2946
}
2947

Y
Yiting Li 已提交
2948
void CheckConsistencyCommand::DoCommand() {
S
sdong 已提交
2949 2950 2951 2952
  options_.paranoid_checks = true;
  options_.num_levels = 64;
  OpenDB();
  if (exec_state_.IsSucceed() || exec_state_.IsNotStarted()) {
Y
Yiting Li 已提交
2953 2954
    fprintf(stdout, "OK\n");
  }
S
sdong 已提交
2955
  CloseDB();
2956
}
Y
Yiting Li 已提交
2957

2958
// ----------------------------------------------------------------------------
A
Andrew Kryczka 已提交
2959

A
Aaron Gao 已提交
2960 2961 2962
const std::string CheckPointCommand::ARG_CHECKPOINT_DIR = "checkpoint_dir";

CheckPointCommand::CheckPointCommand(
A
Andrew Kryczka 已提交
2963
    const std::vector<std::string>& /*params*/,
A
Aaron Gao 已提交
2964 2965 2966 2967 2968
    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);
2969
  if (itr != options.end()) {
A
Aaron Gao 已提交
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989
    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()) {
2990
    fprintf(stdout, "OK\n");
A
Aaron Gao 已提交
2991 2992 2993 2994 2995 2996 2997
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

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

A
Andrew Kryczka 已提交
2998
RepairCommand::RepairCommand(const std::vector<std::string>& /*params*/,
2999 3000
                             const std::map<std::string, std::string>& options,
                             const std::vector<std::string>& flags)
A
Andrew Kryczka 已提交
3001 3002
    : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}

3003
void RepairCommand::Help(std::string& ret) {
A
Andrew Kryczka 已提交
3004 3005 3006 3007 3008
  ret.append("  ");
  ret.append(RepairCommand::Name());
  ret.append("\n");
}

3009 3010 3011 3012 3013
void RepairCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.info_log.reset(new StderrLogger(InfoLogLevel::WARN_LEVEL));
}

A
Andrew Kryczka 已提交
3014
void RepairCommand::DoCommand() {
3015 3016
  PrepareOptions();
  Status status = RepairDB(db_path_, options_);
A
Andrew Kryczka 已提交
3017
  if (status.ok()) {
3018
    fprintf(stdout, "OK\n");
A
Andrew Kryczka 已提交
3019 3020 3021 3022 3023 3024
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

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

3026 3027 3028 3029
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 已提交
3030

3031
BackupableCommand::BackupableCommand(
A
Andrew Kryczka 已提交
3032
    const std::vector<std::string>& /*params*/,
3033 3034 3035 3036 3037 3038 3039
    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 已提交
3040
  if (itr != options.end()) {
3041
    num_threads_ = std::stoi(itr->second);
W
Wanning Jiang 已提交
3042
  }
3043
  itr = options.find(ARG_BACKUP_ENV_URI);
A
Andrew Kryczka 已提交
3044
  if (itr != options.end()) {
3045
    backup_env_uri_ = itr->second;
W
Wanning Jiang 已提交
3046 3047 3048 3049 3050 3051
  }
  itr = options.find(ARG_BACKUP_DIR);
  if (itr == options.end()) {
    exec_state_ = LDBCommandExecuteResult::Failed("--" + ARG_BACKUP_DIR +
                                                  ": missing backup directory");
  } else {
3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066
    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 已提交
3067 3068 3069
  }
}

3070
void BackupableCommand::Help(const std::string& name, std::string& ret) {
W
Wanning Jiang 已提交
3071
  ret.append("  ");
3072 3073
  ret.append(name);
  ret.append(" [--" + ARG_BACKUP_ENV_URI + "] ");
W
Wanning Jiang 已提交
3074
  ret.append(" [--" + ARG_BACKUP_DIR + "] ");
3075 3076
  ret.append(" [--" + ARG_NUM_THREADS + "] ");
  ret.append(" [--" + ARG_STDERR_LOG_LEVEL + "=<int (InfoLogLevel)>] ");
W
Wanning Jiang 已提交
3077 3078 3079
  ret.append("\n");
}

3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
// ----------------------------------------------------------------------------

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 已提交
3091 3092 3093 3094 3095 3096 3097
void BackupCommand::DoCommand() {
  BackupEngine* backup_engine;
  Status status;
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
3098
  fprintf(stdout, "open db OK\n");
3099
  Env* custom_env = nullptr;
3100 3101
  Env::LoadEnv(backup_env_uri_, &custom_env, &backup_env_guard_);
  assert(custom_env != nullptr);
3102

W
Wanning Jiang 已提交
3103
  BackupableDBOptions backup_options =
3104 3105 3106
      BackupableDBOptions(backup_dir_, custom_env);
  backup_options.info_log = logger_.get();
  backup_options.max_background_operations = num_threads_;
3107
  status = BackupEngine::Open(custom_env, backup_options, &backup_engine);
W
Wanning Jiang 已提交
3108
  if (status.ok()) {
3109
    fprintf(stdout, "open backup engine OK\n");
W
Wanning Jiang 已提交
3110 3111 3112 3113 3114 3115
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
    return;
  }
  status = backup_engine->CreateNewBackup(db_);
  if (status.ok()) {
3116
    fprintf(stdout, "create new backup OK\n");
W
Wanning Jiang 已提交
3117 3118 3119 3120 3121 3122 3123
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
    return;
  }
}

// ----------------------------------------------------------------------------
A
Andrew Kryczka 已提交
3124 3125 3126 3127 3128

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

void RestoreCommand::Help(std::string& ret) {
3132
  BackupableCommand::Help(Name(), ret);
A
Andrew Kryczka 已提交
3133 3134 3135
}

void RestoreCommand::DoCommand() {
3136
  Env* custom_env = nullptr;
3137 3138
  Env::LoadEnv(backup_env_uri_, &custom_env, &backup_env_guard_);
  assert(custom_env != nullptr);
3139

A
Andrew Kryczka 已提交
3140 3141 3142 3143
  std::unique_ptr<BackupEngineReadOnly> restore_engine;
  Status status;
  {
    BackupableDBOptions opts(backup_dir_, custom_env);
3144
    opts.info_log = logger_.get();
A
Andrew Kryczka 已提交
3145 3146
    opts.max_background_operations = num_threads_;
    BackupEngineReadOnly* raw_restore_engine_ptr;
3147 3148
    status =
        BackupEngineReadOnly::Open(custom_env, opts, &raw_restore_engine_ptr);
A
Andrew Kryczka 已提交
3149 3150 3151 3152 3153
    if (status.ok()) {
      restore_engine.reset(raw_restore_engine_ptr);
    }
  }
  if (status.ok()) {
3154
    fprintf(stdout, "open restore engine OK\n");
A
Andrew Kryczka 已提交
3155 3156 3157
    status = restore_engine->RestoreDBFromLatestBackup(db_path_, db_path_);
  }
  if (status.ok()) {
3158
    fprintf(stdout, "restore from backup OK\n");
A
Andrew Kryczka 已提交
3159 3160 3161 3162 3163 3164
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

// ----------------------------------------------------------------------------
3165 3166 3167

namespace {

3168 3169
void DumpSstFile(Options options, std::string filename, bool output_hex,
                 bool show_properties) {
3170 3171 3172 3173 3174 3175 3176 3177
  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
3178
  // TODO: add support for decoding blob indexes in ldb as well
3179
  ROCKSDB_NAMESPACE::SstFileDumper dumper(
3180 3181
      options, filename, 2 * 1024 * 1024 /* readahead_size */,
      /* verify_checksum */ false, output_hex,
3182
      /* decode_blob_index */ false);
3183 3184
  Status st = dumper.ReadSequential(true, std::numeric_limits<uint64_t>::max(),
                                    false,            // has_from
3185 3186 3187 3188 3189 3190 3191 3192 3193
                                    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) {
3194
    const ROCKSDB_NAMESPACE::TableProperties* table_properties;
3195

3196
    std::shared_ptr<const ROCKSDB_NAMESPACE::TableProperties>
3197
        table_properties_from_reader;
3198
    st = dumper.ReadTableProperties(&table_properties_from_reader);
3199 3200 3201
    if (!st.ok()) {
      std::cerr << filename << ": " << st.ToString()
                << ". Try to use initial table properties" << std::endl;
3202
      table_properties = dumper.GetInitTableProperties();
3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
    } 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;
    }
  }
}

}  // namespace

3215
DBFileDumperCommand::DBFileDumperCommand(
A
Andrew Kryczka 已提交
3216
    const std::vector<std::string>& /*params*/,
3217 3218
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
3219 3220
    : LDBCommand(options, flags, true, BuildCmdLineOptions({})) {}

3221
void DBFileDumperCommand::Help(std::string& ret) {
3222 3223 3224 3225 3226 3227 3228
  ret.append("  ");
  ret.append(DBFileDumperCommand::Name());
  ret.append("\n");
}

void DBFileDumperCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
3229
    assert(GetExecuteState().IsFailed());
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
    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);
3246
  std::string manifest_filepath = db_->GetName() + "/" + manifest_filename;
3247
  std::cout << manifest_filepath << std::endl;
3248
  DumpManifestFile(options_, manifest_filepath, false, false, false);
3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
  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;
3259
    DumpSstFile(options_, filename, false, true);
3260 3261 3262 3263 3264 3265
    std::cout << std::endl;
  }
  std::cout << std::endl;

  std::cout << "Write Ahead Log Files" << std::endl;
  std::cout << "==============================" << std::endl;
3266
  ROCKSDB_NAMESPACE::VectorLogPtr wal_files;
3267 3268 3269 3270 3271 3272 3273 3274
  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;
3275
      // TODO(myabandeh): allow configuring is_write_commited
3276
      DumpWalFile(options_, filename, true, true, true /* is_write_commited */,
3277
                  &exec_state_);
3278 3279 3280 3281
    }
  }
}

Y
Yanqin Jin 已提交
3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
void WriteExternalSstFilesCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(WriteExternalSstFilesCommand::Name());
  ret.append(" <output_sst_path>");
  ret.append("\n");
}

WriteExternalSstFilesCommand::WriteExternalSstFilesCommand(
    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_HEX, ARG_KEY_HEX, ARG_VALUE_HEX, ARG_FROM,
                               ARG_TO, ARG_CREATE_IF_MISSING})) {
  create_if_missing_ =
      IsFlagPresent(flags, ARG_CREATE_IF_MISSING) ||
      ParseBooleanOption(options, ARG_CREATE_IF_MISSING, false);
  if (params.size() != 1) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "output SST file path must be specified");
  } else {
    output_sst_path_ = params.at(0);
  }
}

void WriteExternalSstFilesCommand::DoCommand() {
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  ColumnFamilyHandle* cfh = GetCfHandle();
  SstFileWriter sst_file_writer(EnvOptions(), db_->GetOptions(), cfh);
  Status status = sst_file_writer.Open(output_sst_path_);
  if (!status.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed("failed to open SST file: " +
                                                  status.ToString());
    return;
  }

  int bad_lines = 0;
  std::string line;
  std::ifstream ifs_stdin("/dev/stdin");
  std::istream* istream_p = ifs_stdin.is_open() ? &ifs_stdin : &std::cin;
  while (getline(*istream_p, line, '\n')) {
    std::string key;
    std::string value;
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
      status = sst_file_writer.Put(key, value);
      if (!status.ok()) {
        exec_state_ = LDBCommandExecuteResult::Failed(
            "failed to write record to file: " + status.ToString());
        return;
      }
    } 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++;
    }
  }

  status = sst_file_writer.Finish();
  if (!status.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "Failed to finish writing to file: " + status.ToString());
    return;
  }

  if (bad_lines > 0) {
    fprintf(stderr, "Warning: %d bad lines ignored.\n", bad_lines);
  }
  exec_state_ = LDBCommandExecuteResult::Succeed(
      "external SST file written to " + output_sst_path_);
}

3359 3360 3361
void WriteExternalSstFilesCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
Y
Yanqin Jin 已提交
3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
}

const std::string IngestExternalSstFilesCommand::ARG_MOVE_FILES = "move_files";
const std::string IngestExternalSstFilesCommand::ARG_SNAPSHOT_CONSISTENCY =
    "snapshot_consistency";
const std::string IngestExternalSstFilesCommand::ARG_ALLOW_GLOBAL_SEQNO =
    "allow_global_seqno";
const std::string IngestExternalSstFilesCommand::ARG_ALLOW_BLOCKING_FLUSH =
    "allow_blocking_flush";
const std::string IngestExternalSstFilesCommand::ARG_INGEST_BEHIND =
    "ingest_behind";
const std::string IngestExternalSstFilesCommand::ARG_WRITE_GLOBAL_SEQNO =
    "write_global_seqno";

void IngestExternalSstFilesCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(IngestExternalSstFilesCommand::Name());
  ret.append(" <input_sst_path>");
  ret.append(" [--" + ARG_MOVE_FILES + "] ");
  ret.append(" [--" + ARG_SNAPSHOT_CONSISTENCY + "] ");
  ret.append(" [--" + ARG_ALLOW_GLOBAL_SEQNO + "] ");
  ret.append(" [--" + ARG_ALLOW_BLOCKING_FLUSH + "] ");
  ret.append(" [--" + ARG_INGEST_BEHIND + "] ");
  ret.append(" [--" + ARG_WRITE_GLOBAL_SEQNO + "] ");
  ret.append("\n");
}

IngestExternalSstFilesCommand::IngestExternalSstFilesCommand(
    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_MOVE_FILES, ARG_SNAPSHOT_CONSISTENCY,
                               ARG_ALLOW_GLOBAL_SEQNO, ARG_CREATE_IF_MISSING,
                               ARG_ALLOW_BLOCKING_FLUSH, ARG_INGEST_BEHIND,
                               ARG_WRITE_GLOBAL_SEQNO})),
      move_files_(false),
      snapshot_consistency_(true),
      allow_global_seqno_(true),
      allow_blocking_flush_(true),
      ingest_behind_(false),
      write_global_seqno_(true) {
  create_if_missing_ =
      IsFlagPresent(flags, ARG_CREATE_IF_MISSING) ||
      ParseBooleanOption(options, ARG_CREATE_IF_MISSING, false);
  move_files_ = IsFlagPresent(flags, ARG_MOVE_FILES) ||
                ParseBooleanOption(options, ARG_MOVE_FILES, false);
  snapshot_consistency_ =
      IsFlagPresent(flags, ARG_SNAPSHOT_CONSISTENCY) ||
      ParseBooleanOption(options, ARG_SNAPSHOT_CONSISTENCY, true);
  allow_global_seqno_ =
      IsFlagPresent(flags, ARG_ALLOW_GLOBAL_SEQNO) ||
      ParseBooleanOption(options, ARG_ALLOW_GLOBAL_SEQNO, true);
  allow_blocking_flush_ =
      IsFlagPresent(flags, ARG_ALLOW_BLOCKING_FLUSH) ||
      ParseBooleanOption(options, ARG_ALLOW_BLOCKING_FLUSH, true);
  ingest_behind_ = IsFlagPresent(flags, ARG_INGEST_BEHIND) ||
                   ParseBooleanOption(options, ARG_INGEST_BEHIND, false);
  write_global_seqno_ =
      IsFlagPresent(flags, ARG_WRITE_GLOBAL_SEQNO) ||
      ParseBooleanOption(options, ARG_WRITE_GLOBAL_SEQNO, true);

  if (allow_global_seqno_) {
    if (!write_global_seqno_) {
      fprintf(stderr,
              "Warning: not writing global_seqno to the ingested SST can\n"
              "prevent older versions of RocksDB from being able to open it\n");
    }
  } else {
    if (write_global_seqno_) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "ldb cannot write global_seqno to the ingested SST when global_seqno "
          "is not allowed");
    }
  }

  if (params.size() != 1) {
    exec_state_ =
        LDBCommandExecuteResult::Failed("input SST path must be specified");
  } else {
    input_sst_path_ = params.at(0);
  }
}

void IngestExternalSstFilesCommand::DoCommand() {
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  if (GetExecuteState().IsFailed()) {
    return;
  }
  ColumnFamilyHandle* cfh = GetCfHandle();
  IngestExternalFileOptions ifo;
  ifo.move_files = move_files_;
  ifo.snapshot_consistency = snapshot_consistency_;
  ifo.allow_global_seqno = allow_global_seqno_;
  ifo.allow_blocking_flush = allow_blocking_flush_;
  ifo.ingest_behind = ingest_behind_;
  ifo.write_global_seqno = write_global_seqno_;
  Status status = db_->IngestExternalFile(cfh, {input_sst_path_}, ifo);
  if (!status.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "failed to ingest external SST: " + status.ToString());
  } else {
    exec_state_ =
        LDBCommandExecuteResult::Succeed("external SST files ingested");
  }
}

3473 3474 3475
void IngestExternalSstFilesCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
Y
Yanqin Jin 已提交
3476 3477
}

3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513
ListFileRangeDeletesCommand::ListFileRangeDeletesCommand(
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, true, BuildCmdLineOptions({ARG_MAX_KEYS})) {
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_MAX_KEYS);
  if (itr != options.end()) {
    try {
#if defined(CYGWIN)
      max_keys_ = strtol(itr->second.c_str(), 0, 10);
#else
      max_keys_ = std::stoi(itr->second);
#endif
    } catch (const std::invalid_argument&) {
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
                                                    " has an invalid value");
    } catch (const std::out_of_range&) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
    }
  }
}

void ListFileRangeDeletesCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(ListFileRangeDeletesCommand::Name());
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  ret.append(" : print tombstones in SST files.\n");
}

void ListFileRangeDeletesCommand::DoCommand() {
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }

3514
  DBImpl* db_impl = static_cast_with_check<DBImpl>(db_->GetRootDB());
3515 3516 3517 3518 3519 3520 3521 3522 3523

  std::string out_str;

  Status st =
      db_impl->TablesRangeTombstoneSummary(GetCfHandle(), max_keys_, &out_str);
  if (st.ok()) {
    TEST_SYNC_POINT_CALLBACK(
        "ListFileRangeDeletesCommand::DoCommand:BeforePrint", &out_str);
    fprintf(stdout, "%s\n", out_str.c_str());
3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
  }
}

void UnsafeRemoveSstFileCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(UnsafeRemoveSstFileCommand::Name());
  ret.append(" <SST file number>");
  ret.append("\n");
  ret.append("    MUST NOT be used on a live DB.");
  ret.append("\n");
}

UnsafeRemoveSstFileCommand::UnsafeRemoveSstFileCommand(
    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({})) {
  if (params.size() != 1) {
    exec_state_ =
        LDBCommandExecuteResult::Failed("SST file number must be specified");
3545
  } else {
3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
    char* endptr = nullptr;
    sst_file_number_ = strtoull(params.at(0).c_str(), &endptr, 10 /* base */);
    if (endptr == nullptr || *endptr != '\0') {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Failed to parse SST file number " + params.at(0));
    }
  }
}

void UnsafeRemoveSstFileCommand::DoCommand() {
  // Instead of opening a `DB` and calling `DeleteFile()`, this implementation
  // uses the underlying `VersionSet` API to read and modify the MANIFEST. This
  // allows us to use the user's real options, while not having to worry about
  // the DB persisting new SST files via flush/compaction or attempting to read/
  // compact files which may fail, particularly for the file we intend to remove
  // (the user may want to remove an already deleted file from MANIFEST).
  PrepareOptions();

  if (options_.db_paths.empty()) {
    // `VersionSet` expects options that have been through `SanitizeOptions()`,
    // which would sanitize an empty `db_paths`.
    options_.db_paths.emplace_back(db_path_, 0 /* target_size */);
  }

  WriteController wc(options_.delayed_write_rate);
  WriteBufferManager wb(options_.db_write_buffer_size);
  ImmutableDBOptions immutable_db_options(options_);
  std::shared_ptr<Cache> tc(
      NewLRUCache(1 << 20 /* capacity */, options_.table_cache_numshardbits));
  EnvOptions sopt;
  VersionSet versions(db_path_, &immutable_db_options, sopt, tc.get(), &wb, &wc,
                      /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr);
  Status s = versions.Recover(column_families_);

  ColumnFamilyData* cfd = nullptr;
  int level = -1;
  if (s.ok()) {
    FileMetaData* metadata = nullptr;
    s = versions.GetMetadataForFile(sst_file_number_, &level, &metadata, &cfd);
  }

  if (s.ok()) {
    VersionEdit edit;
    edit.SetColumnFamily(cfd->GetID());
    edit.DeleteFile(level, sst_file_number_);
    // Use `mutex` to imitate a locked DB mutex when calling `LogAndApply()`.
    InstrumentedMutex mutex;
    mutex.Lock();
    s = versions.LogAndApply(cfd, *cfd->GetLatestMutableCFOptions(), &edit,
                             &mutex, nullptr /* db_directory */,
                             false /* new_descriptor_log */);
    mutex.Unlock();
  }

  if (!s.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "failed to unsafely remove SST file: " + s.ToString());
  } else {
    exec_state_ = LDBCommandExecuteResult::Succeed("unsafely removed SST file");
3605 3606 3607
  }
}

3608
}  // namespace ROCKSDB_NAMESPACE
I
Igor Canadi 已提交
3609
#endif  // ROCKSDB_LITE