ldb_cmd.cc 114.7 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
#include "db/db_impl/db_impl.h"
A
Andrew Kryczka 已提交
13 14
#include "db/dbformat.h"
#include "db/log_reader.h"
A
Abhishek Kona 已提交
15
#include "db/write_batch_internal.h"
16
#include "env/composite_env_wrapper.h"
17
#include "file/filename.h"
18
#include "port/port_dirent.h"
I
Igor Canadi 已提交
19
#include "rocksdb/cache.h"
20
#include "rocksdb/file_checksum.h"
21
#include "rocksdb/table_properties.h"
W
Wanning Jiang 已提交
22
#include "rocksdb/utilities/backupable_db.h"
A
Aaron Gao 已提交
23
#include "rocksdb/utilities/checkpoint.h"
A
Andrew Kryczka 已提交
24
#include "rocksdb/utilities/debug.h"
25
#include "rocksdb/utilities/options_util.h"
A
Andrew Kryczka 已提交
26
#include "rocksdb/write_batch.h"
27
#include "rocksdb/write_buffer_manager.h"
S
sdong 已提交
28
#include "table/scoped_arena_iterator.h"
A
Arun Sharma 已提交
29
#include "tools/ldb_cmd_impl.h"
30
#include "tools/sst_dump_tool_imp.h"
S
Siying Dong 已提交
31
#include "util/cast_util.h"
32
#include "util/coding.h"
33
#include "util/file_checksum_helper.h"
A
Andrew Kryczka 已提交
34
#include "util/stderr_logger.h"
S
sdong 已提交
35
#include "util/string_util.h"
36
#include "utilities/merge_operators.h"
37
#include "utilities/ttl/db_ttl_impl.h"
38

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

49
namespace ROCKSDB_NAMESPACE {
50

51 52
class FileChecksumGenCrc32c;
class FileChecksumGenCrc32cFactory;
53

54
const std::string LDBCommand::ARG_ENV_URI = "env_uri";
55 56
const std::string LDBCommand::ARG_DB = "db";
const std::string LDBCommand::ARG_PATH = "path";
57
const std::string LDBCommand::ARG_SECONDARY_PATH = "secondary_path";
58 59 60 61 62 63 64 65
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";
66
const std::string LDBCommand::ARG_TRY_LOAD_OPTIONS = "try_load_options";
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(
S
sdong 已提交
98 99 100
    int argc, char** argv, const Options& options,
    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 234 235 236 237
  } 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);
238 239
  } else if (parsed_params.cmd == DropColumnFamilyCommand::Name()) {
    return new DropColumnFamilyCommand(parsed_params.cmd_params,
240 241
                                       parsed_params.option_map,
                                       parsed_params.flags);
242 243 244 245 246 247 248 249 250 251 252 253
  } 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 已提交
254 255 256 257
  } else if (parsed_params.cmd == CheckPointCommand::Name()) {
    return new CheckPointCommand(parsed_params.cmd_params,
                                 parsed_params.option_map,
                                 parsed_params.flags);
258 259 260
  } else if (parsed_params.cmd == RepairCommand::Name()) {
    return new RepairCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
W
Wanning Jiang 已提交
261 262 263
  } else if (parsed_params.cmd == BackupCommand::Name()) {
    return new BackupCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
A
Andrew Kryczka 已提交
264 265 266
  } else if (parsed_params.cmd == RestoreCommand::Name()) {
    return new RestoreCommand(parsed_params.cmd_params,
                              parsed_params.option_map, parsed_params.flags);
Y
Yanqin Jin 已提交
267 268 269 270 271 272 273 274
  } 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);
275 276 277
  } else if (parsed_params.cmd == ListFileRangeDeletesCommand::Name()) {
    return new ListFileRangeDeletesCommand(parsed_params.option_map,
                                           parsed_params.flags);
278
  }
279
  return nullptr;
280 281
}

A
Arun Sharma 已提交
282 283 284 285 286 287
/* Run the command, and return the execute result. */
void LDBCommand::Run() {
  if (!exec_state_.IsNotStarted()) {
    return;
  }

288 289 290 291 292 293 294 295 296 297 298
  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 已提交
299 300
  if (db_ == nullptr && !NoDBOpen()) {
    OpenDB();
301 302 303 304 305 306
    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 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
  }

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

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

343 344 345 346 347
  itr = options.find(ARG_ENV_URI);
  if (itr != options.end()) {
    env_uri_ = itr->second;
  }

A
Arun Sharma 已提交
348 349 350 351 352 353 354
  itr = options.find(ARG_CF_NAME);
  if (itr != options.end()) {
    column_family_name_ = itr->second;
  } else {
    column_family_name_ = kDefaultColumnFamilyName;
  }

355 356 357 358 359 360
  itr = options.find(ARG_SECONDARY_PATH);
  secondary_path_ = "";
  if (itr != options.end()) {
    secondary_path_ = itr->second;
  }

A
Arun Sharma 已提交
361 362 363 364
  is_key_hex_ = IsKeyHex(options, flags);
  is_value_hex_ = IsValueHex(options, flags);
  is_db_ttl_ = IsFlagPresent(flags, ARG_TTL);
  timestamp_ = IsFlagPresent(flags, ARG_TIMESTAMP);
365
  try_load_options_ = IsFlagPresent(flags, ARG_TRY_LOAD_OPTIONS);
366
  ignore_unknown_options_ = IsFlagPresent(flags, ARG_IGNORE_UNKNOWN_OPTIONS);
A
Arun Sharma 已提交
367 368 369
}

void LDBCommand::OpenDB() {
370
  if (!create_if_missing_ && try_load_options_) {
371
    Status s = LoadLatestOptions(db_path_, options_.env, &options_,
372
                                 &column_families_, ignore_unknown_options_);
373
    if (!s.ok() && !s.IsNotFound()) {
374 375 376 377 378 379
      // Option file exists but load option file error.
      std::string msg = s.ToString();
      exec_state_ = LDBCommandExecuteResult::Failed(msg);
      db_ = nullptr;
      return;
    }
380 381 382 383 384 385
    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");
    }
386 387 388 389 390 391 392 393 394

    // If merge operator is not set, set a string append operator. There is
    // no harm doing it.
    for (auto& cf_entry : column_families_) {
      if (!cf_entry.options.merge_operator) {
        cf_entry.options.merge_operator =
            MergeOperators::CreateStringAppendOperator(':');
      }
    }
395
  }
A
Andrew Kryczka 已提交
396
  options_ = PrepareOptionsForOpenDB();
A
Arun Sharma 已提交
397 398 399
  if (!exec_state_.IsNotStarted()) {
    return;
  }
400 401 402 403
  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 已提交
404 405 406 407 408 409 410 411 412
  // 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");
    }
413 414 415 416
    if (!secondary_path_.empty()) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Open as secondary is not supported for TTL DB yet.");
    }
A
Arun Sharma 已提交
417
    if (is_read_only_) {
A
Andrew Kryczka 已提交
418
      st = DBWithTTL::Open(options_, db_path_, &db_ttl_, 0, true);
A
Arun Sharma 已提交
419
    } else {
A
Andrew Kryczka 已提交
420
      st = DBWithTTL::Open(options_, db_path_, &db_ttl_);
A
Arun Sharma 已提交
421 422 423
    }
    db_ = db_ttl_;
  } else {
A
Andrew Kryczka 已提交
424
    if (column_families_.empty()) {
A
Arun Sharma 已提交
425 426
      // Try to figure out column family lists
      std::vector<std::string> cf_list;
427
      st = DB::ListColumnFamilies(options_, db_path_, &cf_list);
A
Arun Sharma 已提交
428 429 430 431 432 433 434
      // There is possible the DB doesn't exist yet, for "create if not
      // "existing case". The failure is ignored here. We rely on DB::Open()
      // to give us the correct error message for problem with opening
      // existing DB.
      if (st.ok() && cf_list.size() > 1) {
        // Ignore single column family DB.
        for (auto cf_name : cf_list) {
A
Andrew Kryczka 已提交
435
          column_families_.emplace_back(cf_name, options_);
A
Arun Sharma 已提交
436 437 438
        }
      }
    }
439
    if (is_read_only_ && secondary_path_.empty()) {
A
Arun Sharma 已提交
440
      if (column_families_.empty()) {
A
Andrew Kryczka 已提交
441
        st = DB::OpenForReadOnly(options_, db_path_, &db_);
A
Arun Sharma 已提交
442
      } else {
A
Andrew Kryczka 已提交
443
        st = DB::OpenForReadOnly(options_, db_path_, column_families_,
A
Arun Sharma 已提交
444 445 446 447
                                 &handles_opened, &db_);
      }
    } else {
      if (column_families_.empty()) {
448 449 450 451 452
        if (secondary_path_.empty()) {
          st = DB::Open(options_, db_path_, &db_);
        } else {
          st = DB::OpenAsSecondary(options_, db_path_, secondary_path_, &db_);
        }
A
Arun Sharma 已提交
453
      } else {
454 455 456 457 458 459 460
        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 已提交
461 462 463 464
      }
    }
  }
  if (!st.ok()) {
465
    std::string msg = st.ToString();
A
Arun Sharma 已提交
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    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();
}

515 516
std::vector<std::string> LDBCommand::BuildCmdLineOptions(
    std::vector<std::string> options) {
517 518
  std::vector<std::string> ret = {ARG_ENV_URI,
                                  ARG_DB,
519
                                  ARG_SECONDARY_PATH,
520 521 522 523 524 525 526 527
                                  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,
528
                                  ARG_TRY_LOAD_OPTIONS,
529
                                  ARG_IGNORE_UNKNOWN_OPTIONS,
530
                                  ARG_CF_NAME};
A
Arun Sharma 已提交
531 532 533
  ret.insert(ret.end(), options.begin(), options.end());
  return ret;
}
534

535 536 537 538 539 540 541
/**
 * 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.
 */
542
bool LDBCommand::ParseIntOption(
A
Andrew Kryczka 已提交
543
    const std::map<std::string, std::string>& /*options*/,
544 545 546 547
    const std::string& option, int& value,
    LDBCommandExecuteResult& exec_state) {
  std::map<std::string, std::string>::const_iterator itr =
      option_map_.find(option);
548
  if (itr != option_map_.end()) {
549
    try {
S
sdong 已提交
550 551 552
#if defined(CYGWIN)
      value = strtol(itr->second.c_str(), 0, 10);
#else
553
      value = std::stoi(itr->second);
S
sdong 已提交
554
#endif
555
      return true;
556
    } catch (const std::invalid_argument&) {
557 558
      exec_state =
          LDBCommandExecuteResult::Failed(option + " has an invalid value.");
559
    } catch (const std::out_of_range&) {
560 561
      exec_state = LDBCommandExecuteResult::Failed(
          option + " has a value out-of-range.");
562 563
    }
  }
564
  return false;
565 566
}

567 568 569 570 571
/**
 * Parses the specified option and fills in the value.
 * Returns true if the option is found.
 * Returns false otherwise.
 */
572
bool LDBCommand::ParseStringOption(
A
Andrew Kryczka 已提交
573
    const std::map<std::string, std::string>& /*options*/,
574
    const std::string& option, std::string* value) {
575 576 577 578 579 580 581 582
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
    *value = itr->second;
    return true;
  }
  return false;
}

583
Options LDBCommand::PrepareOptionsForOpenDB() {
A
Andrew Kryczka 已提交
584 585 586 587 588 589 590 591 592 593 594 595 596
  ColumnFamilyOptions* cf_opts;
  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()) {
    cf_opts = &column_families_iter->options;
  } else {
    cf_opts = static_cast<ColumnFamilyOptions*>(&options_);
  }
  DBOptions* db_opts = static_cast<DBOptions*>(&options_);
  db_opts->create_if_missing = false;
597

598
  std::map<std::string, std::string>::const_iterator itr;
599

600
  BlockBasedTableOptions table_options;
S
sdong 已提交
601
  bool use_table_options = false;
602
  int bits;
603
  if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
604
    if (bits > 0) {
S
sdong 已提交
605
      use_table_options = true;
606
      table_options.filter_policy.reset(NewBloomFilterPolicy(bits));
607
    } else {
608 609
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOOM_BITS + " must be > 0.");
610 611 612 613
    }
  }

  int block_size;
614
  if (ParseIntOption(option_map_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
615
    if (block_size > 0) {
S
sdong 已提交
616
      use_table_options = true;
617
      table_options.block_size = block_size;
618
    } else {
619 620
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOCK_SIZE + " must be > 0.");
621 622 623
    }
  }

S
sdong 已提交
624
  if (use_table_options) {
A
Andrew Kryczka 已提交
625
    cf_opts->table_factory.reset(NewBlockBasedTableFactory(table_options));
S
sdong 已提交
626 627
  }

628 629
  itr = option_map_.find(ARG_AUTO_COMPACTION);
  if (itr != option_map_.end()) {
A
Andrew Kryczka 已提交
630
    cf_opts->disable_auto_compactions = !StringToBool(itr->second);
631 632
  }

633 634
  itr = option_map_.find(ARG_COMPRESSION_TYPE);
  if (itr != option_map_.end()) {
635
    std::string comp = itr->second;
636
    if (comp == "no") {
A
Andrew Kryczka 已提交
637
      cf_opts->compression = kNoCompression;
638
    } else if (comp == "snappy") {
A
Andrew Kryczka 已提交
639
      cf_opts->compression = kSnappyCompression;
640
    } else if (comp == "zlib") {
A
Andrew Kryczka 已提交
641
      cf_opts->compression = kZlibCompression;
642
    } else if (comp == "bzip2") {
A
Andrew Kryczka 已提交
643
      cf_opts->compression = kBZip2Compression;
A
Albert Strasheim 已提交
644
    } else if (comp == "lz4") {
A
Andrew Kryczka 已提交
645
      cf_opts->compression = kLZ4Compression;
A
Albert Strasheim 已提交
646
    } else if (comp == "lz4hc") {
A
Andrew Kryczka 已提交
647
      cf_opts->compression = kLZ4HCCompression;
648
    } else if (comp == "xpress") {
A
Andrew Kryczka 已提交
649
      cf_opts->compression = kXpressCompression;
650
    } else if (comp == "zstd") {
A
Andrew Kryczka 已提交
651
      cf_opts->compression = kZSTD;
652 653
    } else {
      // Unknown compression.
654 655
      exec_state_ =
          LDBCommandExecuteResult::Failed("Unknown compression level: " + comp);
656 657 658
    }
  }

659 660 661 662
  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) {
A
Andrew Kryczka 已提交
663
      cf_opts->compression_opts.max_dict_bytes = compression_max_dict_bytes;
664 665 666 667 668 669
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_COMPRESSION_MAX_DICT_BYTES + " must be >= 0.");
    }
  }

670 671 672 673
  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) {
A
Andrew Kryczka 已提交
674
      db_opts->db_write_buffer_size = db_write_buffer_size;
675
    } else {
676
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_DB_WRITE_BUFFER_SIZE +
677
                                                    " must be >= 0.");
678 679 680
    }
  }

681
  int write_buffer_size;
682 683
  if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
        exec_state_)) {
684
    if (write_buffer_size > 0) {
A
Andrew Kryczka 已提交
685
      cf_opts->write_buffer_size = write_buffer_size;
686
    } else {
687
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_WRITE_BUFFER_SIZE +
688
                                                    " must be > 0.");
689 690 691 692
    }
  }

  int file_size;
693
  if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
694
    if (file_size > 0) {
A
Andrew Kryczka 已提交
695
      cf_opts->target_file_size_base = file_size;
696
    } else {
697 698
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_FILE_SIZE + " must be > 0.");
699 700 701
    }
  }

A
Andrew Kryczka 已提交
702 703 704
  if (db_opts->db_paths.size() == 0) {
    db_opts->db_paths.emplace_back(db_path_,
                                   std::numeric_limits<uint64_t>::max());
705 706
  }

S
sdong 已提交
707
  int fix_prefix_len;
708 709
  if (ParseIntOption(option_map_, ARG_FIX_PREFIX_LEN, fix_prefix_len,
                     exec_state_)) {
S
sdong 已提交
710
    if (fix_prefix_len > 0) {
A
Andrew Kryczka 已提交
711
      cf_opts->prefix_extractor.reset(
S
sdong 已提交
712 713
          NewFixedPrefixTransform(static_cast<size_t>(fix_prefix_len)));
    } else {
714
      exec_state_ =
715
          LDBCommandExecuteResult::Failed(ARG_FIX_PREFIX_LEN + " must be > 0.");
S
sdong 已提交
716 717
    }
  }
718

A
Andrew Kryczka 已提交
719 720 721 722
  // TODO(ajkr): this return value doesn't reflect the CF options changed, so
  // subcommands that rely on this won't see the effect of CF-related CLI args.
  // Such subcommands need to be changed to properly support CFs.
  return options_;
723 724
}

725 726 727
bool LDBCommand::ParseKeyValue(const std::string& line, std::string* key,
                               std::string* value, bool is_key_hex,
                               bool is_value_hex) {
728
  size_t pos = line.find(DELIM);
729
  if (pos != std::string::npos) {
730 731 732 733 734 735 736 737 738 739 740 741 742
    *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;
  }
}
743

744 745 746 747 748 749 750 751
/**
 * 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() {
752 753 754 755 756 757
  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()) {
758 759 760 761
      fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
      return false;
    }
  }
762

763 764 765 766 767
  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()) {
768 769
      fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
      return false;
770 771 772
    }
  }

773 774 775 776
  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());
777 778 779 780 781 782
    return false;
  }

  return true;
}

783 784
std::string LDBCommand::HexToString(const std::string& str) {
  std::string result;
A
Arun Sharma 已提交
785 786 787 788 789 790 791 792 793 794 795
  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;
}

796 797
std::string LDBCommand::StringToHex(const std::string& str) {
  std::string result("0x");
A
Arun Sharma 已提交
798 799 800 801
  result.append(Slice(str).ToString(true));
  return result;
}

802 803 804 805
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 已提交
806 807 808 809 810 811
  result.append(is_key_hex ? StringToHex(key) : key);
  result.append(DELIM);
  result.append(is_value_hex ? StringToHex(value) : value);
  return result;
}

812 813
std::string LDBCommand::PrintKeyValue(const std::string& key,
                                      const std::string& value, bool is_hex) {
A
Arun Sharma 已提交
814 815 816
  return PrintKeyValue(key, value, is_hex, is_hex);
}

817
std::string LDBCommand::HelpRangeCmdArgs() {
A
Arun Sharma 已提交
818 819 820 821 822 823 824
  std::ostringstream str_stream;
  str_stream << " ";
  str_stream << "[--" << ARG_FROM << "] ";
  str_stream << "[--" << ARG_TO << "] ";
  return str_stream.str();
}

825 826
bool LDBCommand::IsKeyHex(const std::map<std::string, std::string>& options,
                          const std::vector<std::string>& flags) {
A
Arun Sharma 已提交
827 828 829 830 831
  return (IsFlagPresent(flags, ARG_HEX) || IsFlagPresent(flags, ARG_KEY_HEX) ||
          ParseBooleanOption(options, ARG_HEX, false) ||
          ParseBooleanOption(options, ARG_KEY_HEX, false));
}

832 833
bool LDBCommand::IsValueHex(const std::map<std::string, std::string>& options,
                            const std::vector<std::string>& flags) {
A
Arun Sharma 已提交
834 835 836 837 838 839
  return (IsFlagPresent(flags, ARG_HEX) ||
          IsFlagPresent(flags, ARG_VALUE_HEX) ||
          ParseBooleanOption(options, ARG_HEX, false) ||
          ParseBooleanOption(options, ARG_VALUE_HEX, false));
}

840 841 842 843
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 已提交
844
  if (itr != options.end()) {
845
    std::string option_val = itr->second;
A
Arun Sharma 已提交
846 847 848 849 850
    return StringToBool(itr->second);
  }
  return default_val;
}

851
bool LDBCommand::StringToBool(std::string val) {
A
Arun Sharma 已提交
852 853 854 855 856 857 858 859 860 861 862 863
  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";
  }
}

864
CompactorCommand::CompactorCommand(
A
Andrew Kryczka 已提交
865
    const std::vector<std::string>& /*params*/,
866 867 868 869 870 871 872 873 874
    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);
875 876 877 878 879 880 881 882 883 884 885 886
  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_) {
887 888 889 890 891 892 893 894 895
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

896
void CompactorCommand::Help(std::string& ret) {
897 898 899 900
  ret.append("  ");
  ret.append(CompactorCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
901 902
}

903
void CompactorCommand::DoCommand() {
S
sdong 已提交
904 905 906 907
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
908

909 910
  Slice* begin = nullptr;
  Slice* end = nullptr;
911
  if (!null_from_) {
912
    begin = new Slice(from_);
913 914
  }
  if (!null_to_) {
915
    end = new Slice(to_);
916 917
  }

918
  CompactRangeOptions cro;
919
  cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
920

921
  db_->CompactRange(cro, GetCfHandle(), begin, end);
922
  exec_state_ = LDBCommandExecuteResult::Succeed("");
923 924 925 926 927

  delete begin;
  delete end;
}

928
// ---------------------------------------------------------------------------
929 930 931
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";
932

933
DBLoaderCommand::DBLoaderCommand(
A
Andrew Kryczka 已提交
934
    const std::vector<std::string>& /*params*/,
935 936 937 938 939 940 941 942 943 944
    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) {
945 946
  create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
947 948
  bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  compact_ = IsFlagPresent(flags, ARG_COMPACT);
Z
Zheng Shao 已提交
949 950
}

951
void DBLoaderCommand::Help(std::string& ret) {
952 953 954 955 956 957 958
  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 已提交
959 960
}

961 962
Options DBLoaderCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
Z
Zheng Shao 已提交
963
  opt.create_if_missing = create_if_missing_;
964 965 966
  if (bulk_load_) {
    opt.PrepareForBulkLoad();
  }
Z
Zheng Shao 已提交
967 968 969
  return opt;
}

970
void DBLoaderCommand::DoCommand() {
Z
Zheng Shao 已提交
971
  if (!db_) {
S
sdong 已提交
972
    assert(GetExecuteState().IsFailed());
Z
Zheng Shao 已提交
973 974 975 976 977 978 979 980 981
    return;
  }

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

  int bad_lines = 0;
982
  std::string line;
983 984 985 986
  // 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')) {
987 988
    std::string key;
    std::string value;
989
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
S
sdong 已提交
990
      db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
Z
Zheng Shao 已提交
991 992 993 994 995 996 997 998
    } 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 ++;
    }
  }
999

Z
Zheng Shao 已提交
1000
  if (bad_lines > 0) {
1001
    std::cout << "Warning: " << bad_lines << " bad lines ignored." << std::endl;
Z
Zheng Shao 已提交
1002
  }
1003
  if (compact_) {
S
sdong 已提交
1004
    db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);
1005
  }
Z
Zheng Shao 已提交
1006 1007
}

1008 1009
// ----------------------------------------------------------------------------

1010 1011
namespace {

1012 1013
void DumpManifestFile(Options options, std::string file, bool verbose, bool hex,
                      bool json) {
1014 1015
  EnvOptions sopt;
  std::string dbname("dummy");
1016 1017
  std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
                                        options.table_cache_numshardbits));
1018 1019 1020 1021
  // 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);
1022
  options.num_levels = 64;
S
sdong 已提交
1023
  WriteController wc(options.delayed_write_rate);
1024
  WriteBufferManager wb(options.db_write_buffer_size);
1025
  ImmutableDBOptions immutable_db_options(options);
1026 1027
  VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc,
                      /*block_cache_tracer=*/nullptr);
1028
  Status s = versions.DumpManifest(options, file, verbose, hex, json);
1029
  if (!s.ok()) {
1030 1031
    fprintf(stderr, "Error in processing file %s %s\n", file.c_str(),
            s.ToString().c_str());
1032 1033 1034 1035 1036
  }
}

}  // namespace

1037 1038 1039
const std::string ManifestDumpCommand::ARG_VERBOSE = "verbose";
const std::string ManifestDumpCommand::ARG_JSON = "json";
const std::string ManifestDumpCommand::ARG_PATH = "path";
1040

1041
void ManifestDumpCommand::Help(std::string& ret) {
1042 1043 1044
  ret.append("  ");
  ret.append(ManifestDumpCommand::Name());
  ret.append(" [--" + ARG_VERBOSE + "]");
1045
  ret.append(" [--" + ARG_JSON + "]");
1046 1047
  ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  ret.append("\n");
1048 1049
}

1050
ManifestDumpCommand::ManifestDumpCommand(
A
Andrew Kryczka 已提交
1051
    const std::vector<std::string>& /*params*/,
1052 1053 1054 1055 1056 1057 1058 1059
    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_("") {
1060
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
1061
  json_ = IsFlagPresent(flags, ARG_JSON);
1062

1063 1064
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_PATH);
1065 1066 1067
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
1068
      exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    }
  }
}

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 已提交
1082

1083 1084 1085 1086 1087 1088 1089
    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);
1090 1091
      return;
    }
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    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;
      FileType file_type = kLogFile;  // Just for initialization
      if (ParseFileName(fname, &file_num, &file_type) &&
          file_type == kDescriptorFile) {
        if (!matched_file.empty()) {
1118
          exec_state_ = LDBCommandExecuteResult::Failed(
1119
              "Multiple MANIFEST files found; use --path to select one");
1120
          return;
1121 1122
        } else {
          matched_file.swap(fname);
1123 1124 1125
        }
      }
    }
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    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;
1136 1137 1138
  }

  if (verbose_) {
1139
    fprintf(stdout, "Processing Manifest file %s\n", manifestfile.c_str());
1140 1141
  }

1142
  DumpManifestFile(options_, manifestfile, verbose_, is_key_hex_, json_);
1143

1144
  if (verbose_) {
1145
    fprintf(stdout, "Processing Manifest file %s done\n", manifestfile.c_str());
1146 1147 1148
  }
}

1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
// ----------------------------------------------------------------------------
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,
                      /*block_cache_tracer=*/nullptr);
  std::vector<std::string> cf_name_list;
  s = versions.ListColumnFamilies(&cf_name_list, db_path,
1172
                                  immutable_db_options.fs.get());
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 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 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
  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)
    : LDBCommand(options, flags, false, BuildCmdLineOptions({ARG_PATH})),
      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");
    }
  }
}

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());
        fprintf(stdout, "%" PRId64 ", %s, %s\n", file_numbers[i],
                checksum_func_names[i].c_str(), checksums[i].c_str());
      }
    }
    fprintf(stdout, "Print SST file checksum information finished \n");
  }
}

1243
// ----------------------------------------------------------------------------
1244

1245
void ListColumnFamiliesCommand::Help(std::string& ret) {
1246 1247 1248
  ret.append("  ");
  ret.append(ListColumnFamiliesCommand::Name());
  ret.append("\n");
1249 1250 1251
}

ListColumnFamiliesCommand::ListColumnFamiliesCommand(
1252
    const std::vector<std::string>& /*params*/,
1253 1254
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1255
    : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}
1256 1257

void ListColumnFamiliesCommand::DoCommand() {
1258
  std::vector<std::string> column_families;
1259
  Status s = DB::ListColumnFamilies(options_, db_path_, &column_families);
1260
  if (!s.ok()) {
1261 1262
    fprintf(stderr, "Error in processing db %s %s\n", db_path_.c_str(),
            s.ToString().c_str());
1263
  } else {
1264
    fprintf(stdout, "Column families in %s: \n{", db_path_.c_str());
1265 1266 1267
    bool first = true;
    for (auto cf : column_families) {
      if (!first) {
1268
        fprintf(stdout, ", ");
1269 1270
      }
      first = false;
1271
      fprintf(stdout, "%s", cf.c_str());
1272
    }
1273
    fprintf(stdout, "}\n");
1274 1275 1276
  }
}

1277
void CreateColumnFamilyCommand::Help(std::string& ret) {
S
sdong 已提交
1278 1279 1280 1281 1282 1283 1284
  ret.append("  ");
  ret.append(CreateColumnFamilyCommand::Name());
  ret.append(" --db=<db_path> <new_column_family_name>");
  ret.append("\n");
}

CreateColumnFamilyCommand::CreateColumnFamilyCommand(
1285 1286 1287
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
S
sdong 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    : 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() {
1298
  ColumnFamilyHandle* new_cf_handle = nullptr;
S
sdong 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
  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();
}

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
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)
1321
    : LDBCommand(options, flags, true, {ARG_DB}) {
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
  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() {
  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();
}

1348
// ----------------------------------------------------------------------------
I
Igor Canadi 已提交
1349 1350
namespace {

1351 1352
// 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
1353 1354 1355
void IncBucketCounts(std::vector<uint64_t>& bucket_counts, int ttl_start,
                     int time_range, int bucket_size, int timekv,
                     int num_buckets) {
1356 1357 1358 1359
#ifdef NDEBUG
  (void)time_range;
  (void)num_buckets;
#endif
1360 1361 1362
  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;
1363
  bucket_counts[bucket]++;
1364 1365
}

1366 1367 1368
void PrintBucketCounts(const std::vector<uint64_t>& bucket_counts,
                       int ttl_start, int ttl_end, int bucket_size,
                       int num_buckets) {
1369
  int time_point = ttl_start;
1370 1371
  for(int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
    fprintf(stdout, "Keys in range %s to %s : %lu\n",
1372 1373
            TimeToHumanString(time_point).c_str(),
            TimeToHumanString(time_point + bucket_size).c_str(),
1374
            (unsigned long)bucket_counts[i]);
1375
  }
1376
  fprintf(stdout, "Keys in range %s to %s : %lu\n",
1377 1378
          TimeToHumanString(time_point).c_str(),
          TimeToHumanString(ttl_end).c_str(),
1379
          (unsigned long)bucket_counts[num_buckets - 1]);
1380 1381
}

I
Igor Canadi 已提交
1382 1383
}  // namespace

1384 1385 1386 1387
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";
1388

1389
InternalDumpCommand::InternalDumpCommand(
A
Andrew Kryczka 已提交
1390
    const std::vector<std::string>& /*params*/,
1391 1392
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
    : 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) {
1406 1407 1408
  has_from_ = ParseStringOption(options, ARG_FROM, &from_);
  has_to_ = ParseStringOption(options, ARG_TO, &to_);

1409
  ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
1410 1411
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_COUNT_DELIM);
1412 1413 1414
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
1415
   // fprintf(stdout,"delim = %c\n",delim_[0]);
1416 1417
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
1418
    delim_=".";
1419
  }
1420 1421 1422

  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
1423
  is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
1424

1425
  if (is_input_key_hex_) {
1426 1427 1428 1429 1430 1431 1432 1433 1434
    if (has_from_) {
      from_ = HexToString(from_);
    }
    if (has_to_) {
      to_ = HexToString(to_);
    }
  }
}

1435
void InternalDumpCommand::Help(std::string& ret) {
1436 1437 1438 1439 1440 1441 1442 1443 1444
  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");
1445 1446 1447 1448
}

void InternalDumpCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
1449
    assert(GetExecuteState().IsFailed());
1450 1451 1452 1453
    return;
  }

  if (print_stats_) {
1454
    std::string stats;
S
sdong 已提交
1455
    if (db_->GetProperty(GetCfHandle(), "rocksdb.stats", &stats)) {
1456 1457 1458 1459 1460
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Cast as DBImpl to get internal iterator
A
Andrew Kryczka 已提交
1461
  std::vector<KeyVersion> key_versions;
1462 1463
  Status st = GetAllKeyVersions(db_, GetCfHandle(), from_, to_, max_keys_,
                                &key_versions);
A
Andrew Kryczka 已提交
1464 1465
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1466 1467
    return;
  }
1468
  std::string rtype1, rtype2, row, val;
1469
  rtype2 = "";
1470 1471
  uint64_t c=0;
  uint64_t s1=0,s2=0;
1472

1473
  long long count = 0;
A
Andrew Kryczka 已提交
1474 1475 1476 1477 1478 1479
  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.
1480 1481 1482
      break;
    }
    ++count;
1483 1484 1485
    int k;
    if (count_delim_) {
      rtype1 = "";
1486
      s1=0;
A
Andrew Kryczka 已提交
1487 1488
      row = ikey.Encode().ToString();
      val = key_version.value;
1489
      for(k=0;row[k]!='\x01' && row[k]!='\0';k++)
1490
        s1++;
1491
      for(k=0;val[k]!='\x01' && val[k]!='\0';k++)
1492
        s1++;
1493 1494 1495
      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) {
1496 1497
        fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
                rtype2.c_str(), c, s2);
1498 1499
        c=1;
        s2=s1;
1500 1501 1502
        rtype2 = rtype1;
      } else {
        c++;
1503 1504
        s2+=s1;
        rtype2=rtype1;
A
Andrew Kryczka 已提交
1505
      }
1506
    }
1507

1508
    if (!count_only_ && !count_delim_) {
1509
      std::string key = ikey.DebugString(is_key_hex_);
A
Andrew Kryczka 已提交
1510
      std::string value = Slice(key_version.value).ToString(is_value_hex_);
1511
      std::cout << key << " => " << value << "\n";
1512 1513 1514
    }

    // Terminate if maximum number of keys have been dumped
1515
    if (max_keys_ > 0 && count >= max_keys_) break;
1516
  }
1517
  if(count_delim_) {
1518 1519 1520 1521 1522
    fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
            rtype2.c_str(), c, s2);
  } else {
    fprintf(stdout, "Internal keys in range: %lld\n", count);
  }
1523 1524
}

1525 1526 1527 1528
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";
1529

1530
DBDumperCommand::DBDumperCommand(
A
Andrew Kryczka 已提交
1531
    const std::vector<std::string>& /*params*/,
1532 1533
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    : 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) {
1546 1547
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_FROM);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
  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 已提交
1562 1563 1564
#if defined(CYGWIN)
      max_keys_ = strtol(itr->second.c_str(), 0, 10);
#else
1565
      max_keys_ = std::stoi(itr->second);
S
sdong 已提交
1566
#endif
1567
    } catch (const std::invalid_argument&) {
1568
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
1569
                                                    " has an invalid value");
1570
    } catch (const std::out_of_range&) {
1571 1572
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
1573 1574
    }
  }
1575 1576 1577 1578 1579 1580
  itr = options.find(ARG_COUNT_DELIM);
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
1581
    delim_=".";
1582
  }
1583

1584 1585 1586 1587
  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);

  if (is_key_hex_) {
1588 1589 1590 1591 1592 1593 1594
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
1595 1596 1597 1598

  itr = options.find(ARG_PATH);
  if (itr != options.end()) {
    path_ = itr->second;
1599 1600 1601
    if (db_path_.empty()) {
      db_path_ = path_;
    }
1602
  }
1603 1604
}

1605
void DBDumperCommand::Help(std::string& ret) {
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
  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]");
1618
  ret.append(" [--" + ARG_PATH + "=<path_to_a_file>]");
1619
  ret.append("\n");
1620 1621
}

1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
/**
 * 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.
 *
 */
1633
void DBDumperCommand::DoCommand() {
1634
  if (!db_) {
1635
    assert(!path_.empty());
1636
    std::string fileName = GetFileNameFromPath(path_);
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
    uint64_t number;
    FileType type;

    exec_state_ = LDBCommandExecuteResult::Succeed("");

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

    switch (type) {
      case kLogFile:
1650
        // TODO(myabandeh): allow configuring is_write_commited
1651 1652 1653
        DumpWalFile(options_, path_, /* print_header_ */ true,
                    /* print_values_ */ true, true /* is_write_commited */,
                    &exec_state_);
1654 1655
        break;
      case kTableFile:
1656
        DumpSstFile(options_, path_, is_key_hex_, /* show_properties */ true);
1657 1658
        break;
      case kDescriptorFile:
1659
        DumpManifestFile(options_, path_, /* verbose_ */ false, is_key_hex_,
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
                         /*  json_ */ false);
        break;
      default:
        exec_state_ = LDBCommandExecuteResult::Failed(
            "File type not supported: " + path_);
        break;
    }

  } else {
    DoDumpCommand();
1670
  }
1671 1672 1673 1674 1675 1676
}

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

1677 1678 1679
  // Parse command line args
  uint64_t count = 0;
  if (print_stats_) {
1680
    std::string stats;
1681
    if (db_->GetProperty("rocksdb.stats", &stats)) {
1682 1683 1684 1685 1686
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Setup key iterator
1687 1688 1689
  ReadOptions scan_read_opts;
  scan_read_opts.total_order_seek = true;
  Iterator* iter = db_->NewIterator(scan_read_opts, GetCfHandle());
1690
  Status st = iter->status();
1691
  if (!st.ok()) {
1692 1693
    exec_state_ =
        LDBCommandExecuteResult::Failed("Iterator error." + st.ToString());
1694 1695 1696 1697 1698 1699 1700 1701 1702
  }

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

  int max_keys = max_keys_;
1703
  int ttl_start;
1704
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
1705
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
1706 1707
  }
  int ttl_end;
1708
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
1709
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
1710 1711 1712 1713 1714 1715 1716 1717
  }
  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;
1718
  if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
1719 1720 1721
      bucket_size <= 0) {
    bucket_size = time_range; // Will have just 1 bucket by default
  }
1722
  //cretaing variables for row count of each type
1723
  std::string rtype1, rtype2, row, val;
1724
  rtype2 = "";
1725 1726
  uint64_t c=0;
  uint64_t s1=0,s2=0;
1727

1728
  // At this point, bucket_size=0 => time_range=0
1729 1730 1731
  int num_buckets = (bucket_size >= time_range)
                        ? 1
                        : ((time_range + bucket_size - 1) / bucket_size);
1732
  std::vector<uint64_t> bucket_counts(num_buckets, 0);
1733
  if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
1734
    fprintf(stdout, "Dumping key-values from %s to %s\n",
1735 1736
            TimeToHumanString(ttl_start).c_str(),
            TimeToHumanString(ttl_end).c_str());
1737 1738
  }

1739 1740
  HistogramImpl vsize_hist;

1741
  for (; iter->Valid(); iter->Next()) {
1742
    int rawtime = 0;
1743 1744 1745 1746 1747 1748
    // 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;
1749
    if (is_db_ttl_) {
S
Siying Dong 已提交
1750
      TtlIterator* it_ttl = static_cast_with_check<TtlIterator, Iterator>(iter);
Y
Yanqin Jin 已提交
1751
      rawtime = it_ttl->ttl_timestamp();
1752
      if (rawtime < ttl_start || rawtime >= ttl_end) {
1753 1754 1755
        continue;
      }
    }
1756 1757 1758
    if (max_keys > 0) {
      --max_keys;
    }
1759
    if (is_db_ttl_ && num_buckets > 1) {
1760
      IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
1761 1762
                      rawtime, num_buckets);
    }
1763
    ++count;
1764 1765 1766 1767 1768
    if (count_delim_) {
      rtype1 = "";
      row = iter->key().ToString();
      val = iter->value().ToString();
      s1 = row.size()+val.size();
1769 1770 1771
      for(int j=0;row[j]!=delim_[0] && row[j]!='\0';j++)
        rtype1+=row[j];
      if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
1772 1773
        fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
                rtype2.c_str(), c, s2);
1774 1775
        c=1;
        s2=s1;
1776 1777
        rtype2 = rtype1;
      } else {
1778 1779 1780
          c++;
          s2+=s1;
          rtype2=rtype1;
1781
      }
1782

1783 1784
    }

1785 1786 1787
    if (count_only_) {
      vsize_hist.Add(iter->value().size());
    }
1788

1789
    if (!count_only_ && !count_delim_) {
1790
      if (is_db_ttl_ && timestamp_) {
1791
        fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
1792
      }
1793 1794 1795
      std::string str =
          PrintKeyValue(iter->key().ToString(), iter->value().ToString(),
                        is_key_hex_, is_value_hex_);
1796
      fprintf(stdout, "%s\n", str.c_str());
1797 1798
    }
  }
1799

1800
  if (num_buckets > 1 && is_db_ttl_) {
1801
    PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
1802
                      num_buckets);
1803
  } else if(count_delim_) {
1804 1805
    fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
            rtype2.c_str(), c, s2);
1806
  } else {
1807
    fprintf(stdout, "Keys in range: %" PRIu64 "\n", count);
1808
  }
1809 1810 1811 1812 1813

  if (count_only_) {
    fprintf(stdout, "Value size distribution: \n");
    fprintf(stdout, "%s\n", vsize_hist.ToString().c_str());
  }
1814 1815 1816 1817
  // Clean up
  delete iter;
}

1818 1819 1820
const std::string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
const std::string ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS =
    "print_old_levels";
1821

1822
ReduceDBLevelsCommand::ReduceDBLevelsCommand(
A
Andrew Kryczka 已提交
1823
    const std::vector<std::string>& /*params*/,
1824 1825 1826 1827 1828 1829 1830
    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) {
1831
  ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
1832
  print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
1833

1834
  if(new_levels_ <= 0) {
1835
    exec_state_ = LDBCommandExecuteResult::Failed(
1836
        " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
1837 1838 1839
  }
}

1840 1841 1842
std::vector<std::string> ReduceDBLevelsCommand::PrepareArgs(
    const std::string& db_path, int new_levels, bool print_old_level) {
  std::vector<std::string> ret;
1843
  ret.push_back("reduce_levels");
1844
  ret.push_back("--" + ARG_DB + "=" + db_path);
1845 1846
  ret.push_back("--" + ARG_NEW_LEVELS + "=" +
                ROCKSDB_NAMESPACE::ToString(new_levels));
1847
  if(print_old_level) {
1848
    ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
1849 1850 1851 1852
  }
  return ret;
}

1853
void ReduceDBLevelsCommand::Help(std::string& ret) {
1854 1855 1856 1857 1858
  ret.append("  ");
  ret.append(ReduceDBLevelsCommand::Name());
  ret.append(" --" + ARG_NEW_LEVELS + "=<New number of levels>");
  ret.append(" [--" + ARG_PRINT_OLD_LEVELS + "]");
  ret.append("\n");
1859 1860
}

1861 1862
Options ReduceDBLevelsCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1863
  opt.num_levels = old_levels_;
1864
  opt.max_bytes_for_level_multiplier_additional.resize(opt.num_levels, 1);
1865
  // Disable size compaction
I
Igor Canadi 已提交
1866
  opt.max_bytes_for_level_base = 1ULL << 50;
1867
  opt.max_bytes_for_level_multiplier = 1;
1868 1869 1870
  return opt;
}

1871
Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt,
1872
    int* levels) {
1873
  ImmutableDBOptions db_options(opt);
H
Haobo Xu 已提交
1874
  EnvOptions soptions;
I
Igor Canadi 已提交
1875
  std::shared_ptr<Cache> tc(
1876
      NewLRUCache(opt.max_open_files - 10, opt.table_cache_numshardbits));
1877
  const InternalKeyComparator cmp(opt.comparator);
S
sdong 已提交
1878
  WriteController wc(opt.delayed_write_rate);
1879
  WriteBufferManager wb(opt.db_write_buffer_size);
1880 1881
  VersionSet versions(db_path_, &db_options, soptions, tc.get(), &wb, &wc,
                      /*block_cache_tracer=*/nullptr);
I
Igor Canadi 已提交
1882
  std::vector<ColumnFamilyDescriptor> dummy;
1883
  ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName,
I
Igor Canadi 已提交
1884 1885
                                          ColumnFamilyOptions(opt));
  dummy.push_back(dummy_descriptor);
1886 1887 1888
  // 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 已提交
1889
  Status st = versions.Recover(dummy);
1890 1891 1892 1893
  if (!st.ok()) {
    return st;
  }
  int max = -1;
1894
  auto default_cfd = versions.GetColumnFamilySet()->GetDefault();
I
Igor Canadi 已提交
1895
  for (int i = 0; i < default_cfd->NumberLevels(); i++) {
S
sdong 已提交
1896
    if (default_cfd->current()->storage_info()->NumLevelFiles(i)) {
1897 1898 1899 1900 1901 1902 1903 1904
      max = i;
    }
  }

  *levels = max + 1;
  return st;
}

1905
void ReduceDBLevelsCommand::DoCommand() {
1906
  if (new_levels_ <= 1) {
1907 1908
    exec_state_ =
        LDBCommandExecuteResult::Failed("Invalid number of levels.\n");
1909 1910 1911
    return;
  }

1912 1913
  Status st;
  Options opt = PrepareOptionsForOpenDB();
1914 1915 1916
  int old_level_num = -1;
  st = GetOldNumOfLevels(opt, &old_level_num);
  if (!st.ok()) {
1917
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1918 1919 1920
    return;
  }

1921
  if (print_old_levels_) {
1922
    fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
1923
  }
1924

1925 1926
  if (old_level_num <= new_levels_) {
    return;
1927 1928
  }

1929 1930 1931
  old_levels_ = old_level_num;

  OpenDB();
1932
  if (exec_state_.IsFailed()) {
1933 1934
    return;
  }
1935
  assert(db_ != nullptr);
1936
  // Compact the whole DB to put all files to the highest level.
1937
  fprintf(stdout, "Compacting the db...\n");
S
sdong 已提交
1938
  db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);
1939 1940
  CloseDB();

H
Haobo Xu 已提交
1941
  EnvOptions soptions;
1942
  st = VersionSet::ReduceNumberOfLevels(db_path_, &opt, soptions, new_levels_);
1943
  if (!st.ok()) {
1944
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1945 1946 1947 1948
    return;
  }
}

1949 1950 1951 1952
const std::string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
    "old_compaction_style";
const std::string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
    "new_compaction_style";
1953 1954

ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
A
Andrew Kryczka 已提交
1955
    const std::vector<std::string>& /*params*/,
1956 1957 1958 1959 1960 1961 1962
    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) {
1963 1964
  ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
    exec_state_);
1965 1966
  if (old_compaction_style_ != kCompactionStyleLevel &&
     old_compaction_style_ != kCompactionStyleUniversal) {
1967
    exec_state_ = LDBCommandExecuteResult::Failed(
1968 1969
        "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
        "style. Check ldb help for proper compaction style value.\n");
1970 1971 1972
    return;
  }

1973 1974
  ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
    exec_state_);
1975 1976
  if (new_compaction_style_ != kCompactionStyleLevel &&
     new_compaction_style_ != kCompactionStyleUniversal) {
1977
    exec_state_ = LDBCommandExecuteResult::Failed(
1978 1979
        "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
        "style. Check ldb help for proper compaction style value.\n");
1980 1981 1982 1983
    return;
  }

  if (new_compaction_style_ == old_compaction_style_) {
1984
    exec_state_ = LDBCommandExecuteResult::Failed(
1985 1986
        "Old compaction style is the same as new compaction style. "
        "Nothing to do.\n");
1987 1988 1989 1990 1991
    return;
  }

  if (old_compaction_style_ == kCompactionStyleUniversal &&
      new_compaction_style_ == kCompactionStyleLevel) {
1992
    exec_state_ = LDBCommandExecuteResult::Failed(
1993 1994
        "Convert from universal compaction to level compaction. "
        "Nothing to do.\n");
1995 1996 1997 1998
    return;
  }
}

1999
void ChangeCompactionStyleCommand::Help(std::string& ret) {
2000 2001 2002 2003 2004 2005 2006
  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");
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
}

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

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

  return opt;
}

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

2035
    // format print string
2036
    char buf[100];
2037
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
2038 2039 2040 2041 2042 2043
    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
2044 2045 2046
  CompactRangeOptions compact_options;
  compact_options.change_level = true;
  compact_options.target_level = 0;
S
sdong 已提交
2047
  db_->CompactRange(compact_options, GetCfHandle(), nullptr, nullptr);
2048 2049 2050 2051

  // verify compaction result
  files_per_level = "";
  int num_files = 0;
2052
  for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
S
sdong 已提交
2053 2054
    db_->GetProperty(GetCfHandle(),
                     "rocksdb.num-files-at-level" + NumberToString(i),
2055 2056
                     &property);

2057
    // format print string
2058
    char buf[100];
2059
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
2060 2061 2062 2063 2064 2065
    files_per_level += buf;

    num_files = atoi(property.c_str());

    // level 0 should have only 1 file
    if (i == 0 && num_files != 1) {
2066 2067 2068 2069
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level 0 after compaction is " +
          ToString(num_files) + ", not 1.\n");
2070 2071 2072 2073
      return;
    }
    // other levels should have no file
    if (i > 0 && num_files != 0) {
2074 2075 2076 2077 2078
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level " +
          ToString(i) + " after compaction is " + ToString(num_files) +
          ", not 0.\n");
2079 2080 2081 2082 2083 2084 2085 2086
      return;
    }
  }

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

2087 2088 2089 2090 2091
// ----------------------------------------------------------------------------

namespace {

struct StdErrReporter : public log::Reader::Reporter {
2092
  void Corruption(size_t /*bytes*/, const Status& s) override {
2093
    std::cerr << "Corruption detected in log file " << s.ToString() << "\n";
2094 2095 2096
  }
};

2097 2098
class InMemoryHandler : public WriteBatch::Handler {
 public:
2099 2100 2101 2102 2103 2104
  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) {}
2105

2106
  void commonPutMerge(const Slice& key, const Slice& value) {
2107
    std::string k = LDBCommand::StringToHex(key.ToString());
2108
    if (print_values_) {
2109
      std::string v = LDBCommand::StringToHex(value.ToString());
2110 2111 2112 2113 2114
      row_ << k << " : ";
      row_ << v << " ";
    } else {
      row_ << k << " ";
    }
2115
  }
2116

2117
  Status PutCF(uint32_t cf, const Slice& key, const Slice& value) override {
R
Reid Horuff 已提交
2118
    row_ << "PUT(" << cf << ") : ";
2119
    commonPutMerge(key, value);
R
Reid Horuff 已提交
2120
    return Status::OK();
2121 2122
  }

2123
  Status MergeCF(uint32_t cf, const Slice& key, const Slice& value) override {
R
Reid Horuff 已提交
2124
    row_ << "MERGE(" << cf << ") : ";
2125
    commonPutMerge(key, value);
R
Reid Horuff 已提交
2126
    return Status::OK();
2127
  }
2128

2129
  Status MarkNoop(bool) override {
2130 2131 2132 2133
    row_ << "NOOP ";
    return Status::OK();
  }

2134
  Status DeleteCF(uint32_t cf, const Slice& key) override {
R
Reid Horuff 已提交
2135
    row_ << "DELETE(" << cf << ") : ";
2136
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
R
Reid Horuff 已提交
2137 2138 2139
    return Status::OK();
  }

2140
  Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
R
Reid Horuff 已提交
2141 2142 2143 2144 2145
    row_ << "SINGLE_DELETE(" << cf << ") : ";
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
    return Status::OK();
  }

2146 2147
  Status DeleteRangeCF(uint32_t cf, const Slice& begin_key,
                       const Slice& end_key) override {
A
Andrew Kryczka 已提交
2148 2149 2150 2151 2152 2153
    row_ << "DELETE_RANGE(" << cf << ") : ";
    row_ << LDBCommand::StringToHex(begin_key.ToString()) << " ";
    row_ << LDBCommand::StringToHex(end_key.ToString()) << " ";
    return Status::OK();
  }

2154
  Status MarkBeginPrepare(bool unprepare) override {
2155 2156
    row_ << "BEGIN_PREPARE(";
    row_ << (unprepare ? "true" : "false") << ") ";
R
Reid Horuff 已提交
2157 2158 2159
    return Status::OK();
  }

2160
  Status MarkEndPrepare(const Slice& xid) override {
R
Reid Horuff 已提交
2161 2162 2163 2164 2165
    row_ << "END_PREPARE(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
  }

2166
  Status MarkRollback(const Slice& xid) override {
R
Reid Horuff 已提交
2167 2168 2169 2170 2171
    row_ << "ROLLBACK(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
  }

2172
  Status MarkCommit(const Slice& xid) override {
R
Reid Horuff 已提交
2173 2174 2175
    row_ << "COMMIT(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
2176 2177
  }

2178
  ~InMemoryHandler() override {}
2179

2180
 protected:
2181
  bool WriteAfterCommit() const override { return write_after_commit_; }
2182

2183
 private:
2184
  std::stringstream& row_;
2185
  bool print_values_;
2186
  bool write_after_commit_;
2187 2188
};

2189 2190 2191 2192 2193
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);
2194
  std::unique_ptr<SequentialFileReader> wal_file_reader;
2195 2196 2197

  Status status;
  {
2198
    std::unique_ptr<SequentialFile> file;
2199
    status = env->NewSequentialFile(wal_file, &file, soptions);
2200
    if (status.ok()) {
2201 2202
      wal_file_reader.reset(new SequentialFileReader(
          NewLegacySequentialFileWrapper(file), wal_file));
2203 2204
    }
  }
2205 2206
  if (!status.ok()) {
    if (exec_state) {
2207
      *exec_state = LDBCommandExecuteResult::Failed("Failed to open WAL file " +
2208 2209
                                                    status.ToString());
    } else {
2210 2211
      std::cerr << "Error: Failed to open WAL file " << status.ToString()
                << std::endl;
2212 2213 2214
    }
  } else {
    StdErrReporter reporter;
2215 2216 2217 2218
    uint64_t log_number;
    FileType type;

    // we need the log number, but ParseFilename expects dbname/NNN.log.
2219
    std::string sanitized = wal_file;
2220 2221 2222 2223 2224 2225 2226
    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;
    }
2227
    log::Reader reader(options.info_log, std::move(wal_file_reader), &reporter,
2228
                       true /* checksum */, log_number);
2229
    std::string scratch;
2230 2231
    WriteBatch batch;
    Slice record;
2232
    std::stringstream row;
2233
    if (print_header) {
2234
      std::cout << "Sequence,Count,ByteSize,Physical Offset,Key(s)";
2235
      if (print_values) {
2236
        std::cout << " : value ";
2237
      }
2238
      std::cout << "\n";
2239 2240 2241
    }
    while (reader.ReadRecord(&record, &scratch)) {
      row.str("");
2242
      if (record.size() < WriteBatchInternal::kHeader) {
2243 2244 2245 2246 2247 2248 2249 2250
        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() << ",";
2251
        InMemoryHandler handler(row, print_values, is_write_committed);
2252 2253 2254
        batch.Iterate(&handler);
        row << "\n";
      }
2255
      std::cout << row.str();
2256 2257 2258 2259 2260 2261
    }
  }
}

}  // namespace

2262
const std::string WALDumperCommand::ARG_WAL_FILE = "walfile";
2263
const std::string WALDumperCommand::ARG_WRITE_COMMITTED = "write_committed";
2264 2265
const std::string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
const std::string WALDumperCommand::ARG_PRINT_HEADER = "header";
2266

2267
WALDumperCommand::WALDumperCommand(
A
Andrew Kryczka 已提交
2268
    const std::vector<std::string>& /*params*/,
2269 2270 2271
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, true,
2272 2273
                 BuildCmdLineOptions({ARG_WAL_FILE, ARG_WRITE_COMMITTED,
                                      ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
2274
      print_header_(false),
2275 2276
      print_values_(false),
      is_write_committed_(false) {
A
Abhishek Kona 已提交
2277
  wal_file_.clear();
2278

2279 2280
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_WAL_FILE);
2281 2282
  if (itr != options.end()) {
    wal_file_ = itr->second;
A
Abhishek Kona 已提交
2283
  }
2284 2285


2286 2287
  print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
2288 2289
  is_write_committed_ = ParseBooleanOption(options, ARG_WRITE_COMMITTED, true);

A
Abhishek Kona 已提交
2290
  if (wal_file_.empty()) {
2291 2292
    exec_state_ = LDBCommandExecuteResult::Failed("Argument " + ARG_WAL_FILE +
                                                  " must be specified.");
A
Abhishek Kona 已提交
2293 2294 2295
  }
}

2296
void WALDumperCommand::Help(std::string& ret) {
2297 2298 2299 2300 2301
  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 + "] ");
2302
  ret.append(" [--" + ARG_WRITE_COMMITTED + "=true|false] ");
2303
  ret.append("\n");
A
Abhishek Kona 已提交
2304 2305
}

2306
void WALDumperCommand::DoCommand() {
2307 2308
  DumpWalFile(options_, wal_file_, print_header_, print_values_,
              is_write_committed_, &exec_state_);
A
Abhishek Kona 已提交
2309 2310
}

2311
// ----------------------------------------------------------------------------
2312

2313 2314 2315 2316 2317 2318
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})) {
2319
  if (params.size() != 1) {
2320
    exec_state_ = LDBCommandExecuteResult::Failed(
2321
        "<key> must be specified for the get command");
2322 2323 2324 2325 2326 2327 2328 2329 2330
  } else {
    key_ = params.at(0);
  }

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

2331
void GetCommand::Help(std::string& ret) {
2332 2333 2334 2335 2336
  ret.append("  ");
  ret.append(GetCommand::Name());
  ret.append(" <key>");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2337 2338 2339
}

void GetCommand::DoCommand() {
S
sdong 已提交
2340 2341 2342 2343
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2344
  std::string value;
S
sdong 已提交
2345
  Status st = db_->Get(ReadOptions(), GetCfHandle(), key_, &value);
2346 2347 2348 2349
  if (st.ok()) {
    fprintf(stdout, "%s\n",
              (is_value_hex_ ? StringToHex(value) : value).c_str());
  } else {
2350
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2351 2352 2353
  }
}

2354
// ----------------------------------------------------------------------------
2355

2356
ApproxSizeCommand::ApproxSizeCommand(
A
Andrew Kryczka 已提交
2357
    const std::vector<std::string>& /*params*/,
2358 2359 2360 2361 2362
    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})) {
2363 2364 2365
  if (options.find(ARG_FROM) != options.end()) {
    start_key_ = options.find(ARG_FROM)->second;
  } else {
2366 2367
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_FROM + " must be specified for approxsize command");
2368 2369 2370 2371 2372 2373
    return;
  }

  if (options.find(ARG_TO) != options.end()) {
    end_key_ = options.find(ARG_TO)->second;
  } else {
2374 2375
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_TO + " must be specified for approxsize command");
2376 2377 2378 2379 2380 2381 2382 2383 2384
    return;
  }

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

2385
void ApproxSizeCommand::Help(std::string& ret) {
2386 2387 2388 2389
  ret.append("  ");
  ret.append(ApproxSizeCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
2390 2391 2392
}

void ApproxSizeCommand::DoCommand() {
S
sdong 已提交
2393 2394 2395 2396
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2397 2398
  Range ranges[1];
  ranges[0] = Range(start_key_, end_key_);
2399
  uint64_t sizes[1];
S
sdong 已提交
2400
  db_->GetApproximateSizes(GetCfHandle(), ranges, 1, sizes);
K
Kai Liu 已提交
2401
  fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
2402
  /* Weird that GetApproximateSizes() returns void, although documentation
2403 2404
   * says that it returns a Status object.
  if (!st.ok()) {
2405
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2406 2407 2408 2409
  }
  */
}

2410
// ----------------------------------------------------------------------------
2411

2412 2413 2414 2415 2416 2417 2418
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})) {
2419
  if (params.size() < 2) {
2420
    exec_state_ = LDBCommandExecuteResult::Failed(
2421
        "At least one <key> <value> pair must be specified batchput.");
2422
  } else if (params.size() % 2 != 0) {
2423
    exec_state_ = LDBCommandExecuteResult::Failed(
2424 2425 2426
        "Equal number of <key>s and <value>s must be specified for batchput.");
  } else {
    for (size_t i = 0; i < params.size(); i += 2) {
2427 2428 2429 2430 2431
      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));
2432 2433
    }
  }
2434
  create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
2435 2436
}

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

void BatchPutCommand::DoCommand() {
S
sdong 已提交
2446 2447 2448 2449
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2450
  WriteBatch batch;
2451

2452 2453 2454
  for (std::vector<std::pair<std::string, std::string>>::const_iterator itr =
           key_values_.begin();
       itr != key_values_.end(); ++itr) {
S
sdong 已提交
2455
    batch.Put(GetCfHandle(), itr->first, itr->second);
2456
  }
2457
  Status st = db_->Write(WriteOptions(), &batch);
2458 2459 2460
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2461
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2462 2463 2464
  }
}

2465 2466
Options BatchPutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
2467
  opt.create_if_missing = create_if_missing_;
2468 2469 2470
  return opt;
}

2471
// ----------------------------------------------------------------------------
2472

A
Andrew Kryczka 已提交
2473
ScanCommand::ScanCommand(const std::vector<std::string>& /*params*/,
2474 2475 2476 2477 2478 2479 2480
                         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 已提交
2481 2482 2483 2484
      start_key_specified_(false),
      end_key_specified_(false),
      max_keys_scanned_(-1),
      no_value_(false) {
2485 2486
  std::map<std::string, std::string>::const_iterator itr =
      options.find(ARG_FROM);
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
  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;
  }

2503
  std::vector<std::string>::const_iterator vitr =
A
Alexander Fenster 已提交
2504
      std::find(flags.begin(), flags.end(), ARG_NO_VALUE);
2505 2506 2507 2508
  if (vitr != flags.end()) {
    no_value_ = true;
  }

2509 2510 2511
  itr = options.find(ARG_MAX_KEYS);
  if (itr != options.end()) {
    try {
S
sdong 已提交
2512 2513 2514
#if defined(CYGWIN)
      max_keys_scanned_ = strtol(itr->second.c_str(), 0, 10);
#else
2515
      max_keys_scanned_ = std::stoi(itr->second);
S
sdong 已提交
2516
#endif
2517
    } catch (const std::invalid_argument&) {
2518
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
2519
                                                    " has an invalid value");
2520
    } catch (const std::out_of_range&) {
2521 2522
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
2523 2524 2525 2526
    }
  }
}

2527
void ScanCommand::Help(std::string& ret) {
2528 2529 2530 2531 2532 2533 2534 2535
  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]");
2536
  ret.append(" [--" + ARG_NO_VALUE + "]");
2537
  ret.append("\n");
2538 2539 2540
}

void ScanCommand::DoCommand() {
S
sdong 已提交
2541 2542 2543 2544
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2545 2546

  int num_keys_scanned = 0;
2547 2548 2549
  ReadOptions scan_read_opts;
  scan_read_opts.total_order_seek = true;
  Iterator* it = db_->NewIterator(scan_read_opts, GetCfHandle());
2550 2551 2552 2553 2554
  if (start_key_specified_) {
    it->Seek(start_key_);
  } else {
    it->SeekToFirst();
  }
2555
  int ttl_start;
2556
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
2557
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
2558 2559
  }
  int ttl_end;
2560
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
2561
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
2562 2563 2564 2565 2566 2567 2568 2569
  }
  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",
2570 2571
            TimeToHumanString(ttl_start).c_str(),
            TimeToHumanString(ttl_end).c_str());
2572
  }
2573
  for ( ;
2574 2575
        it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
        it->Next()) {
2576
    if (is_db_ttl_) {
S
Siying Dong 已提交
2577
      TtlIterator* it_ttl = static_cast_with_check<TtlIterator, Iterator>(it);
Y
Yanqin Jin 已提交
2578
      int rawtime = it_ttl->ttl_timestamp();
2579
      if (rawtime < ttl_start || rawtime >= ttl_end) {
2580 2581 2582
        continue;
      }
      if (timestamp_) {
2583
        fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
2584 2585
      }
    }
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597

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

2598
    if (no_value_) {
A
Alexander Fenster 已提交
2599 2600
      fprintf(stdout, "%.*s\n", static_cast<int>(key_slice.size()),
              key_slice.data());
2601
    } else {
A
Alexander Fenster 已提交
2602 2603 2604 2605 2606 2607 2608 2609 2610
      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());
2611 2612
    }

2613 2614 2615 2616 2617 2618
    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
2619
    exec_state_ = LDBCommandExecuteResult::Failed(it->status().ToString());
2620 2621 2622 2623
  }
  delete it;
}

2624
// ----------------------------------------------------------------------------
2625

2626 2627 2628 2629 2630
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})) {
2631
  if (params.size() != 1) {
2632
    exec_state_ = LDBCommandExecuteResult::Failed(
2633
        "KEY must be specified for the delete command");
2634 2635 2636 2637 2638 2639 2640 2641
  } else {
    key_ = params.at(0);
    if (is_key_hex_) {
      key_ = HexToString(key_);
    }
  }
}

2642
void DeleteCommand::Help(std::string& ret) {
2643 2644 2645
  ret.append("  ");
  ret.append(DeleteCommand::Name() + " <key>");
  ret.append("\n");
2646 2647 2648
}

void DeleteCommand::DoCommand() {
S
sdong 已提交
2649 2650 2651 2652 2653
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st = db_->Delete(WriteOptions(), GetCfHandle(), key_);
2654 2655 2656
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2657
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2658 2659 2660
  }
}

A
Andrew Kryczka 已提交
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
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());
  }
}

2700 2701 2702 2703 2704 2705
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})) {
2706
  if (params.size() != 2) {
2707
    exec_state_ = LDBCommandExecuteResult::Failed(
2708
        "<key> and <value> must be specified for the put command");
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
  } else {
    key_ = params.at(0);
    value_ = params.at(1);
  }

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

  if (is_value_hex_) {
    value_ = HexToString(value_);
  }
2721
  create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
2722 2723
}

2724
void PutCommand::Help(std::string& ret) {
2725 2726 2727 2728 2729
  ret.append("  ");
  ret.append(PutCommand::Name());
  ret.append(" <key> <value> ");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2730 2731 2732
}

void PutCommand::DoCommand() {
S
sdong 已提交
2733 2734 2735 2736 2737
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st = db_->Put(WriteOptions(), GetCfHandle(), key_, value_);
2738 2739 2740
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2741
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2742 2743 2744
  }
}

2745 2746
Options PutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
2747
  opt.create_if_missing = create_if_missing_;
2748 2749 2750
  return opt;
}

2751
// ----------------------------------------------------------------------------
2752 2753 2754 2755 2756 2757

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

2758
DBQuerierCommand::DBQuerierCommand(
A
Andrew Kryczka 已提交
2759
    const std::vector<std::string>& /*params*/,
2760 2761 2762 2763 2764
    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})) {
2765 2766 2767

}

2768
void DBQuerierCommand::Help(std::string& ret) {
2769 2770 2771 2772 2773
  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 "
2774
             "commands.");
2775
  ret.append("\n");
2776 2777 2778 2779
}

void DBQuerierCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
2780
    assert(GetExecuteState().IsFailed());
2781 2782
    return;
  }
2783

2784 2785
  ReadOptions read_options;
  WriteOptions write_options;
2786

2787 2788 2789 2790 2791 2792
  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;
2793 2794 2795
    size_t pos = 0;
    while (true) {
      size_t pos2 = line.find(' ', pos);
2796
      if (pos2 == std::string::npos) {
2797 2798 2799 2800 2801 2802 2803
        break;
      }
      tokens.push_back(line.substr(pos, pos2-pos));
      pos = pos2 + 1;
    }
    tokens.push_back(line.substr(pos));

2804
    const std::string& cmd = tokens[0];
2805 2806 2807 2808 2809 2810 2811 2812

    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 已提交
2813
      db_->Delete(write_options, GetCfHandle(), Slice(key));
2814 2815 2816 2817
      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 已提交
2818
      db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
2819 2820 2821 2822
      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 已提交
2823
      if (db_->Get(read_options, GetCfHandle(), Slice(key), &value).ok()) {
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
        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());
    }
  }
}

2835 2836
// ----------------------------------------------------------------------------

2837
CheckConsistencyCommand::CheckConsistencyCommand(
A
Andrew Kryczka 已提交
2838
    const std::vector<std::string>& /*params*/,
2839 2840 2841
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}
Y
Yiting Li 已提交
2842

2843
void CheckConsistencyCommand::Help(std::string& ret) {
2844 2845 2846
  ret.append("  ");
  ret.append(CheckConsistencyCommand::Name());
  ret.append("\n");
Y
Yiting Li 已提交
2847
}
2848

Y
Yiting Li 已提交
2849 2850
void CheckConsistencyCommand::DoCommand() {
  Options opt = PrepareOptionsForOpenDB();
I
Igor Canadi 已提交
2851
  opt.paranoid_checks = true;
Y
Yiting Li 已提交
2852 2853 2854
  if (!exec_state_.IsNotStarted()) {
    return;
  }
I
Igor Canadi 已提交
2855 2856 2857
  DB* db;
  Status st = DB::OpenForReadOnly(opt, db_path_, &db, false);
  delete db;
Y
Yiting Li 已提交
2858 2859 2860
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2861
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
Y
Yiting Li 已提交
2862
  }
2863
}
Y
Yiting Li 已提交
2864

2865
// ----------------------------------------------------------------------------
A
Andrew Kryczka 已提交
2866

A
Aaron Gao 已提交
2867 2868 2869
const std::string CheckPointCommand::ARG_CHECKPOINT_DIR = "checkpoint_dir";

CheckPointCommand::CheckPointCommand(
A
Andrew Kryczka 已提交
2870
    const std::vector<std::string>& /*params*/,
A
Aaron Gao 已提交
2871 2872 2873 2874 2875
    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);
2876
  if (itr != options.end()) {
A
Aaron Gao 已提交
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
    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()) {
2897
    fprintf(stdout, "OK\n");
A
Aaron Gao 已提交
2898 2899 2900 2901 2902 2903 2904
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

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

A
Andrew Kryczka 已提交
2905
RepairCommand::RepairCommand(const std::vector<std::string>& /*params*/,
2906 2907
                             const std::map<std::string, std::string>& options,
                             const std::vector<std::string>& flags)
A
Andrew Kryczka 已提交
2908 2909
    : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}

2910
void RepairCommand::Help(std::string& ret) {
A
Andrew Kryczka 已提交
2911 2912 2913 2914 2915 2916 2917
  ret.append("  ");
  ret.append(RepairCommand::Name());
  ret.append("\n");
}

void RepairCommand::DoCommand() {
  Options options = PrepareOptionsForOpenDB();
A
Andrew Kryczka 已提交
2918
  options.info_log.reset(new StderrLogger(InfoLogLevel::WARN_LEVEL));
A
Andrew Kryczka 已提交
2919 2920
  Status status = RepairDB(db_path_, options);
  if (status.ok()) {
2921
    fprintf(stdout, "OK\n");
A
Andrew Kryczka 已提交
2922 2923 2924 2925 2926 2927
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

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

2929 2930 2931 2932
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 已提交
2933

2934
BackupableCommand::BackupableCommand(
A
Andrew Kryczka 已提交
2935
    const std::vector<std::string>& /*params*/,
2936 2937 2938 2939 2940 2941 2942
    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 已提交
2943
  if (itr != options.end()) {
2944
    num_threads_ = std::stoi(itr->second);
W
Wanning Jiang 已提交
2945
  }
2946
  itr = options.find(ARG_BACKUP_ENV_URI);
A
Andrew Kryczka 已提交
2947
  if (itr != options.end()) {
2948
    backup_env_uri_ = itr->second;
W
Wanning Jiang 已提交
2949 2950 2951 2952 2953 2954
  }
  itr = options.find(ARG_BACKUP_DIR);
  if (itr == options.end()) {
    exec_state_ = LDBCommandExecuteResult::Failed("--" + ARG_BACKUP_DIR +
                                                  ": missing backup directory");
  } else {
2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969
    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 已提交
2970 2971 2972
  }
}

2973
void BackupableCommand::Help(const std::string& name, std::string& ret) {
W
Wanning Jiang 已提交
2974
  ret.append("  ");
2975 2976
  ret.append(name);
  ret.append(" [--" + ARG_BACKUP_ENV_URI + "] ");
W
Wanning Jiang 已提交
2977
  ret.append(" [--" + ARG_BACKUP_DIR + "] ");
2978 2979
  ret.append(" [--" + ARG_NUM_THREADS + "] ");
  ret.append(" [--" + ARG_STDERR_LOG_LEVEL + "=<int (InfoLogLevel)>] ");
W
Wanning Jiang 已提交
2980 2981 2982
  ret.append("\n");
}

2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
// ----------------------------------------------------------------------------

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 已提交
2994 2995 2996 2997 2998 2999 3000
void BackupCommand::DoCommand() {
  BackupEngine* backup_engine;
  Status status;
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
3001
  fprintf(stdout, "open db OK\n");
3002
  Env* custom_env = nullptr;
3003 3004
  Env::LoadEnv(backup_env_uri_, &custom_env, &backup_env_guard_);
  assert(custom_env != nullptr);
3005

W
Wanning Jiang 已提交
3006
  BackupableDBOptions backup_options =
3007 3008 3009
      BackupableDBOptions(backup_dir_, custom_env);
  backup_options.info_log = logger_.get();
  backup_options.max_background_operations = num_threads_;
3010
  status = BackupEngine::Open(custom_env, backup_options, &backup_engine);
W
Wanning Jiang 已提交
3011
  if (status.ok()) {
3012
    fprintf(stdout, "open backup engine OK\n");
W
Wanning Jiang 已提交
3013 3014 3015 3016 3017 3018
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
    return;
  }
  status = backup_engine->CreateNewBackup(db_);
  if (status.ok()) {
3019
    fprintf(stdout, "create new backup OK\n");
W
Wanning Jiang 已提交
3020 3021 3022 3023 3024 3025 3026
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
    return;
  }
}

// ----------------------------------------------------------------------------
A
Andrew Kryczka 已提交
3027 3028 3029 3030 3031

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

void RestoreCommand::Help(std::string& ret) {
3035
  BackupableCommand::Help(Name(), ret);
A
Andrew Kryczka 已提交
3036 3037 3038
}

void RestoreCommand::DoCommand() {
3039
  Env* custom_env = nullptr;
3040 3041
  Env::LoadEnv(backup_env_uri_, &custom_env, &backup_env_guard_);
  assert(custom_env != nullptr);
3042

A
Andrew Kryczka 已提交
3043 3044 3045 3046
  std::unique_ptr<BackupEngineReadOnly> restore_engine;
  Status status;
  {
    BackupableDBOptions opts(backup_dir_, custom_env);
3047
    opts.info_log = logger_.get();
A
Andrew Kryczka 已提交
3048 3049
    opts.max_background_operations = num_threads_;
    BackupEngineReadOnly* raw_restore_engine_ptr;
3050 3051
    status =
        BackupEngineReadOnly::Open(custom_env, opts, &raw_restore_engine_ptr);
A
Andrew Kryczka 已提交
3052 3053 3054 3055 3056
    if (status.ok()) {
      restore_engine.reset(raw_restore_engine_ptr);
    }
  }
  if (status.ok()) {
3057
    fprintf(stdout, "open restore engine OK\n");
A
Andrew Kryczka 已提交
3058 3059 3060
    status = restore_engine->RestoreDBFromLatestBackup(db_path_, db_path_);
  }
  if (status.ok()) {
3061
    fprintf(stdout, "restore from backup OK\n");
A
Andrew Kryczka 已提交
3062 3063 3064 3065 3066 3067
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

// ----------------------------------------------------------------------------
3068 3069 3070

namespace {

3071 3072
void DumpSstFile(Options options, std::string filename, bool output_hex,
                 bool show_properties) {
3073 3074 3075 3076 3077 3078 3079 3080
  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
3081
  // TODO: add support for decoding blob indexes in ldb as well
3082 3083 3084
  ROCKSDB_NAMESPACE::SstFileDumper dumper(
      options, filename, /* verify_checksum */ false, output_hex,
      /* decode_blob_index */ false);
3085 3086
  Status st = dumper.ReadSequential(true, std::numeric_limits<uint64_t>::max(),
                                    false,            // has_from
3087 3088 3089 3090 3091 3092 3093 3094 3095
                                    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) {
3096
    const ROCKSDB_NAMESPACE::TableProperties* table_properties;
3097

3098
    std::shared_ptr<const ROCKSDB_NAMESPACE::TableProperties>
3099
        table_properties_from_reader;
3100
    st = dumper.ReadTableProperties(&table_properties_from_reader);
3101 3102 3103
    if (!st.ok()) {
      std::cerr << filename << ": " << st.ToString()
                << ". Try to use initial table properties" << std::endl;
3104
      table_properties = dumper.GetInitTableProperties();
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
    } 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

3117
DBFileDumperCommand::DBFileDumperCommand(
A
Andrew Kryczka 已提交
3118
    const std::vector<std::string>& /*params*/,
3119 3120
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
3121 3122
    : LDBCommand(options, flags, true, BuildCmdLineOptions({})) {}

3123
void DBFileDumperCommand::Help(std::string& ret) {
3124 3125 3126 3127 3128 3129 3130
  ret.append("  ");
  ret.append(DBFileDumperCommand::Name());
  ret.append("\n");
}

void DBFileDumperCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
3131
    assert(GetExecuteState().IsFailed());
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
    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);
3148
  std::string manifest_filepath = db_->GetName() + "/" + manifest_filename;
3149
  std::cout << manifest_filepath << std::endl;
3150
  DumpManifestFile(options_, manifest_filepath, false, false, false);
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
  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;
3161
    DumpSstFile(options_, filename, false, true);
3162 3163 3164 3165 3166 3167
    std::cout << std::endl;
  }
  std::cout << std::endl;

  std::cout << "Write Ahead Log Files" << std::endl;
  std::cout << "==============================" << std::endl;
3168
  ROCKSDB_NAMESPACE::VectorLogPtr wal_files;
3169 3170 3171 3172 3173 3174 3175 3176
  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;
3177
      // TODO(myabandeh): allow configuring is_write_commited
3178
      DumpWalFile(options_, filename, true, true, true /* is_write_commited */,
3179
                  &exec_state_);
3180 3181 3182 3183
    }
  }
}

Y
Yanqin Jin 已提交
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 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 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381
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_);
}

Options WriteExternalSstFilesCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
  opt.create_if_missing = create_if_missing_;
  return opt;
}

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

Options IngestExternalSstFilesCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
  opt.create_if_missing = create_if_missing_;
  return opt;
}

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

  DBImpl* db_impl = static_cast_with_check<DBImpl, DB>(db_->GetRootDB());

  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());
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
  }
}

3433
}  // namespace ROCKSDB_NAMESPACE
I
Igor Canadi 已提交
3434
#endif  // ROCKSDB_LITE