ldb_cmd.cc 142.3 KB
Newer Older
1

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

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

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

52
namespace ROCKSDB_NAMESPACE {
53

54 55
class FileChecksumGenCrc32c;
class FileChecksumGenCrc32cFactory;
56

57
const std::string LDBCommand::ARG_ENV_URI = "env_uri";
58
const std::string LDBCommand::ARG_FS_URI = "fs_uri";
59 60
const std::string LDBCommand::ARG_DB = "db";
const std::string LDBCommand::ARG_PATH = "path";
61
const std::string LDBCommand::ARG_SECONDARY_PATH = "secondary_path";
62 63 64 65 66 67 68 69
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";
70
const std::string LDBCommand::ARG_TRY_LOAD_OPTIONS = "try_load_options";
S
sdong 已提交
71 72
const std::string LDBCommand::ARG_DISABLE_CONSISTENCY_CHECKS =
    "disable_consistency_checks";
73 74
const std::string LDBCommand::ARG_IGNORE_UNKNOWN_OPTIONS =
    "ignore_unknown_options";
75 76 77 78 79 80 81
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 =
82
    "compression_max_dict_bytes";
83 84 85 86 87 88 89
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";
90 91 92 93 94 95 96 97 98 99 100 101 102
const std::string LDBCommand::ARG_ENABLE_BLOB_FILES = "enable_blob_files";
const std::string LDBCommand::ARG_MIN_BLOB_SIZE = "min_blob_size";
const std::string LDBCommand::ARG_BLOB_FILE_SIZE = "blob_file_size";
const std::string LDBCommand::ARG_BLOB_COMPRESSION_TYPE =
    "blob_compression_type";
const std::string LDBCommand::ARG_ENABLE_BLOB_GARBAGE_COLLECTION =
    "enable_blob_garbage_collection";
const std::string LDBCommand::ARG_BLOB_GARBAGE_COLLECTION_AGE_CUTOFF =
    "blob_garbage_collection_age_cutoff";
const std::string LDBCommand::ARG_BLOB_GARBAGE_COLLECTION_FORCE_THRESHOLD =
    "blob_garbage_collection_force_threshold";
const std::string LDBCommand::ARG_BLOB_COMPACTION_READAHEAD_SIZE =
    "blob_compaction_readahead_size";
103
const std::string LDBCommand::ARG_DECODE_BLOB_INDEX = "decode_blob_index";
104 105
const std::string LDBCommand::ARG_DUMP_UNCOMPRESSED_BLOBS =
    "dump_uncompressed_blobs";
106

107
const char* LDBCommand::DELIM = " ==> ";
108

109 110
namespace {

111 112 113
void DumpWalFile(Options options, std::string wal_file, bool print_header,
                 bool print_values, bool is_write_committed,
                 LDBCommandExecuteResult* exec_state);
114

115
void DumpSstFile(Options options, std::string filename, bool output_hex,
116
                 bool show_properties, bool decode_blob_index);
117 118 119

void DumpBlobFile(const std::string& filename, bool is_key_hex,
                  bool is_value_hex, bool dump_uncompressed_blobs);
120 121
};

122
LDBCommand* LDBCommand::InitFromCmdLineArgs(
123
    int argc, char const* const* argv, const Options& options,
S
sdong 已提交
124 125
    const LDBOptions& ldb_options,
    const std::vector<ColumnFamilyDescriptor>* column_families) {
126
  std::vector<std::string> args;
127 128 129
  for (int i = 1; i < argc; i++) {
    args.push_back(argv[i]);
  }
A
Arun Sharma 已提交
130 131
  return InitFromCmdLineArgs(args, options, ldb_options, column_families,
                             SelectCommand);
132 133 134 135 136 137
}

/**
 * Parse the command-line arguments and create the appropriate LDBCommand2
 * instance.
 * The command line arguments must be in the following format:
138 139
 * ./ldb --db=PATH_TO_DB [--commonOpt1=commonOpt1Val] ..
 *        COMMAND <PARAM1> <PARAM2> ... [-cmdSpecificOpt1=cmdSpecificOpt1Val] ..
140 141
 * This is similar to the command line format used by HBaseClientTool.
 * Command name is not included in args.
142
 * Returns nullptr if the command-line cannot be parsed.
143
 */
144
LDBCommand* LDBCommand::InitFromCmdLineArgs(
145
    const std::vector<std::string>& args, const Options& options,
S
sdong 已提交
146
    const LDBOptions& ldb_options,
A
Andrew Kryczka 已提交
147
    const std::vector<ColumnFamilyDescriptor>* /*column_families*/,
148 149 150 151 152 153 154
    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;
155

156
  // Everything other than option_map and flags. Represents commands
157
  // and their parameters.  For eg: put key1 value1 go into this vector.
158
  std::vector<std::string> cmdTokens;
159

160
  const std::string OPTION_PREFIX = "--";
161

162
  for (const auto& arg : args) {
163
    if (arg[0] == '-' && arg[1] == '-'){
164
      std::vector<std::string> splits = StringSplit(arg, '=');
165
      // --option_name=option_value
166
      if (splits.size() == 2) {
167
        std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
168
        parsed_params.option_map[optionKey] = splits[1];
169 170
      } else if (splits.size() == 1) {
        // --flag_name
171
        std::string optionKey = splits[0].substr(OPTION_PREFIX.size());
172
        parsed_params.flags.push_back(optionKey);
173 174 175 176 177
      } 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);
178
      }
179
    } else {
180
      cmdTokens.push_back(arg);
181 182 183 184 185
    }
  }

  if (cmdTokens.size() < 1) {
    fprintf(stderr, "Command not specified!");
186
    return nullptr;
187 188
  }

189 190 191 192
  parsed_params.cmd = cmdTokens[0];
  parsed_params.cmd_params.assign(cmdTokens.begin() + 1, cmdTokens.end());

  LDBCommand* command = selector(parsed_params);
193 194

  if (command) {
195 196
    command->SetDBOptions(options);
    command->SetLDBOptions(ldb_options);
197 198 199 200
  }
  return command;
}

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
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 已提交
217 218 219 220
  } else if (parsed_params.cmd == DeleteRangeCommand::Name()) {
    return new DeleteRangeCommand(parsed_params.cmd_params,
                                  parsed_params.option_map,
                                  parsed_params.flags);
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
  } 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);
251 252 253 254
  } else if (parsed_params.cmd == FileChecksumDumpCommand::Name()) {
    return new FileChecksumDumpCommand(parsed_params.cmd_params,
                                       parsed_params.option_map,
                                       parsed_params.flags);
255 256 257 258
  } else if (parsed_params.cmd == GetPropertyCommand::Name()) {
    return new GetPropertyCommand(parsed_params.cmd_params,
                                  parsed_params.option_map,
                                  parsed_params.flags);
259 260 261 262 263 264 265 266
  } 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);
267 268
  } else if (parsed_params.cmd == DropColumnFamilyCommand::Name()) {
    return new DropColumnFamilyCommand(parsed_params.cmd_params,
269 270
                                       parsed_params.option_map,
                                       parsed_params.flags);
271 272 273 274
  } else if (parsed_params.cmd == DBFileDumperCommand::Name()) {
    return new DBFileDumperCommand(parsed_params.cmd_params,
                                   parsed_params.option_map,
                                   parsed_params.flags);
275 276 277 278
  } else if (parsed_params.cmd == DBLiveFilesMetadataDumperCommand::Name()) {
    return new DBLiveFilesMetadataDumperCommand(parsed_params.cmd_params,
                                                parsed_params.option_map,
                                                parsed_params.flags);
279 280 281 282 283 284 285 286
  } 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 已提交
287 288 289 290
  } else if (parsed_params.cmd == CheckPointCommand::Name()) {
    return new CheckPointCommand(parsed_params.cmd_params,
                                 parsed_params.option_map,
                                 parsed_params.flags);
291 292 293
  } else if (parsed_params.cmd == RepairCommand::Name()) {
    return new RepairCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
W
Wanning Jiang 已提交
294 295 296
  } else if (parsed_params.cmd == BackupCommand::Name()) {
    return new BackupCommand(parsed_params.cmd_params, parsed_params.option_map,
                             parsed_params.flags);
A
Andrew Kryczka 已提交
297 298 299
  } else if (parsed_params.cmd == RestoreCommand::Name()) {
    return new RestoreCommand(parsed_params.cmd_params,
                              parsed_params.option_map, parsed_params.flags);
Y
Yanqin Jin 已提交
300 301 302 303 304 305 306 307
  } 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);
308 309 310
  } else if (parsed_params.cmd == ListFileRangeDeletesCommand::Name()) {
    return new ListFileRangeDeletesCommand(parsed_params.option_map,
                                           parsed_params.flags);
311 312 313 314
  } else if (parsed_params.cmd == UnsafeRemoveSstFileCommand::Name()) {
    return new UnsafeRemoveSstFileCommand(parsed_params.cmd_params,
                                          parsed_params.option_map,
                                          parsed_params.flags);
315 316 317 318
  } else if (parsed_params.cmd == UpdateManifestCommand::Name()) {
    return new UpdateManifestCommand(parsed_params.cmd_params,
                                     parsed_params.option_map,
                                     parsed_params.flags);
319
  }
320
  return nullptr;
321 322
}

A
Arun Sharma 已提交
323 324 325 326 327 328
/* Run the command, and return the execute result. */
void LDBCommand::Run() {
  if (!exec_state_.IsNotStarted()) {
    return;
  }

329 330
  if (!options_.env || options_.env == Env::Default()) {
    Env* env = Env::Default();
331 332 333 334 335
    Status s = Env::CreateFromUri(config_options_, env_uri_, fs_uri_, &env,
                                  &env_guard_);
    if (!s.ok()) {
      fprintf(stderr, "%s\n", s.ToString().c_str());
      exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
336 337 338 339 340
      return;
    }
    options_.env = env;
  }

A
Arun Sharma 已提交
341 342
  if (db_ == nullptr && !NoDBOpen()) {
    OpenDB();
343 344 345 346 347 348
    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 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
  }

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

364 365 366
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 已提交
367
    : db_(nullptr),
P
Prashant D 已提交
368
      db_ttl_(nullptr),
A
Arun Sharma 已提交
369 370 371 372 373
      is_read_only_(is_read_only),
      is_key_hex_(false),
      is_value_hex_(false),
      is_db_ttl_(false),
      timestamp_(false),
374 375
      try_load_options_(false),
      create_if_missing_(false),
A
Arun Sharma 已提交
376 377 378
      option_map_(options),
      flags_(flags),
      valid_cmd_line_options_(valid_cmd_line_options) {
379
  auto itr = options.find(ARG_DB);
A
Arun Sharma 已提交
380 381 382 383
  if (itr != options.end()) {
    db_path_ = itr->second;
  }

384 385 386 387 388
  itr = options.find(ARG_ENV_URI);
  if (itr != options.end()) {
    env_uri_ = itr->second;
  }

389 390 391 392 393
  itr = options.find(ARG_FS_URI);
  if (itr != options.end()) {
    fs_uri_ = itr->second;
  }

A
Arun Sharma 已提交
394 395 396 397 398 399 400
  itr = options.find(ARG_CF_NAME);
  if (itr != options.end()) {
    column_family_name_ = itr->second;
  } else {
    column_family_name_ = kDefaultColumnFamilyName;
  }

401 402 403 404 405 406
  itr = options.find(ARG_SECONDARY_PATH);
  secondary_path_ = "";
  if (itr != options.end()) {
    secondary_path_ = itr->second;
  }

A
Arun Sharma 已提交
407 408 409 410
  is_key_hex_ = IsKeyHex(options, flags);
  is_value_hex_ = IsValueHex(options, flags);
  is_db_ttl_ = IsFlagPresent(flags, ARG_TTL);
  timestamp_ = IsFlagPresent(flags, ARG_TIMESTAMP);
411
  try_load_options_ = IsFlagPresent(flags, ARG_TRY_LOAD_OPTIONS);
S
sdong 已提交
412 413
  force_consistency_checks_ =
      !IsFlagPresent(flags, ARG_DISABLE_CONSISTENCY_CHECKS);
414 415 416
  enable_blob_files_ = IsFlagPresent(flags, ARG_ENABLE_BLOB_FILES);
  enable_blob_garbage_collection_ =
      IsFlagPresent(flags, ARG_ENABLE_BLOB_GARBAGE_COLLECTION);
417 418
  config_options_.ignore_unknown_options =
      IsFlagPresent(flags, ARG_IGNORE_UNKNOWN_OPTIONS);
A
Arun Sharma 已提交
419 420 421
}

void LDBCommand::OpenDB() {
422
  PrepareOptions();
A
Arun Sharma 已提交
423 424 425
  if (!exec_state_.IsNotStarted()) {
    return;
  }
426 427 428 429
  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 已提交
430 431 432 433 434 435 436 437 438
  // 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");
    }
439 440 441 442
    if (!secondary_path_.empty()) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Open as secondary is not supported for TTL DB yet.");
    }
A
Arun Sharma 已提交
443
    if (is_read_only_) {
A
Andrew Kryczka 已提交
444
      st = DBWithTTL::Open(options_, db_path_, &db_ttl_, 0, true);
A
Arun Sharma 已提交
445
    } else {
A
Andrew Kryczka 已提交
446
      st = DBWithTTL::Open(options_, db_path_, &db_ttl_);
A
Arun Sharma 已提交
447 448 449
    }
    db_ = db_ttl_;
  } else {
450
    if (is_read_only_ && secondary_path_.empty()) {
A
Arun Sharma 已提交
451
      if (column_families_.empty()) {
A
Andrew Kryczka 已提交
452
        st = DB::OpenForReadOnly(options_, db_path_, &db_);
A
Arun Sharma 已提交
453
      } else {
A
Andrew Kryczka 已提交
454
        st = DB::OpenForReadOnly(options_, db_path_, column_families_,
A
Arun Sharma 已提交
455 456 457 458
                                 &handles_opened, &db_);
      }
    } else {
      if (column_families_.empty()) {
459 460 461 462 463
        if (secondary_path_.empty()) {
          st = DB::Open(options_, db_path_, &db_);
        } else {
          st = DB::OpenAsSecondary(options_, db_path_, secondary_path_, &db_);
        }
A
Arun Sharma 已提交
464
      } else {
465 466 467 468 469 470 471
        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 已提交
472 473 474 475
      }
    }
  }
  if (!st.ok()) {
476
    std::string msg = st.ToString();
A
Arun Sharma 已提交
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 515 516 517 518 519 520 521 522 523 524 525
    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();
}

526 527
std::vector<std::string> LDBCommand::BuildCmdLineOptions(
    std::vector<std::string> options) {
528
  std::vector<std::string> ret = {ARG_ENV_URI,
529
                                  ARG_FS_URI,
530
                                  ARG_DB,
531
                                  ARG_SECONDARY_PATH,
532 533 534 535 536 537 538 539
                                  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,
540
                                  ARG_TRY_LOAD_OPTIONS,
S
sdong 已提交
541
                                  ARG_DISABLE_CONSISTENCY_CHECKS,
542 543 544 545 546 547 548 549
                                  ARG_ENABLE_BLOB_FILES,
                                  ARG_MIN_BLOB_SIZE,
                                  ARG_BLOB_FILE_SIZE,
                                  ARG_BLOB_COMPRESSION_TYPE,
                                  ARG_ENABLE_BLOB_GARBAGE_COLLECTION,
                                  ARG_BLOB_GARBAGE_COLLECTION_AGE_CUTOFF,
                                  ARG_BLOB_GARBAGE_COLLECTION_FORCE_THRESHOLD,
                                  ARG_BLOB_COMPACTION_READAHEAD_SIZE,
550
                                  ARG_IGNORE_UNKNOWN_OPTIONS,
551
                                  ARG_CF_NAME};
A
Arun Sharma 已提交
552 553 554
  ret.insert(ret.end(), options.begin(), options.end());
  return ret;
}
555

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
/**
 * Parses the specific double 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.
 */
bool LDBCommand::ParseDoubleOption(
    const std::map<std::string, std::string>& /*options*/,
    const std::string& option, double& value,
    LDBCommandExecuteResult& exec_state) {
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
#if defined(CYGWIN)
    char* str_end = nullptr;
    value = std::strtod(itr->second.c_str(), &str_end);
    if (str_end == itr->second.c_str()) {
      exec_state =
          LDBCommandExecuteResult::Failed(option + " has an invalid value.");
    } else if (errno == ERANGE) {
      exec_state = LDBCommandExecuteResult::Failed(
          option + " has a value out-of-range.");
    } else {
      return true;
    }
#else
    try {
      value = std::stod(itr->second);
      return true;
    } catch (const std::invalid_argument&) {
      exec_state =
          LDBCommandExecuteResult::Failed(option + " has an invalid value.");
    } catch (const std::out_of_range&) {
      exec_state = LDBCommandExecuteResult::Failed(
          option + " has a value out-of-range.");
    }
#endif
  }
  return false;
}

597 598 599 600 601 602 603
/**
 * 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.
 */
604
bool LDBCommand::ParseIntOption(
A
Andrew Kryczka 已提交
605
    const std::map<std::string, std::string>& /*options*/,
606 607
    const std::string& option, int& value,
    LDBCommandExecuteResult& exec_state) {
608
  auto itr = option_map_.find(option);
609
  if (itr != option_map_.end()) {
S
sdong 已提交
610
#if defined(CYGWIN)
611 612 613 614 615 616 617 618 619 620 621
    char* str_end = nullptr;
    value = strtol(itr->second.c_str(), &str_end, 10);
    if (str_end == itr->second.c_str()) {
      exec_state =
          LDBCommandExecuteResult::Failed(option + " has an invalid value.");
    } else if (errno == ERANGE) {
      exec_state = LDBCommandExecuteResult::Failed(
          option + " has a value out-of-range.");
    } else {
      return true;
    }
S
sdong 已提交
622
#else
623
    try {
624
      value = std::stoi(itr->second);
625
      return true;
626
    } catch (const std::invalid_argument&) {
627 628
      exec_state =
          LDBCommandExecuteResult::Failed(option + " has an invalid value.");
629
    } catch (const std::out_of_range&) {
630 631
      exec_state = LDBCommandExecuteResult::Failed(
          option + " has a value out-of-range.");
632
    }
633
#endif
634
  }
635
  return false;
636 637
}

638 639 640 641 642
/**
 * Parses the specified option and fills in the value.
 * Returns true if the option is found.
 * Returns false otherwise.
 */
643
bool LDBCommand::ParseStringOption(
A
Andrew Kryczka 已提交
644
    const std::map<std::string, std::string>& /*options*/,
645
    const std::string& option, std::string* value) {
646 647 648 649 650 651 652 653
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
    *value = itr->second;
    return true;
  }
  return false;
}

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
/**
 * Parses the specified compression type and fills in the value.
 * Returns true if the compression type is found.
 * Returns false otherwise.
 */
bool LDBCommand::ParseCompressionTypeOption(
    const std::map<std::string, std::string>& /*options*/,
    const std::string& option, CompressionType& value,
    LDBCommandExecuteResult& exec_state) {
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
    const std::string& comp = itr->second;
    if (comp == "no") {
      value = kNoCompression;
      return true;
    } else if (comp == "snappy") {
      value = kSnappyCompression;
      return true;
    } else if (comp == "zlib") {
      value = kZlibCompression;
      return true;
    } else if (comp == "bzip2") {
      value = kBZip2Compression;
      return true;
    } else if (comp == "lz4") {
      value = kLZ4Compression;
      return true;
    } else if (comp == "lz4hc") {
      value = kLZ4HCCompression;
      return true;
    } else if (comp == "xpress") {
      value = kXpressCompression;
      return true;
    } else if (comp == "zstd") {
      value = kZSTD;
      return true;
    } else {
      // Unknown compression.
      exec_state = LDBCommandExecuteResult::Failed(
          "Unknown compression algorithm: " + comp);
    }
  }
  return false;
}

699 700
void LDBCommand::OverrideBaseOptions() {
  options_.create_if_missing = false;
701

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
  int db_write_buffer_size;
  if (ParseIntOption(option_map_, ARG_DB_WRITE_BUFFER_SIZE,
                     db_write_buffer_size, exec_state_)) {
    if (db_write_buffer_size >= 0) {
      options_.db_write_buffer_size = db_write_buffer_size;
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_DB_WRITE_BUFFER_SIZE +
                                                    " must be >= 0.");
    }
  }

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

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

void LDBCommand::OverrideBaseCFOptions(ColumnFamilyOptions* cf_opts) {
722
  BlockBasedTableOptions table_options;
S
sdong 已提交
723
  bool use_table_options = false;
724
  int bits;
725
  if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
726
    if (bits > 0) {
S
sdong 已提交
727
      use_table_options = true;
728
      table_options.filter_policy.reset(NewBloomFilterPolicy(bits));
729
    } else {
730 731
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOOM_BITS + " must be > 0.");
732 733 734 735
    }
  }

  int block_size;
736
  if (ParseIntOption(option_map_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
737
    if (block_size > 0) {
S
sdong 已提交
738
      use_table_options = true;
739
      table_options.block_size = block_size;
740
    } else {
741 742
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOCK_SIZE + " must be > 0.");
743 744 745
    }
  }

746
  cf_opts->force_consistency_checks = force_consistency_checks_;
S
sdong 已提交
747
  if (use_table_options) {
748
    cf_opts->table_factory.reset(NewBlockBasedTableFactory(table_options));
S
sdong 已提交
749 750
  }

751 752 753 754 755 756 757 758 759 760 761
  cf_opts->enable_blob_files = enable_blob_files_;

  int min_blob_size;
  if (ParseIntOption(option_map_, ARG_MIN_BLOB_SIZE, min_blob_size,
                     exec_state_)) {
    if (min_blob_size >= 0) {
      cf_opts->min_blob_size = min_blob_size;
    } else {
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_MIN_BLOB_SIZE + " must be >= 0.");
    }
762 763
  }

764 765 766 767 768
  int blob_file_size;
  if (ParseIntOption(option_map_, ARG_BLOB_FILE_SIZE, blob_file_size,
                     exec_state_)) {
    if (blob_file_size > 0) {
      cf_opts->blob_file_size = blob_file_size;
769
    } else {
770
      exec_state_ =
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
          LDBCommandExecuteResult::Failed(ARG_BLOB_FILE_SIZE + " must be > 0.");
    }
  }

  cf_opts->enable_blob_garbage_collection = enable_blob_garbage_collection_;

  double blob_garbage_collection_age_cutoff;
  if (ParseDoubleOption(option_map_, ARG_BLOB_GARBAGE_COLLECTION_AGE_CUTOFF,
                        blob_garbage_collection_age_cutoff, exec_state_)) {
    if (blob_garbage_collection_age_cutoff >= 0 &&
        blob_garbage_collection_age_cutoff <= 1) {
      cf_opts->blob_garbage_collection_age_cutoff =
          blob_garbage_collection_age_cutoff;
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_BLOB_GARBAGE_COLLECTION_AGE_CUTOFF + " must be >= 0 and <= 1.");
    }
  }

  double blob_garbage_collection_force_threshold;
  if (ParseDoubleOption(option_map_,
                        ARG_BLOB_GARBAGE_COLLECTION_FORCE_THRESHOLD,
                        blob_garbage_collection_force_threshold, exec_state_)) {
    if (blob_garbage_collection_force_threshold >= 0 &&
        blob_garbage_collection_force_threshold <= 1) {
      cf_opts->blob_garbage_collection_force_threshold =
          blob_garbage_collection_force_threshold;
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_BLOB_GARBAGE_COLLECTION_FORCE_THRESHOLD +
          " must be >= 0 and <= 1.");
    }
  }

  int blob_compaction_readahead_size;
  if (ParseIntOption(option_map_, ARG_BLOB_COMPACTION_READAHEAD_SIZE,
                     blob_compaction_readahead_size, exec_state_)) {
    if (blob_compaction_readahead_size > 0) {
      cf_opts->blob_compaction_readahead_size = blob_compaction_readahead_size;
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_BLOB_COMPACTION_READAHEAD_SIZE + " must be > 0.");
813 814 815
    }
  }

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
  auto itr = option_map_.find(ARG_AUTO_COMPACTION);
  if (itr != option_map_.end()) {
    cf_opts->disable_auto_compactions = !StringToBool(itr->second);
  }

  CompressionType compression_type;
  if (ParseCompressionTypeOption(option_map_, ARG_COMPRESSION_TYPE,
                                 compression_type, exec_state_)) {
    cf_opts->compression = compression_type;
  }

  CompressionType blob_compression_type;
  if (ParseCompressionTypeOption(option_map_, ARG_BLOB_COMPRESSION_TYPE,
                                 blob_compression_type, exec_state_)) {
    cf_opts->blob_compression_type = blob_compression_type;
  }

833 834 835 836
  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) {
837
      cf_opts->compression_opts.max_dict_bytes = compression_max_dict_bytes;
838 839 840 841 842 843
    } else {
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_COMPRESSION_MAX_DICT_BYTES + " must be >= 0.");
    }
  }

844
  int write_buffer_size;
845 846
  if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
        exec_state_)) {
847
    if (write_buffer_size > 0) {
848
      cf_opts->write_buffer_size = write_buffer_size;
849
    } else {
850
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_WRITE_BUFFER_SIZE +
851
                                                    " must be > 0.");
852 853 854 855
    }
  }

  int file_size;
856
  if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
857
    if (file_size > 0) {
858
      cf_opts->target_file_size_base = file_size;
859
    } else {
860 861
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_FILE_SIZE + " must be > 0.");
862 863 864
    }
  }

S
sdong 已提交
865
  int fix_prefix_len;
866 867
  if (ParseIntOption(option_map_, ARG_FIX_PREFIX_LEN, fix_prefix_len,
                     exec_state_)) {
S
sdong 已提交
868
    if (fix_prefix_len > 0) {
869
      cf_opts->prefix_extractor.reset(
S
sdong 已提交
870 871
          NewFixedPrefixTransform(static_cast<size_t>(fix_prefix_len)));
    } else {
872
      exec_state_ =
873
          LDBCommandExecuteResult::Failed(ARG_FIX_PREFIX_LEN + " must be > 0.");
S
sdong 已提交
874 875
    }
  }
876
}
877

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
// First, initializes the options state using the OPTIONS file when enabled.
// Second, overrides the options according to the CLI arguments and the
// specific subcommand being run.
void LDBCommand::PrepareOptions() {
  if (!create_if_missing_ && try_load_options_) {
    config_options_.env = options_.env;
    Status s = LoadLatestOptions(config_options_, db_path_, &options_,
                                 &column_families_);
    if (!s.ok() && !s.IsNotFound()) {
      // Option file exists but load option file error.
      std::string msg = s.ToString();
      exec_state_ = LDBCommandExecuteResult::Failed(msg);
      db_ = nullptr;
      return;
    }
893 894 895 896 897 898 899
    if (!options_.wal_dir.empty()) {
      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");
      }
900 901 902 903 904 905 906 907 908 909 910
    }

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

911 912 913 914
  if (options_.env == Env::Default()) {
    options_.env = config_options_.env;
  }

915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
  OverrideBaseOptions();
  if (exec_state_.IsFailed()) {
    return;
  }

  if (column_families_.empty()) {
    // Reads the MANIFEST to figure out what column families exist. In this
    // case, the option overrides from the CLI argument/specific subcommand
    // apply to all column families.
    std::vector<std::string> cf_list;
    Status st = DB::ListColumnFamilies(options_, db_path_, &cf_list);
    // It is possible the DB doesn't exist yet, for "create if not
    // existing" case. The failure is ignored here. We rely on DB::Open()
    // to give us the correct error message for problem with opening
    // existing DB.
    if (st.ok() && cf_list.size() > 1) {
      // Ignore single column family DB.
      for (auto cf_name : cf_list) {
        column_families_.emplace_back(cf_name, options_);
      }
    }
  } else {
    // We got column families from the OPTIONS file. In this case, the option
    // overrides from the CLI argument/specific subcommand only apply to the
    // column family specified by `--column_family_name`.
    auto column_families_iter =
        std::find_if(column_families_.begin(), column_families_.end(),
                     [this](const ColumnFamilyDescriptor& cf_desc) {
                       return cf_desc.name == column_family_name_;
                     });
    if (column_families_iter == column_families_.end()) {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Non-existing column family " + column_family_name_);
      return;
    }
950
    OverrideBaseCFOptions(&column_families_iter->options);
951
  }
952 953
}

954 955 956
bool LDBCommand::ParseKeyValue(const std::string& line, std::string* key,
                               std::string* value, bool is_key_hex,
                               bool is_value_hex) {
957
  size_t pos = line.find(DELIM);
958
  if (pos != std::string::npos) {
959 960 961 962 963 964 965 966 967 968 969 970 971
    *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;
  }
}
972

973 974 975 976 977 978 979 980
/**
 * 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() {
981
  for (auto itr = option_map_.begin(); itr != option_map_.end(); ++itr) {
982 983 984
    if (std::find(valid_cmd_line_options_.begin(),
                  valid_cmd_line_options_.end(),
                  itr->first) == valid_cmd_line_options_.end()) {
985 986 987 988
      fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
      return false;
    }
  }
989

990 991 992 993 994
  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()) {
995 996
      fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
      return false;
997 998 999
    }
  }

1000 1001 1002 1003
  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());
1004 1005 1006 1007 1008 1009
    return false;
  }

  return true;
}

1010 1011
std::string LDBCommand::HexToString(const std::string& str) {
  std::string result;
A
Arun Sharma 已提交
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
  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;
}

1023 1024
std::string LDBCommand::StringToHex(const std::string& str) {
  std::string result("0x");
A
Arun Sharma 已提交
1025 1026 1027 1028
  result.append(Slice(str).ToString(true));
  return result;
}

1029 1030 1031 1032
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 已提交
1033 1034 1035 1036 1037 1038
  result.append(is_key_hex ? StringToHex(key) : key);
  result.append(DELIM);
  result.append(is_value_hex ? StringToHex(value) : value);
  return result;
}

1039 1040
std::string LDBCommand::PrintKeyValue(const std::string& key,
                                      const std::string& value, bool is_hex) {
A
Arun Sharma 已提交
1041 1042 1043
  return PrintKeyValue(key, value, is_hex, is_hex);
}

1044
std::string LDBCommand::HelpRangeCmdArgs() {
A
Arun Sharma 已提交
1045 1046 1047 1048 1049 1050 1051
  std::ostringstream str_stream;
  str_stream << " ";
  str_stream << "[--" << ARG_FROM << "] ";
  str_stream << "[--" << ARG_TO << "] ";
  return str_stream.str();
}

1052 1053
bool LDBCommand::IsKeyHex(const std::map<std::string, std::string>& options,
                          const std::vector<std::string>& flags) {
A
Arun Sharma 已提交
1054 1055 1056 1057 1058
  return (IsFlagPresent(flags, ARG_HEX) || IsFlagPresent(flags, ARG_KEY_HEX) ||
          ParseBooleanOption(options, ARG_HEX, false) ||
          ParseBooleanOption(options, ARG_KEY_HEX, false));
}

1059 1060
bool LDBCommand::IsValueHex(const std::map<std::string, std::string>& options,
                            const std::vector<std::string>& flags) {
A
Arun Sharma 已提交
1061 1062 1063 1064 1065 1066
  return (IsFlagPresent(flags, ARG_HEX) ||
          IsFlagPresent(flags, ARG_VALUE_HEX) ||
          ParseBooleanOption(options, ARG_HEX, false) ||
          ParseBooleanOption(options, ARG_VALUE_HEX, false));
}

1067 1068 1069
bool LDBCommand::ParseBooleanOption(
    const std::map<std::string, std::string>& options,
    const std::string& option, bool default_val) {
1070
  auto itr = options.find(option);
A
Arun Sharma 已提交
1071
  if (itr != options.end()) {
1072
    std::string option_val = itr->second;
A
Arun Sharma 已提交
1073 1074 1075 1076 1077
    return StringToBool(itr->second);
  }
  return default_val;
}

1078
bool LDBCommand::StringToBool(std::string val) {
A
Arun Sharma 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  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";
  }
}

1091
CompactorCommand::CompactorCommand(
A
Andrew Kryczka 已提交
1092
    const std::vector<std::string>& /*params*/,
1093 1094 1095 1096 1097 1098 1099
    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) {
1100
  auto itr = options.find(ARG_FROM);
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  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_) {
1113 1114 1115 1116 1117 1118 1119 1120 1121
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

1122
void CompactorCommand::Help(std::string& ret) {
1123 1124 1125 1126
  ret.append("  ");
  ret.append(CompactorCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
1127 1128
}

1129
void CompactorCommand::DoCommand() {
S
sdong 已提交
1130 1131 1132 1133
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
1134

1135 1136
  Slice* begin = nullptr;
  Slice* end = nullptr;
1137
  if (!null_from_) {
1138
    begin = new Slice(from_);
1139 1140
  }
  if (!null_to_) {
1141
    end = new Slice(to_);
1142 1143
  }

1144
  CompactRangeOptions cro;
1145
  cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
1146

1147 1148 1149 1150 1151 1152 1153 1154
  Status s = db_->CompactRange(cro, GetCfHandle(), begin, end);
  if (!s.ok()) {
    std::stringstream oss;
    oss << "Compaction failed: " << s.ToString();
    exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  } else {
    exec_state_ = LDBCommandExecuteResult::Succeed("");
  }
1155 1156 1157 1158 1159

  delete begin;
  delete end;
}

1160
// ---------------------------------------------------------------------------
1161 1162 1163
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";
1164

1165
DBLoaderCommand::DBLoaderCommand(
A
Andrew Kryczka 已提交
1166
    const std::vector<std::string>& /*params*/,
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
    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) {
1177 1178
  create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
1179 1180
  bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  compact_ = IsFlagPresent(flags, ARG_COMPACT);
Z
Zheng Shao 已提交
1181 1182
}

1183
void DBLoaderCommand::Help(std::string& ret) {
1184 1185 1186 1187 1188 1189 1190
  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 已提交
1191 1192
}

1193 1194 1195
void DBLoaderCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
1196
  if (bulk_load_) {
1197
    options_.PrepareForBulkLoad();
1198
  }
Z
Zheng Shao 已提交
1199 1200
}

1201
void DBLoaderCommand::DoCommand() {
Z
Zheng Shao 已提交
1202
  if (!db_) {
S
sdong 已提交
1203
    assert(GetExecuteState().IsFailed());
Z
Zheng Shao 已提交
1204 1205 1206 1207 1208 1209 1210 1211 1212
    return;
  }

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

  int bad_lines = 0;
1213
  std::string line;
1214 1215 1216
  // 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;
1217 1218
  Status s;
  while (s.ok() && getline(*istream_p, line, '\n')) {
1219 1220
    std::string key;
    std::string value;
1221
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
1222
      s = db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
Z
Zheng Shao 已提交
1223 1224 1225 1226 1227 1228 1229 1230
    } 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 ++;
    }
  }
1231

Z
Zheng Shao 已提交
1232
  if (bad_lines > 0) {
1233
    std::cout << "Warning: " << bad_lines << " bad lines ignored." << std::endl;
Z
Zheng Shao 已提交
1234
  }
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
  if (!s.ok()) {
    std::stringstream oss;
    oss << "Load failed: " << s.ToString();
    exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  }
  if (compact_ && s.ok()) {
    s = db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr,
                          nullptr);
  }
  if (!s.ok()) {
    std::stringstream oss;
    oss << "Compaction failed: " << s.ToString();
    exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
1248
  }
Z
Zheng Shao 已提交
1249 1250
}

1251 1252
// ----------------------------------------------------------------------------

1253 1254
namespace {

1255 1256
void DumpManifestFile(Options options, std::string file, bool verbose, bool hex,
                      bool json) {
1257 1258
  EnvOptions sopt;
  std::string dbname("dummy");
1259 1260
  std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
                                        options.table_cache_numshardbits));
1261 1262 1263 1264
  // 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);
1265
  options.num_levels = 64;
S
sdong 已提交
1266
  WriteController wc(options.delayed_write_rate);
1267
  WriteBufferManager wb(options.db_write_buffer_size);
1268
  ImmutableDBOptions immutable_db_options(options);
1269
  VersionSet versions(dbname, &immutable_db_options, sopt, tc.get(), &wb, &wc,
1270 1271
                      /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr,
                      /*db_session_id*/ "");
1272
  Status s = versions.DumpManifest(options, file, verbose, hex, json);
1273
  if (!s.ok()) {
1274 1275
    fprintf(stderr, "Error in processing file %s %s\n", file.c_str(),
            s.ToString().c_str());
1276 1277 1278 1279 1280
  }
}

}  // namespace

1281 1282 1283
const std::string ManifestDumpCommand::ARG_VERBOSE = "verbose";
const std::string ManifestDumpCommand::ARG_JSON = "json";
const std::string ManifestDumpCommand::ARG_PATH = "path";
1284

1285
void ManifestDumpCommand::Help(std::string& ret) {
1286 1287 1288
  ret.append("  ");
  ret.append(ManifestDumpCommand::Name());
  ret.append(" [--" + ARG_VERBOSE + "]");
1289
  ret.append(" [--" + ARG_JSON + "]");
1290 1291
  ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  ret.append("\n");
1292 1293
}

1294
ManifestDumpCommand::ManifestDumpCommand(
A
Andrew Kryczka 已提交
1295
    const std::vector<std::string>& /*params*/,
1296 1297 1298 1299 1300 1301 1302 1303
    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_("") {
1304
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
1305
  json_ = IsFlagPresent(flags, ARG_JSON);
1306

1307
  auto itr = options.find(ARG_PATH);
1308 1309 1310
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
1311
      exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    }
  }
}

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

1326 1327 1328 1329 1330 1331 1332
    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);
1333 1334
      return;
    }
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    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;
1357
      FileType file_type = kWalFile;  // Just for initialization
1358 1359 1360
      if (ParseFileName(fname, &file_num, &file_type) &&
          file_type == kDescriptorFile) {
        if (!matched_file.empty()) {
1361
          exec_state_ = LDBCommandExecuteResult::Failed(
1362
              "Multiple MANIFEST files found; use --path to select one");
1363
          return;
1364 1365
        } else {
          matched_file.swap(fname);
1366 1367 1368
        }
      }
    }
1369 1370 1371 1372 1373 1374
    if (matched_file.empty()) {
      std::string err_msg("No MANIFEST found in ");
      err_msg.append(db_path_);
      exec_state_ = LDBCommandExecuteResult::Failed(err_msg);
      return;
    }
1375
    if (db_path_.back() != '/') {
1376 1377 1378
      db_path_.append("/");
    }
    manifestfile = db_path_ + matched_file;
1379 1380 1381
  }

  if (verbose_) {
1382
    fprintf(stdout, "Processing Manifest file %s\n", manifestfile.c_str());
1383 1384
  }

1385
  DumpManifestFile(options_, manifestfile, verbose_, is_key_hex_, json_);
1386

1387
  if (verbose_) {
1388
    fprintf(stdout, "Processing Manifest file %s done\n", manifestfile.c_str());
1389 1390 1391
  }
}

1392 1393 1394
// ----------------------------------------------------------------------------
namespace {

1395 1396 1397
Status GetLiveFilesChecksumInfoFromVersionSet(Options options,
                                              const std::string& db_path,
                                              FileChecksumList* checksum_list) {
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
  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,
1412 1413
                      /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr,
                      /*db_session_id*/ "");
1414 1415
  std::vector<std::string> cf_name_list;
  s = versions.ListColumnFamilies(&cf_name_list, db_path,
1416
                                  immutable_db_options.fs.get());
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
  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);
  }
1427
  return s;
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
}

}  // 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)
1445 1446
    : LDBCommand(options, flags, false,
                 BuildCmdLineOptions({ARG_PATH, ARG_HEX})),
1447
      path_("") {
1448
  auto itr = options.find(ARG_PATH);
1449 1450 1451 1452 1453 1454
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
      exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
    }
  }
1455
  is_checksum_hex_ = IsFlagPresent(flags, ARG_HEX);
1456 1457 1458 1459 1460 1461 1462 1463 1464
}

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());
1465 1466 1467
  Status s = GetLiveFilesChecksumInfoFromVersionSet(options_, db_path_,
                                                    checksum_list.get());
  if (s.ok() && checksum_list != nullptr) {
1468 1469 1470
    std::vector<uint64_t> file_numbers;
    std::vector<std::string> checksums;
    std::vector<std::string> checksum_func_names;
1471 1472
    s = checksum_list->GetAllFileChecksums(&file_numbers, &checksums,
                                           &checksum_func_names);
1473 1474 1475 1476 1477
    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());
1478 1479 1480 1481 1482 1483
        std::string checksum;
        if (is_checksum_hex_) {
          checksum = StringToHex(checksums[i]);
        } else {
          checksum = std::move(checksums[i]);
        }
1484
        fprintf(stdout, "%" PRId64 ", %s, %s\n", file_numbers[i],
1485
                checksum_func_names[i].c_str(), checksum.c_str());
1486
      }
1487
      fprintf(stdout, "Print SST file checksum information finished \n");
1488
    }
1489 1490 1491 1492
  }

  if (!s.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
1493 1494 1495
  }
}

1496
// ----------------------------------------------------------------------------
1497

1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
void GetPropertyCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(GetPropertyCommand::Name());
  ret.append(" <property_name>");
  ret.append("\n");
}

GetPropertyCommand::GetPropertyCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, true, BuildCmdLineOptions({})) {
  if (params.size() != 1) {
    exec_state_ =
        LDBCommandExecuteResult::Failed("property name must be specified");
  } else {
    property_ = params[0];
  }
}

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

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

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

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

1550
void ListColumnFamiliesCommand::Help(std::string& ret) {
1551 1552 1553
  ret.append("  ");
  ret.append(ListColumnFamiliesCommand::Name());
  ret.append("\n");
1554 1555 1556
}

ListColumnFamiliesCommand::ListColumnFamiliesCommand(
1557
    const std::vector<std::string>& /*params*/,
1558 1559
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1560
    : LDBCommand(options, flags, false, BuildCmdLineOptions({})) {}
1561 1562

void ListColumnFamiliesCommand::DoCommand() {
1563
  std::vector<std::string> column_families;
1564
  Status s = DB::ListColumnFamilies(options_, db_path_, &column_families);
1565
  if (!s.ok()) {
1566 1567
    fprintf(stderr, "Error in processing db %s %s\n", db_path_.c_str(),
            s.ToString().c_str());
1568
  } else {
1569
    fprintf(stdout, "Column families in %s: \n{", db_path_.c_str());
1570 1571 1572
    bool first = true;
    for (auto cf : column_families) {
      if (!first) {
1573
        fprintf(stdout, ", ");
1574 1575
      }
      first = false;
1576
      fprintf(stdout, "%s", cf.c_str());
1577
    }
1578
    fprintf(stdout, "}\n");
1579 1580 1581
  }
}

1582
void CreateColumnFamilyCommand::Help(std::string& ret) {
S
sdong 已提交
1583 1584 1585 1586 1587 1588 1589
  ret.append("  ");
  ret.append(CreateColumnFamilyCommand::Name());
  ret.append(" --db=<db_path> <new_column_family_name>");
  ret.append("\n");
}

CreateColumnFamilyCommand::CreateColumnFamilyCommand(
1590 1591 1592
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
S
sdong 已提交
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
    : 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() {
1603 1604 1605 1606
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
1607
  ColumnFamilyHandle* new_cf_handle = nullptr;
S
sdong 已提交
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
  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();
}

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
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)
1630
    : LDBCommand(options, flags, true, {ARG_DB}) {
1631 1632 1633 1634 1635 1636 1637 1638 1639
  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() {
1640 1641 1642 1643
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
  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();
}

1661
// ----------------------------------------------------------------------------
I
Igor Canadi 已提交
1662 1663
namespace {

1664 1665
// 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
1666 1667 1668
void IncBucketCounts(std::vector<uint64_t>& bucket_counts, int ttl_start,
                     int time_range, int bucket_size, int timekv,
                     int num_buckets) {
1669 1670 1671 1672
#ifdef NDEBUG
  (void)time_range;
  (void)num_buckets;
#endif
1673 1674 1675
  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;
1676
  bucket_counts[bucket]++;
1677 1678
}

1679 1680 1681
void PrintBucketCounts(const std::vector<uint64_t>& bucket_counts,
                       int ttl_start, int ttl_end, int bucket_size,
                       int num_buckets) {
1682
  int time_point = ttl_start;
1683 1684
  for(int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
    fprintf(stdout, "Keys in range %s to %s : %lu\n",
1685 1686
            TimeToHumanString(time_point).c_str(),
            TimeToHumanString(time_point + bucket_size).c_str(),
1687
            (unsigned long)bucket_counts[i]);
1688
  }
1689
  fprintf(stdout, "Keys in range %s to %s : %lu\n",
1690 1691
          TimeToHumanString(time_point).c_str(),
          TimeToHumanString(ttl_end).c_str(),
1692
          (unsigned long)bucket_counts[num_buckets - 1]);
1693 1694
}

I
Igor Canadi 已提交
1695 1696
}  // namespace

1697 1698 1699 1700
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";
1701

1702
InternalDumpCommand::InternalDumpCommand(
A
Andrew Kryczka 已提交
1703
    const std::vector<std::string>& /*params*/,
1704 1705
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1706 1707 1708 1709 1710
    : 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, ARG_DECODE_BLOB_INDEX})),
1711 1712 1713 1714 1715 1716 1717
      has_from_(false),
      has_to_(false),
      max_keys_(-1),
      delim_("."),
      count_only_(false),
      count_delim_(false),
      print_stats_(false),
1718 1719
      is_input_key_hex_(false),
      decode_blob_index_(false) {
1720 1721 1722
  has_from_ = ParseStringOption(options, ARG_FROM, &from_);
  has_to_ = ParseStringOption(options, ARG_TO, &to_);

1723
  ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
1724
  auto itr = options.find(ARG_COUNT_DELIM);
1725 1726 1727
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
1728
   // fprintf(stdout,"delim = %c\n",delim_[0]);
1729 1730
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
1731
    delim_=".";
1732
  }
1733 1734 1735

  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
1736
  is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
1737
  decode_blob_index_ = IsFlagPresent(flags, ARG_DECODE_BLOB_INDEX);
1738

1739
  if (is_input_key_hex_) {
1740 1741 1742 1743 1744 1745 1746 1747 1748
    if (has_from_) {
      from_ = HexToString(from_);
    }
    if (has_to_) {
      to_ = HexToString(to_);
    }
  }
}

1749
void InternalDumpCommand::Help(std::string& ret) {
1750 1751 1752 1753 1754 1755 1756 1757
  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 + "]");
1758
  ret.append(" [--" + ARG_DECODE_BLOB_INDEX + "]");
1759
  ret.append("\n");
1760 1761 1762 1763
}

void InternalDumpCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
1764
    assert(GetExecuteState().IsFailed());
1765 1766 1767 1768
    return;
  }

  if (print_stats_) {
1769
    std::string stats;
S
sdong 已提交
1770
    if (db_->GetProperty(GetCfHandle(), "rocksdb.stats", &stats)) {
1771 1772 1773 1774 1775
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Cast as DBImpl to get internal iterator
A
Andrew Kryczka 已提交
1776
  std::vector<KeyVersion> key_versions;
1777 1778
  Status st = GetAllKeyVersions(db_, GetCfHandle(), from_, to_, max_keys_,
                                &key_versions);
A
Andrew Kryczka 已提交
1779 1780
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1781 1782
    return;
  }
1783
  std::string rtype1, rtype2, row, val;
1784
  rtype2 = "";
1785 1786
  uint64_t c=0;
  uint64_t s1=0,s2=0;
1787

1788
  long long count = 0;
A
Andrew Kryczka 已提交
1789
  for (auto& key_version : key_versions) {
1790 1791
    ValueType value_type = static_cast<ValueType>(key_version.type);
    InternalKey ikey(key_version.user_key, key_version.sequence, value_type);
A
Andrew Kryczka 已提交
1792 1793 1794
    if (has_to_ && ikey.user_key() == to_) {
      // GetAllKeyVersions() includes keys with user key `to_`, but idump has
      // traditionally excluded such keys.
1795 1796 1797
      break;
    }
    ++count;
1798 1799 1800
    int k;
    if (count_delim_) {
      rtype1 = "";
1801
      s1=0;
A
Andrew Kryczka 已提交
1802 1803
      row = ikey.Encode().ToString();
      val = key_version.value;
1804
      for(k=0;row[k]!='\x01' && row[k]!='\0';k++)
1805
        s1++;
1806
      for(k=0;val[k]!='\x01' && val[k]!='\0';k++)
1807
        s1++;
1808 1809 1810
      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) {
1811 1812
        fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
                rtype2.c_str(), c, s2);
1813 1814
        c=1;
        s2=s1;
1815 1816 1817
        rtype2 = rtype1;
      } else {
        c++;
1818 1819
        s2+=s1;
        rtype2=rtype1;
A
Andrew Kryczka 已提交
1820
      }
1821
    }
1822

1823
    if (!count_only_ && !count_delim_) {
1824
      std::string key = ikey.DebugString(is_key_hex_);
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
      Slice value(key_version.value);
      if (!decode_blob_index_ || value_type != kTypeBlobIndex) {
        fprintf(stdout, "%s => %s\n", key.c_str(),
                value.ToString(is_value_hex_).c_str());
      } else {
        BlobIndex blob_index;

        const Status s = blob_index.DecodeFrom(value);
        if (!s.ok()) {
          fprintf(stderr, "%s => error decoding blob index =>\n", key.c_str());
        } else {
          fprintf(stdout, "%s => %s\n", key.c_str(),
                  blob_index.DebugString(is_value_hex_).c_str());
        }
      }
1840 1841 1842
    }

    // Terminate if maximum number of keys have been dumped
1843
    if (max_keys_ > 0 && count >= max_keys_) break;
1844
  }
1845
  if(count_delim_) {
1846 1847 1848 1849 1850
    fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
            rtype2.c_str(), c, s2);
  } else {
    fprintf(stdout, "Internal keys in range: %lld\n", count);
  }
1851 1852
}

1853 1854 1855 1856
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";
1857

1858
DBDumperCommand::DBDumperCommand(
A
Andrew Kryczka 已提交
1859
    const std::vector<std::string>& /*params*/,
1860 1861
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
1862 1863 1864 1865 1866 1867 1868
    : 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, ARG_DECODE_BLOB_INDEX, ARG_DUMP_UNCOMPRESSED_BLOBS})),
1869 1870 1871 1872 1873
      null_from_(true),
      null_to_(true),
      max_keys_(-1),
      count_only_(false),
      count_delim_(false),
1874 1875
      print_stats_(false),
      decode_blob_index_(false) {
1876
  auto itr = options.find(ARG_FROM);
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
  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 已提交
1891 1892 1893
#if defined(CYGWIN)
      max_keys_ = strtol(itr->second.c_str(), 0, 10);
#else
1894
      max_keys_ = std::stoi(itr->second);
S
sdong 已提交
1895
#endif
1896
    } catch (const std::invalid_argument&) {
1897
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
1898
                                                    " has an invalid value");
1899
    } catch (const std::out_of_range&) {
1900 1901
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
1902 1903
    }
  }
1904 1905 1906 1907 1908 1909
  itr = options.find(ARG_COUNT_DELIM);
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
1910
    delim_=".";
1911
  }
1912

1913 1914
  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
1915
  decode_blob_index_ = IsFlagPresent(flags, ARG_DECODE_BLOB_INDEX);
1916
  dump_uncompressed_blobs_ = IsFlagPresent(flags, ARG_DUMP_UNCOMPRESSED_BLOBS);
1917 1918

  if (is_key_hex_) {
1919 1920 1921 1922 1923 1924 1925
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
1926 1927 1928 1929

  itr = options.find(ARG_PATH);
  if (itr != options.end()) {
    path_ = itr->second;
1930 1931 1932
    if (db_path_.empty()) {
      db_path_ = path_;
    }
1933
  }
1934 1935
}

1936
void DBDumperCommand::Help(std::string& ret) {
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
  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]");
1949
  ret.append(" [--" + ARG_PATH + "=<path_to_a_file>]");
1950
  ret.append(" [--" + ARG_DECODE_BLOB_INDEX + "]");
1951
  ret.append(" [--" + ARG_DUMP_UNCOMPRESSED_BLOBS + "]");
1952
  ret.append("\n");
1953 1954
}

1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
/**
 * 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.
 *
 */
1966
void DBDumperCommand::DoCommand() {
1967
  if (!db_) {
1968
    assert(!path_.empty());
1969
    std::string fileName = GetFileNameFromPath(path_);
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
    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) {
1982
      case kWalFile:
1983
        // TODO(myabandeh): allow configuring is_write_commited
1984 1985 1986
        DumpWalFile(options_, path_, /* print_header_ */ true,
                    /* print_values_ */ true, true /* is_write_commited */,
                    &exec_state_);
1987 1988
        break;
      case kTableFile:
1989
        DumpSstFile(options_, path_, is_key_hex_, /* show_properties */ true,
1990
                    decode_blob_index_);
1991 1992
        break;
      case kDescriptorFile:
1993
        DumpManifestFile(options_, path_, /* verbose_ */ false, is_key_hex_,
1994 1995
                         /*  json_ */ false);
        break;
1996 1997 1998 1999
      case kBlobFile:
        DumpBlobFile(path_, is_key_hex_, is_value_hex_,
                     dump_uncompressed_blobs_);
        break;
2000 2001 2002 2003 2004 2005 2006 2007
      default:
        exec_state_ = LDBCommandExecuteResult::Failed(
            "File type not supported: " + path_);
        break;
    }

  } else {
    DoDumpCommand();
2008
  }
2009 2010 2011 2012 2013 2014
}

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

2015 2016 2017
  // Parse command line args
  uint64_t count = 0;
  if (print_stats_) {
2018
    std::string stats;
2019
    if (db_->GetProperty("rocksdb.stats", &stats)) {
2020 2021 2022 2023 2024
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Setup key iterator
2025 2026 2027
  ReadOptions scan_read_opts;
  scan_read_opts.total_order_seek = true;
  Iterator* iter = db_->NewIterator(scan_read_opts, GetCfHandle());
2028
  Status st = iter->status();
2029
  if (!st.ok()) {
2030 2031
    exec_state_ =
        LDBCommandExecuteResult::Failed("Iterator error." + st.ToString());
2032 2033 2034 2035 2036 2037 2038 2039 2040
  }

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

  int max_keys = max_keys_;
2041
  int ttl_start;
2042
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
2043
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
2044 2045
  }
  int ttl_end;
2046
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
2047
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
2048 2049 2050 2051 2052 2053 2054 2055
  }
  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;
2056
  if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
2057 2058 2059
      bucket_size <= 0) {
    bucket_size = time_range; // Will have just 1 bucket by default
  }
2060
  //cretaing variables for row count of each type
2061
  std::string rtype1, rtype2, row, val;
2062
  rtype2 = "";
2063 2064
  uint64_t c=0;
  uint64_t s1=0,s2=0;
2065

2066
  // At this point, bucket_size=0 => time_range=0
2067 2068 2069
  int num_buckets = (bucket_size >= time_range)
                        ? 1
                        : ((time_range + bucket_size - 1) / bucket_size);
2070
  std::vector<uint64_t> bucket_counts(num_buckets, 0);
2071
  if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
2072
    fprintf(stdout, "Dumping key-values from %s to %s\n",
2073 2074
            TimeToHumanString(ttl_start).c_str(),
            TimeToHumanString(ttl_end).c_str());
2075 2076
  }

2077 2078
  HistogramImpl vsize_hist;

2079
  for (; iter->Valid(); iter->Next()) {
2080
    int rawtime = 0;
2081 2082 2083 2084 2085 2086
    // 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;
2087
    if (is_db_ttl_) {
2088
      TtlIterator* it_ttl = static_cast_with_check<TtlIterator>(iter);
Y
Yanqin Jin 已提交
2089
      rawtime = it_ttl->ttl_timestamp();
2090
      if (rawtime < ttl_start || rawtime >= ttl_end) {
2091 2092 2093
        continue;
      }
    }
2094 2095 2096
    if (max_keys > 0) {
      --max_keys;
    }
2097
    if (is_db_ttl_ && num_buckets > 1) {
2098
      IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
2099 2100
                      rawtime, num_buckets);
    }
2101
    ++count;
2102 2103 2104 2105 2106
    if (count_delim_) {
      rtype1 = "";
      row = iter->key().ToString();
      val = iter->value().ToString();
      s1 = row.size()+val.size();
2107 2108 2109
      for(int j=0;row[j]!=delim_[0] && row[j]!='\0';j++)
        rtype1+=row[j];
      if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
2110 2111
        fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
                rtype2.c_str(), c, s2);
2112 2113
        c=1;
        s2=s1;
2114 2115
        rtype2 = rtype1;
      } else {
2116 2117 2118
          c++;
          s2+=s1;
          rtype2=rtype1;
2119
      }
2120

2121 2122
    }

2123 2124 2125
    if (count_only_) {
      vsize_hist.Add(iter->value().size());
    }
2126

2127
    if (!count_only_ && !count_delim_) {
2128
      if (is_db_ttl_ && timestamp_) {
2129
        fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
2130
      }
2131 2132 2133
      std::string str =
          PrintKeyValue(iter->key().ToString(), iter->value().ToString(),
                        is_key_hex_, is_value_hex_);
2134
      fprintf(stdout, "%s\n", str.c_str());
2135 2136
    }
  }
2137

2138
  if (num_buckets > 1 && is_db_ttl_) {
2139
    PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
2140
                      num_buckets);
2141
  } else if(count_delim_) {
2142 2143
    fprintf(stdout, "%s => count:%" PRIu64 "\tsize:%" PRIu64 "\n",
            rtype2.c_str(), c, s2);
2144
  } else {
2145
    fprintf(stdout, "Keys in range: %" PRIu64 "\n", count);
2146
  }
2147 2148 2149 2150 2151

  if (count_only_) {
    fprintf(stdout, "Value size distribution: \n");
    fprintf(stdout, "%s\n", vsize_hist.ToString().c_str());
  }
2152 2153 2154 2155
  // Clean up
  delete iter;
}

2156 2157 2158
const std::string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
const std::string ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS =
    "print_old_levels";
2159

2160
ReduceDBLevelsCommand::ReduceDBLevelsCommand(
A
Andrew Kryczka 已提交
2161
    const std::vector<std::string>& /*params*/,
2162 2163 2164 2165 2166 2167 2168
    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) {
2169
  ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
2170
  print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
2171

2172
  if(new_levels_ <= 0) {
2173
    exec_state_ = LDBCommandExecuteResult::Failed(
2174
        " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
2175 2176 2177
  }
}

2178 2179 2180
std::vector<std::string> ReduceDBLevelsCommand::PrepareArgs(
    const std::string& db_path, int new_levels, bool print_old_level) {
  std::vector<std::string> ret;
2181
  ret.push_back("reduce_levels");
2182
  ret.push_back("--" + ARG_DB + "=" + db_path);
2183 2184
  ret.push_back("--" + ARG_NEW_LEVELS + "=" +
                ROCKSDB_NAMESPACE::ToString(new_levels));
2185
  if(print_old_level) {
2186
    ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
2187 2188 2189 2190
  }
  return ret;
}

2191
void ReduceDBLevelsCommand::Help(std::string& ret) {
2192 2193 2194 2195 2196
  ret.append("  ");
  ret.append(ReduceDBLevelsCommand::Name());
  ret.append(" --" + ARG_NEW_LEVELS + "=<New number of levels>");
  ret.append(" [--" + ARG_PRINT_OLD_LEVELS + "]");
  ret.append("\n");
2197 2198
}

2199 2200 2201 2202 2203
void ReduceDBLevelsCommand::OverrideBaseCFOptions(
    ColumnFamilyOptions* cf_opts) {
  LDBCommand::OverrideBaseCFOptions(cf_opts);
  cf_opts->num_levels = old_levels_;
  cf_opts->max_bytes_for_level_multiplier_additional.resize(cf_opts->num_levels,
2204
                                                            1);
2205
  // Disable size compaction
2206 2207
  cf_opts->max_bytes_for_level_base = 1ULL << 50;
  cf_opts->max_bytes_for_level_multiplier = 1;
2208 2209
}

2210
Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt,
2211
    int* levels) {
2212
  ImmutableDBOptions db_options(opt);
H
Haobo Xu 已提交
2213
  EnvOptions soptions;
I
Igor Canadi 已提交
2214
  std::shared_ptr<Cache> tc(
2215
      NewLRUCache(opt.max_open_files - 10, opt.table_cache_numshardbits));
2216
  const InternalKeyComparator cmp(opt.comparator);
S
sdong 已提交
2217
  WriteController wc(opt.delayed_write_rate);
2218
  WriteBufferManager wb(opt.db_write_buffer_size);
2219
  VersionSet versions(db_path_, &db_options, soptions, tc.get(), &wb, &wc,
2220 2221
                      /*block_cache_tracer=*/nullptr, /*io_tracer=*/nullptr,
                      /*db_session_id*/ "");
I
Igor Canadi 已提交
2222
  std::vector<ColumnFamilyDescriptor> dummy;
2223
  ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName,
I
Igor Canadi 已提交
2224 2225
                                          ColumnFamilyOptions(opt));
  dummy.push_back(dummy_descriptor);
2226 2227 2228
  // 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 已提交
2229
  Status st = versions.Recover(dummy);
2230 2231 2232 2233
  if (!st.ok()) {
    return st;
  }
  int max = -1;
2234
  auto default_cfd = versions.GetColumnFamilySet()->GetDefault();
I
Igor Canadi 已提交
2235
  for (int i = 0; i < default_cfd->NumberLevels(); i++) {
S
sdong 已提交
2236
    if (default_cfd->current()->storage_info()->NumLevelFiles(i)) {
2237 2238 2239 2240 2241 2242 2243 2244
      max = i;
    }
  }

  *levels = max + 1;
  return st;
}

2245
void ReduceDBLevelsCommand::DoCommand() {
2246
  if (new_levels_ <= 1) {
2247 2248
    exec_state_ =
        LDBCommandExecuteResult::Failed("Invalid number of levels.\n");
2249 2250 2251
    return;
  }

2252
  Status st;
2253
  PrepareOptions();
2254
  int old_level_num = -1;
2255
  st = GetOldNumOfLevels(options_, &old_level_num);
2256
  if (!st.ok()) {
2257
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2258 2259 2260
    return;
  }

2261
  if (print_old_levels_) {
2262
    fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
2263
  }
2264

2265 2266
  if (old_level_num <= new_levels_) {
    return;
2267 2268
  }

2269 2270 2271
  old_levels_ = old_level_num;

  OpenDB();
2272
  if (exec_state_.IsFailed()) {
2273 2274
    return;
  }
2275
  assert(db_ != nullptr);
2276
  // Compact the whole DB to put all files to the highest level.
2277
  fprintf(stdout, "Compacting the db...\n");
2278 2279 2280
  st =
      db_->CompactRange(CompactRangeOptions(), GetCfHandle(), nullptr, nullptr);

2281 2282
  CloseDB();

2283 2284 2285 2286 2287
  if (st.ok()) {
    EnvOptions soptions;
    st = VersionSet::ReduceNumberOfLevels(db_path_, &options_, soptions,
                                          new_levels_);
  }
2288
  if (!st.ok()) {
2289
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
2290 2291 2292 2293
    return;
  }
}

2294 2295 2296 2297
const std::string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
    "old_compaction_style";
const std::string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
    "new_compaction_style";
2298 2299

ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
A
Andrew Kryczka 已提交
2300
    const std::vector<std::string>& /*params*/,
2301 2302 2303 2304 2305 2306 2307
    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) {
2308 2309
  ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
    exec_state_);
2310 2311
  if (old_compaction_style_ != kCompactionStyleLevel &&
     old_compaction_style_ != kCompactionStyleUniversal) {
2312
    exec_state_ = LDBCommandExecuteResult::Failed(
2313 2314
        "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
        "style. Check ldb help for proper compaction style value.\n");
2315 2316 2317
    return;
  }

2318 2319
  ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
    exec_state_);
2320 2321
  if (new_compaction_style_ != kCompactionStyleLevel &&
     new_compaction_style_ != kCompactionStyleUniversal) {
2322
    exec_state_ = LDBCommandExecuteResult::Failed(
2323 2324
        "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
        "style. Check ldb help for proper compaction style value.\n");
2325 2326 2327 2328
    return;
  }

  if (new_compaction_style_ == old_compaction_style_) {
2329
    exec_state_ = LDBCommandExecuteResult::Failed(
2330 2331
        "Old compaction style is the same as new compaction style. "
        "Nothing to do.\n");
2332 2333 2334 2335 2336
    return;
  }

  if (old_compaction_style_ == kCompactionStyleUniversal &&
      new_compaction_style_ == kCompactionStyleLevel) {
2337
    exec_state_ = LDBCommandExecuteResult::Failed(
2338 2339
        "Convert from universal compaction to level compaction. "
        "Nothing to do.\n");
2340 2341 2342 2343
    return;
  }
}

2344
void ChangeCompactionStyleCommand::Help(std::string& ret) {
2345 2346 2347 2348 2349 2350 2351
  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");
2352 2353
}

2354 2355 2356
void ChangeCompactionStyleCommand::OverrideBaseCFOptions(
    ColumnFamilyOptions* cf_opts) {
  LDBCommand::OverrideBaseCFOptions(cf_opts);
2357 2358 2359 2360
  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.
2361 2362 2363 2364 2365
    cf_opts->disable_auto_compactions = true;
    cf_opts->target_file_size_base = INT_MAX;
    cf_opts->target_file_size_multiplier = 1;
    cf_opts->max_bytes_for_level_base = INT_MAX;
    cf_opts->max_bytes_for_level_multiplier = 1;
2366 2367 2368 2369
  }
}

void ChangeCompactionStyleCommand::DoCommand() {
2370 2371 2372 2373
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2374 2375 2376
  // print db stats before we have made any change
  std::string property;
  std::string files_per_level;
S
sdong 已提交
2377
  for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
2378
    db_->GetProperty(GetCfHandle(), "rocksdb.num-files-at-level" + ToString(i),
2379 2380
                     &property);

2381
    // format print string
2382
    char buf[100];
2383
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
2384 2385 2386 2387 2388 2389
    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
2390 2391 2392
  CompactRangeOptions compact_options;
  compact_options.change_level = true;
  compact_options.target_level = 0;
2393 2394 2395 2396 2397 2398 2399 2400
  Status s =
      db_->CompactRange(compact_options, GetCfHandle(), nullptr, nullptr);
  if (!s.ok()) {
    std::stringstream oss;
    oss << "Compaction failed: " << s.ToString();
    exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
    return;
  }
2401 2402 2403 2404

  // verify compaction result
  files_per_level = "";
  int num_files = 0;
2405
  for (int i = 0; i < db_->NumberLevels(GetCfHandle()); i++) {
2406
    db_->GetProperty(GetCfHandle(), "rocksdb.num-files-at-level" + ToString(i),
2407 2408
                     &property);

2409
    // format print string
2410
    char buf[100];
2411
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
2412 2413 2414 2415 2416 2417
    files_per_level += buf;

    num_files = atoi(property.c_str());

    // level 0 should have only 1 file
    if (i == 0 && num_files != 1) {
2418 2419 2420 2421
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level 0 after compaction is " +
          ToString(num_files) + ", not 1.\n");
2422 2423 2424 2425
      return;
    }
    // other levels should have no file
    if (i > 0 && num_files != 0) {
2426 2427 2428 2429 2430
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level " +
          ToString(i) + " after compaction is " + ToString(num_files) +
          ", not 0.\n");
2431 2432 2433 2434 2435 2436 2437 2438
      return;
    }
  }

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

2439 2440 2441 2442 2443
// ----------------------------------------------------------------------------

namespace {

struct StdErrReporter : public log::Reader::Reporter {
2444
  void Corruption(size_t /*bytes*/, const Status& s) override {
2445
    std::cerr << "Corruption detected in log file " << s.ToString() << "\n";
2446 2447 2448
  }
};

2449 2450
class InMemoryHandler : public WriteBatch::Handler {
 public:
2451 2452 2453 2454 2455 2456
  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) {}
2457

2458
  void commonPutMerge(const Slice& key, const Slice& value) {
2459
    std::string k = LDBCommand::StringToHex(key.ToString());
2460
    if (print_values_) {
2461
      std::string v = LDBCommand::StringToHex(value.ToString());
2462 2463 2464 2465 2466
      row_ << k << " : ";
      row_ << v << " ";
    } else {
      row_ << k << " ";
    }
2467
  }
2468

2469
  Status PutCF(uint32_t cf, const Slice& key, const Slice& value) override {
R
Reid Horuff 已提交
2470
    row_ << "PUT(" << cf << ") : ";
2471
    commonPutMerge(key, value);
R
Reid Horuff 已提交
2472
    return Status::OK();
2473 2474
  }

2475
  Status MergeCF(uint32_t cf, const Slice& key, const Slice& value) override {
R
Reid Horuff 已提交
2476
    row_ << "MERGE(" << cf << ") : ";
2477
    commonPutMerge(key, value);
R
Reid Horuff 已提交
2478
    return Status::OK();
2479
  }
2480

2481
  Status MarkNoop(bool) override {
2482 2483 2484 2485
    row_ << "NOOP ";
    return Status::OK();
  }

2486
  Status DeleteCF(uint32_t cf, const Slice& key) override {
R
Reid Horuff 已提交
2487
    row_ << "DELETE(" << cf << ") : ";
2488
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
R
Reid Horuff 已提交
2489 2490 2491
    return Status::OK();
  }

2492
  Status SingleDeleteCF(uint32_t cf, const Slice& key) override {
R
Reid Horuff 已提交
2493 2494 2495 2496 2497
    row_ << "SINGLE_DELETE(" << cf << ") : ";
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
    return Status::OK();
  }

2498 2499
  Status DeleteRangeCF(uint32_t cf, const Slice& begin_key,
                       const Slice& end_key) override {
A
Andrew Kryczka 已提交
2500 2501 2502 2503 2504 2505
    row_ << "DELETE_RANGE(" << cf << ") : ";
    row_ << LDBCommand::StringToHex(begin_key.ToString()) << " ";
    row_ << LDBCommand::StringToHex(end_key.ToString()) << " ";
    return Status::OK();
  }

2506
  Status MarkBeginPrepare(bool unprepare) override {
2507 2508
    row_ << "BEGIN_PREPARE(";
    row_ << (unprepare ? "true" : "false") << ") ";
R
Reid Horuff 已提交
2509 2510 2511
    return Status::OK();
  }

2512
  Status MarkEndPrepare(const Slice& xid) override {
R
Reid Horuff 已提交
2513 2514 2515 2516 2517
    row_ << "END_PREPARE(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
  }

2518
  Status MarkRollback(const Slice& xid) override {
R
Reid Horuff 已提交
2519 2520 2521 2522 2523
    row_ << "ROLLBACK(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
  }

2524
  Status MarkCommit(const Slice& xid) override {
R
Reid Horuff 已提交
2525 2526 2527
    row_ << "COMMIT(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ") ";
    return Status::OK();
2528 2529
  }

2530 2531 2532 2533 2534 2535 2536 2537
  Status MarkCommitWithTimestamp(const Slice& xid,
                                 const Slice& commit_ts) override {
    row_ << "COMMIT_WITH_TIMESTAMP(";
    row_ << LDBCommand::StringToHex(xid.ToString()) << ", ";
    row_ << LDBCommand::StringToHex(commit_ts.ToString()) << ") ";
    return Status::OK();
  }

2538
  ~InMemoryHandler() override {}
2539

2540
 protected:
2541 2542 2543 2544
  Handler::OptionState WriteAfterCommit() const override {
    return write_after_commit_ ? Handler::OptionState::kEnabled
                               : Handler::OptionState::kDisabled;
  }
2545

2546
 private:
2547
  std::stringstream& row_;
2548
  bool print_values_;
2549
  bool write_after_commit_;
2550 2551
};

2552 2553 2554
void DumpWalFile(Options options, std::string wal_file, bool print_header,
                 bool print_values, bool is_write_committed,
                 LDBCommandExecuteResult* exec_state) {
2555 2556
  const auto& fs = options.env->GetFileSystem();
  FileOptions soptions(options);
2557
  std::unique_ptr<SequentialFileReader> wal_file_reader;
2558 2559
  Status status = SequentialFileReader::Create(fs, wal_file, soptions,
                                               &wal_file_reader, nullptr);
2560 2561
  if (!status.ok()) {
    if (exec_state) {
2562
      *exec_state = LDBCommandExecuteResult::Failed("Failed to open WAL file " +
2563 2564
                                                    status.ToString());
    } else {
2565 2566
      std::cerr << "Error: Failed to open WAL file " << status.ToString()
                << std::endl;
2567 2568 2569
    }
  } else {
    StdErrReporter reporter;
2570 2571 2572 2573
    uint64_t log_number;
    FileType type;

    // we need the log number, but ParseFilename expects dbname/NNN.log.
2574
    std::string sanitized = wal_file;
2575 2576 2577 2578 2579 2580 2581
    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;
    }
2582
    log::Reader reader(options.info_log, std::move(wal_file_reader), &reporter,
2583
                       true /* checksum */, log_number);
2584
    std::string scratch;
2585 2586
    WriteBatch batch;
    Slice record;
2587
    std::stringstream row;
2588
    if (print_header) {
2589
      std::cout << "Sequence,Count,ByteSize,Physical Offset,Key(s)";
2590
      if (print_values) {
2591
        std::cout << " : value ";
2592
      }
2593
      std::cout << "\n";
2594
    }
2595
    while (status.ok() && reader.ReadRecord(&record, &scratch)) {
2596
      row.str("");
2597
      if (record.size() < WriteBatchInternal::kHeader) {
2598 2599 2600
        reporter.Corruption(record.size(),
                            Status::Corruption("log record too small"));
      } else {
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
        status = WriteBatchInternal::SetContents(&batch, record);
        if (!status.ok()) {
          std::stringstream oss;
          oss << "Parsing write batch failed: " << status.ToString();
          if (exec_state) {
            *exec_state = LDBCommandExecuteResult::Failed(oss.str());
          } else {
            std::cerr << oss.str() << std::endl;
          }
          break;
        }
2612 2613 2614 2615
        row << WriteBatchInternal::Sequence(&batch) << ",";
        row << WriteBatchInternal::Count(&batch) << ",";
        row << WriteBatchInternal::ByteSize(&batch) << ",";
        row << reader.LastRecordOffset() << ",";
2616
        InMemoryHandler handler(row, print_values, is_write_committed);
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
        status = batch.Iterate(&handler);
        if (!status.ok()) {
          if (exec_state) {
            std::stringstream oss;
            oss << "Print write batch error: " << status.ToString();
            *exec_state = LDBCommandExecuteResult::Failed(oss.str());
          }
          row << "error: " << status.ToString();
          break;
        }
2627 2628
        row << "\n";
      }
2629
      std::cout << row.str();
2630 2631 2632 2633 2634 2635
    }
  }
}

}  // namespace

2636
const std::string WALDumperCommand::ARG_WAL_FILE = "walfile";
2637
const std::string WALDumperCommand::ARG_WRITE_COMMITTED = "write_committed";
2638 2639
const std::string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
const std::string WALDumperCommand::ARG_PRINT_HEADER = "header";
2640

2641
WALDumperCommand::WALDumperCommand(
A
Andrew Kryczka 已提交
2642
    const std::vector<std::string>& /*params*/,
2643 2644 2645
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, true,
2646 2647
                 BuildCmdLineOptions({ARG_WAL_FILE, ARG_WRITE_COMMITTED,
                                      ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
2648
      print_header_(false),
2649 2650
      print_values_(false),
      is_write_committed_(false) {
A
Abhishek Kona 已提交
2651
  wal_file_.clear();
2652

2653
  auto itr = options.find(ARG_WAL_FILE);
2654 2655
  if (itr != options.end()) {
    wal_file_ = itr->second;
A
Abhishek Kona 已提交
2656
  }
2657 2658


2659 2660
  print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
2661 2662
  is_write_committed_ = ParseBooleanOption(options, ARG_WRITE_COMMITTED, true);

A
Abhishek Kona 已提交
2663
  if (wal_file_.empty()) {
2664 2665
    exec_state_ = LDBCommandExecuteResult::Failed("Argument " + ARG_WAL_FILE +
                                                  " must be specified.");
A
Abhishek Kona 已提交
2666 2667 2668
  }
}

2669
void WALDumperCommand::Help(std::string& ret) {
2670 2671 2672 2673 2674
  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 + "] ");
2675
  ret.append(" [--" + ARG_WRITE_COMMITTED + "=true|false] ");
2676
  ret.append("\n");
A
Abhishek Kona 已提交
2677 2678
}

2679
void WALDumperCommand::DoCommand() {
2680 2681
  DumpWalFile(options_, wal_file_, print_header_, print_values_,
              is_write_committed_, &exec_state_);
A
Abhishek Kona 已提交
2682 2683
}

2684
// ----------------------------------------------------------------------------
2685

2686 2687 2688 2689 2690 2691
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})) {
2692
  if (params.size() != 1) {
2693
    exec_state_ = LDBCommandExecuteResult::Failed(
2694
        "<key> must be specified for the get command");
2695 2696 2697 2698 2699 2700 2701 2702 2703
  } else {
    key_ = params.at(0);
  }

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

2704
void GetCommand::Help(std::string& ret) {
2705 2706 2707 2708 2709
  ret.append("  ");
  ret.append(GetCommand::Name());
  ret.append(" <key>");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2710 2711 2712
}

void GetCommand::DoCommand() {
S
sdong 已提交
2713 2714 2715 2716
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2717
  std::string value;
S
sdong 已提交
2718
  Status st = db_->Get(ReadOptions(), GetCfHandle(), key_, &value);
2719 2720 2721 2722
  if (st.ok()) {
    fprintf(stdout, "%s\n",
              (is_value_hex_ ? StringToHex(value) : value).c_str());
  } else {
2723 2724 2725
    std::stringstream oss;
    oss << "Get failed: " << st.ToString();
    exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
2726 2727 2728
  }
}

2729
// ----------------------------------------------------------------------------
2730

2731
ApproxSizeCommand::ApproxSizeCommand(
A
Andrew Kryczka 已提交
2732
    const std::vector<std::string>& /*params*/,
2733 2734 2735 2736 2737
    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})) {
2738 2739 2740
  if (options.find(ARG_FROM) != options.end()) {
    start_key_ = options.find(ARG_FROM)->second;
  } else {
2741 2742
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_FROM + " must be specified for approxsize command");
2743 2744 2745 2746 2747 2748
    return;
  }

  if (options.find(ARG_TO) != options.end()) {
    end_key_ = options.find(ARG_TO)->second;
  } else {
2749 2750
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_TO + " must be specified for approxsize command");
2751 2752 2753 2754 2755 2756 2757 2758 2759
    return;
  }

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

2760
void ApproxSizeCommand::Help(std::string& ret) {
2761 2762 2763 2764
  ret.append("  ");
  ret.append(ApproxSizeCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
2765 2766 2767
}

void ApproxSizeCommand::DoCommand() {
S
sdong 已提交
2768 2769 2770 2771
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2772 2773
  Range ranges[1];
  ranges[0] = Range(start_key_, end_key_);
2774
  uint64_t sizes[1];
2775 2776
  Status s = db_->GetApproximateSizes(GetCfHandle(), ranges, 1, sizes);
  if (!s.ok()) {
2777 2778 2779
    std::stringstream oss;
    oss << "ApproximateSize failed: " << s.ToString();
    exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
2780 2781
  } else {
    fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
2782 2783 2784
  }
}

2785
// ----------------------------------------------------------------------------
2786

2787 2788 2789 2790 2791 2792 2793
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})) {
2794
  if (params.size() < 2) {
2795
    exec_state_ = LDBCommandExecuteResult::Failed(
2796
        "At least one <key> <value> pair must be specified batchput.");
2797
  } else if (params.size() % 2 != 0) {
2798
    exec_state_ = LDBCommandExecuteResult::Failed(
2799 2800 2801
        "Equal number of <key>s and <value>s must be specified for batchput.");
  } else {
    for (size_t i = 0; i < params.size(); i += 2) {
2802 2803 2804 2805 2806
      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));
2807 2808
    }
  }
2809
  create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
2810 2811
}

2812
void BatchPutCommand::Help(std::string& ret) {
2813 2814 2815
  ret.append("  ");
  ret.append(BatchPutCommand::Name());
  ret.append(" <key> <value> [<key> <value>] [..]");
2816
  ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
2817 2818
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
2819 2820 2821
}

void BatchPutCommand::DoCommand() {
S
sdong 已提交
2822 2823 2824 2825
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2826
  WriteBatch batch;
2827

2828 2829
  Status st;
  std::stringstream oss;
2830 2831 2832
  for (std::vector<std::pair<std::string, std::string>>::const_iterator itr =
           key_values_.begin();
       itr != key_values_.end(); ++itr) {
2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
    st = batch.Put(GetCfHandle(), itr->first, itr->second);
    if (!st.ok()) {
      oss << "Put to write batch failed: " << itr->first << "=>" << itr->second
          << " error: " << st.ToString();
      break;
    }
  }
  if (st.ok()) {
    st = db_->Write(WriteOptions(), &batch);
    if (!st.ok()) {
      oss << "Write failed: " << st.ToString();
    }
2845 2846 2847 2848
  }
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
2849
    exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
2850 2851 2852
  }
}

2853 2854 2855
void BatchPutCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
2856 2857
}

2858
// ----------------------------------------------------------------------------
2859

A
Andrew Kryczka 已提交
2860
ScanCommand::ScanCommand(const std::vector<std::string>& /*params*/,
2861 2862 2863 2864 2865 2866 2867
                         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 已提交
2868 2869 2870 2871
      start_key_specified_(false),
      end_key_specified_(false),
      max_keys_scanned_(-1),
      no_value_(false) {
2872
  auto itr = options.find(ARG_FROM);
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888
  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;
  }

2889
  std::vector<std::string>::const_iterator vitr =
A
Alexander Fenster 已提交
2890
      std::find(flags.begin(), flags.end(), ARG_NO_VALUE);
2891 2892 2893 2894
  if (vitr != flags.end()) {
    no_value_ = true;
  }

2895 2896 2897
  itr = options.find(ARG_MAX_KEYS);
  if (itr != options.end()) {
    try {
S
sdong 已提交
2898 2899 2900
#if defined(CYGWIN)
      max_keys_scanned_ = strtol(itr->second.c_str(), 0, 10);
#else
2901
      max_keys_scanned_ = std::stoi(itr->second);
S
sdong 已提交
2902
#endif
2903
    } catch (const std::invalid_argument&) {
2904
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
2905
                                                    " has an invalid value");
2906
    } catch (const std::out_of_range&) {
2907 2908
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
2909 2910 2911 2912
    }
  }
}

2913
void ScanCommand::Help(std::string& ret) {
2914 2915 2916 2917 2918 2919 2920 2921
  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]");
2922
  ret.append(" [--" + ARG_NO_VALUE + "]");
2923
  ret.append("\n");
2924 2925 2926
}

void ScanCommand::DoCommand() {
S
sdong 已提交
2927 2928 2929 2930
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
2931 2932

  int num_keys_scanned = 0;
2933 2934 2935
  ReadOptions scan_read_opts;
  scan_read_opts.total_order_seek = true;
  Iterator* it = db_->NewIterator(scan_read_opts, GetCfHandle());
2936 2937 2938 2939 2940
  if (start_key_specified_) {
    it->Seek(start_key_);
  } else {
    it->SeekToFirst();
  }
2941
  int ttl_start;
2942
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
2943
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
2944 2945
  }
  int ttl_end;
2946
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
2947
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
2948 2949 2950 2951 2952 2953 2954 2955
  }
  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",
2956 2957
            TimeToHumanString(ttl_start).c_str(),
            TimeToHumanString(ttl_end).c_str());
2958
  }
2959
  for ( ;
2960 2961
        it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
        it->Next()) {
2962
    if (is_db_ttl_) {
2963
      TtlIterator* it_ttl = static_cast_with_check<TtlIterator>(it);
Y
Yanqin Jin 已提交
2964
      int rawtime = it_ttl->ttl_timestamp();
2965
      if (rawtime < ttl_start || rawtime >= ttl_end) {
2966 2967 2968
        continue;
      }
      if (timestamp_) {
2969
        fprintf(stdout, "%s ", TimeToHumanString(rawtime).c_str());
2970 2971
      }
    }
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983

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

2984
    if (no_value_) {
A
Alexander Fenster 已提交
2985 2986
      fprintf(stdout, "%.*s\n", static_cast<int>(key_slice.size()),
              key_slice.data());
2987
    } else {
A
Alexander Fenster 已提交
2988 2989 2990 2991 2992 2993 2994 2995 2996
      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());
2997 2998
    }

2999 3000 3001 3002 3003 3004
    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
3005
    exec_state_ = LDBCommandExecuteResult::Failed(it->status().ToString());
3006 3007 3008 3009
  }
  delete it;
}

3010
// ----------------------------------------------------------------------------
3011

3012 3013 3014 3015 3016
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})) {
3017
  if (params.size() != 1) {
3018
    exec_state_ = LDBCommandExecuteResult::Failed(
3019
        "KEY must be specified for the delete command");
3020 3021 3022 3023 3024 3025 3026 3027
  } else {
    key_ = params.at(0);
    if (is_key_hex_) {
      key_ = HexToString(key_);
    }
  }
}

3028
void DeleteCommand::Help(std::string& ret) {
3029 3030 3031
  ret.append("  ");
  ret.append(DeleteCommand::Name() + " <key>");
  ret.append("\n");
3032 3033 3034
}

void DeleteCommand::DoCommand() {
S
sdong 已提交
3035 3036 3037 3038 3039
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st = db_->Delete(WriteOptions(), GetCfHandle(), key_);
3040 3041 3042
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
3043
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
3044 3045 3046
  }
}

A
Andrew Kryczka 已提交
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
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());
  }
}

3086 3087 3088 3089 3090 3091
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})) {
3092
  if (params.size() != 2) {
3093
    exec_state_ = LDBCommandExecuteResult::Failed(
3094
        "<key> and <value> must be specified for the put command");
3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
  } else {
    key_ = params.at(0);
    value_ = params.at(1);
  }

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

  if (is_value_hex_) {
    value_ = HexToString(value_);
  }
3107
  create_if_missing_ = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
3108 3109
}

3110
void PutCommand::Help(std::string& ret) {
3111 3112
  ret.append("  ");
  ret.append(PutCommand::Name());
3113 3114
  ret.append(" <key> <value>");
  ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
3115 3116
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
3117 3118 3119
}

void PutCommand::DoCommand() {
S
sdong 已提交
3120 3121 3122 3123 3124
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
  Status st = db_->Put(WriteOptions(), GetCfHandle(), key_, value_);
3125 3126 3127
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
3128
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
3129 3130 3131
  }
}

3132 3133 3134
void PutCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
3135 3136
}

3137
// ----------------------------------------------------------------------------
3138 3139 3140 3141 3142 3143

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

3144
DBQuerierCommand::DBQuerierCommand(
A
Andrew Kryczka 已提交
3145
    const std::vector<std::string>& /*params*/,
3146 3147 3148 3149 3150
    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})) {
3151 3152 3153

}

3154
void DBQuerierCommand::Help(std::string& ret) {
3155 3156 3157 3158 3159
  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 "
3160
             "commands.");
3161
  ret.append("\n");
3162 3163 3164 3165
}

void DBQuerierCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
3166
    assert(GetExecuteState().IsFailed());
3167 3168
    return;
  }
3169

3170 3171
  ReadOptions read_options;
  WriteOptions write_options;
3172

3173 3174 3175
  std::string line;
  std::string key;
  std::string value;
3176 3177 3178
  Status s;
  std::stringstream oss;
  while (s.ok() && getline(std::cin, line, '\n')) {
3179 3180
    // Parse line into std::vector<std::string>
    std::vector<std::string> tokens;
3181 3182 3183
    size_t pos = 0;
    while (true) {
      size_t pos2 = line.find(' ', pos);
3184
      if (pos2 == std::string::npos) {
3185 3186 3187 3188 3189 3190 3191
        break;
      }
      tokens.push_back(line.substr(pos, pos2-pos));
      pos = pos2 + 1;
    }
    tokens.push_back(line.substr(pos));

3192
    const std::string& cmd = tokens[0];
3193 3194 3195 3196 3197 3198 3199 3200

    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]);
3201 3202 3203 3204 3205 3206
      s = db_->Delete(write_options, GetCfHandle(), Slice(key));
      if (s.ok()) {
        fprintf(stdout, "Successfully deleted %s\n", tokens[1].c_str());
      } else {
        oss << "delete " << key << " failed: " << s.ToString();
      }
3207 3208 3209
    } 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]);
3210 3211 3212 3213 3214 3215 3216
      s = db_->Put(write_options, GetCfHandle(), Slice(key), Slice(value));
      if (s.ok()) {
        fprintf(stdout, "Successfully put %s %s\n", tokens[1].c_str(),
                tokens[2].c_str());
      } else {
        oss << "put " << key << "=>" << value << " failed: " << s.ToString();
      }
3217 3218
    } else if (cmd == GET_CMD && tokens.size() == 2) {
      key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
3219 3220
      s = db_->Get(read_options, GetCfHandle(), Slice(key), &value);
      if (s.ok()) {
3221 3222 3223
        fprintf(stdout, "%s\n", PrintKeyValue(key, value,
              is_key_hex_, is_value_hex_).c_str());
      } else {
3224 3225 3226 3227 3228
        if (s.IsNotFound()) {
          fprintf(stdout, "Not found %s\n", tokens[1].c_str());
        } else {
          oss << "get " << key << " error: " << s.ToString();
        }
3229 3230 3231 3232 3233
      }
    } else {
      fprintf(stdout, "Unknown command %s\n", line.c_str());
    }
  }
3234 3235 3236
  if (!s.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(oss.str());
  }
3237 3238
}

3239 3240
// ----------------------------------------------------------------------------

3241
CheckConsistencyCommand::CheckConsistencyCommand(
A
Andrew Kryczka 已提交
3242
    const std::vector<std::string>& /*params*/,
3243 3244
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
S
sdong 已提交
3245
    : LDBCommand(options, flags, true, BuildCmdLineOptions({})) {}
Y
Yiting Li 已提交
3246

3247
void CheckConsistencyCommand::Help(std::string& ret) {
3248 3249 3250
  ret.append("  ");
  ret.append(CheckConsistencyCommand::Name());
  ret.append("\n");
Y
Yiting Li 已提交
3251
}
3252

Y
Yiting Li 已提交
3253
void CheckConsistencyCommand::DoCommand() {
S
sdong 已提交
3254 3255 3256 3257
  options_.paranoid_checks = true;
  options_.num_levels = 64;
  OpenDB();
  if (exec_state_.IsSucceed() || exec_state_.IsNotStarted()) {
Y
Yiting Li 已提交
3258 3259
    fprintf(stdout, "OK\n");
  }
S
sdong 已提交
3260
  CloseDB();
3261
}
Y
Yiting Li 已提交
3262

3263
// ----------------------------------------------------------------------------
A
Andrew Kryczka 已提交
3264

A
Aaron Gao 已提交
3265 3266 3267
const std::string CheckPointCommand::ARG_CHECKPOINT_DIR = "checkpoint_dir";

CheckPointCommand::CheckPointCommand(
A
Andrew Kryczka 已提交
3268
    const std::vector<std::string>& /*params*/,
A
Aaron Gao 已提交
3269 3270 3271 3272 3273
    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);
3274
  if (itr != options.end()) {
A
Aaron Gao 已提交
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
    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()) {
3295
    fprintf(stdout, "OK\n");
A
Aaron Gao 已提交
3296 3297 3298 3299 3300 3301 3302
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

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

3303 3304
const std::string RepairCommand::ARG_VERBOSE = "verbose";

A
Andrew Kryczka 已提交
3305
RepairCommand::RepairCommand(const std::vector<std::string>& /*params*/,
3306 3307
                             const std::map<std::string, std::string>& options,
                             const std::vector<std::string>& flags)
3308 3309 3310
    : LDBCommand(options, flags, false, BuildCmdLineOptions({ARG_VERBOSE})) {
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
}
A
Andrew Kryczka 已提交
3311

3312
void RepairCommand::Help(std::string& ret) {
A
Andrew Kryczka 已提交
3313 3314
  ret.append("  ");
  ret.append(RepairCommand::Name());
3315
  ret.append(" [--" + ARG_VERBOSE + "]");
A
Andrew Kryczka 已提交
3316 3317 3318
  ret.append("\n");
}

3319 3320
void RepairCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
3321 3322
  auto level = verbose_ ? InfoLogLevel::INFO_LEVEL : InfoLogLevel::WARN_LEVEL;
  options_.info_log.reset(new StderrLogger(level));
3323 3324
}

A
Andrew Kryczka 已提交
3325
void RepairCommand::DoCommand() {
3326 3327
  PrepareOptions();
  Status status = RepairDB(db_path_, options_);
A
Andrew Kryczka 已提交
3328
  if (status.ok()) {
3329
    fprintf(stdout, "OK\n");
A
Andrew Kryczka 已提交
3330 3331 3332 3333 3334 3335
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

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

3337 3338 3339 3340 3341 3342 3343 3344
const std::string BackupEngineCommand::ARG_NUM_THREADS = "num_threads";
const std::string BackupEngineCommand::ARG_BACKUP_ENV_URI = "backup_env_uri";
const std::string BackupEngineCommand::ARG_BACKUP_FS_URI = "backup_fs_uri";
const std::string BackupEngineCommand::ARG_BACKUP_DIR = "backup_dir";
const std::string BackupEngineCommand::ARG_STDERR_LOG_LEVEL =
    "stderr_log_level";

BackupEngineCommand::BackupEngineCommand(
A
Andrew Kryczka 已提交
3345
    const std::vector<std::string>& /*params*/,
3346 3347 3348
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false /* is_read_only */,
3349 3350 3351
                 BuildCmdLineOptions({ARG_BACKUP_ENV_URI, ARG_BACKUP_FS_URI,
                                      ARG_BACKUP_DIR, ARG_NUM_THREADS,
                                      ARG_STDERR_LOG_LEVEL})),
3352 3353
      num_threads_(1) {
  auto itr = options.find(ARG_NUM_THREADS);
W
Wanning Jiang 已提交
3354
  if (itr != options.end()) {
3355
    num_threads_ = std::stoi(itr->second);
W
Wanning Jiang 已提交
3356
  }
3357
  itr = options.find(ARG_BACKUP_ENV_URI);
A
Andrew Kryczka 已提交
3358
  if (itr != options.end()) {
3359
    backup_env_uri_ = itr->second;
W
Wanning Jiang 已提交
3360
  }
3361 3362 3363 3364 3365 3366 3367 3368 3369
  itr = options.find(ARG_BACKUP_FS_URI);
  if (itr != options.end()) {
    backup_fs_uri_ = itr->second;
  }
  if (!backup_env_uri_.empty() && !backup_fs_uri_.empty()) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "you may not specity both --" + ARG_BACKUP_ENV_URI + " and --" +
        ARG_BACKUP_FS_URI);
  }
W
Wanning Jiang 已提交
3370 3371 3372 3373 3374
  itr = options.find(ARG_BACKUP_DIR);
  if (itr == options.end()) {
    exec_state_ = LDBCommandExecuteResult::Failed("--" + ARG_BACKUP_DIR +
                                                  ": missing backup directory");
  } else {
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389
    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 已提交
3390 3391 3392
  }
}

3393
void BackupEngineCommand::Help(const std::string& name, std::string& ret) {
W
Wanning Jiang 已提交
3394
  ret.append("  ");
3395
  ret.append(name);
3396
  ret.append(" [--" + ARG_BACKUP_ENV_URI + " | --" + ARG_BACKUP_FS_URI + "] ");
W
Wanning Jiang 已提交
3397
  ret.append(" [--" + ARG_BACKUP_DIR + "] ");
3398 3399
  ret.append(" [--" + ARG_NUM_THREADS + "] ");
  ret.append(" [--" + ARG_STDERR_LOG_LEVEL + "=<int (InfoLogLevel)>] ");
W
Wanning Jiang 已提交
3400 3401 3402
  ret.append("\n");
}

3403 3404 3405 3406 3407
// ----------------------------------------------------------------------------

BackupCommand::BackupCommand(const std::vector<std::string>& params,
                             const std::map<std::string, std::string>& options,
                             const std::vector<std::string>& flags)
3408
    : BackupEngineCommand(params, options, flags) {}
3409 3410

void BackupCommand::Help(std::string& ret) {
3411
  BackupEngineCommand::Help(Name(), ret);
3412 3413
}

W
Wanning Jiang 已提交
3414 3415 3416 3417 3418 3419 3420
void BackupCommand::DoCommand() {
  BackupEngine* backup_engine;
  Status status;
  if (!db_) {
    assert(GetExecuteState().IsFailed());
    return;
  }
3421
  fprintf(stdout, "open db OK\n");
3422

3423 3424 3425 3426 3427 3428
  Env* custom_env = backup_env_guard_.get();
  if (custom_env == nullptr) {
    Status s =
        Env::CreateFromUri(config_options_, backup_env_uri_, backup_fs_uri_,
                           &custom_env, &backup_env_guard_);
    if (!s.ok()) {
3429 3430 3431 3432
      exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
      return;
    }
  }
3433
  assert(custom_env != nullptr);
3434

3435 3436
  BackupEngineOptions backup_options =
      BackupEngineOptions(backup_dir_, custom_env);
3437 3438
  backup_options.info_log = logger_.get();
  backup_options.max_background_operations = num_threads_;
3439
  status = BackupEngine::Open(options_.env, backup_options, &backup_engine);
W
Wanning Jiang 已提交
3440
  if (status.ok()) {
3441
    fprintf(stdout, "open backup engine OK\n");
W
Wanning Jiang 已提交
3442 3443 3444 3445 3446 3447
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
    return;
  }
  status = backup_engine->CreateNewBackup(db_);
  if (status.ok()) {
3448
    fprintf(stdout, "create new backup OK\n");
W
Wanning Jiang 已提交
3449 3450 3451 3452 3453 3454 3455
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
    return;
  }
}

// ----------------------------------------------------------------------------
A
Andrew Kryczka 已提交
3456 3457 3458 3459 3460

RestoreCommand::RestoreCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
3461
    : BackupEngineCommand(params, options, flags) {}
A
Andrew Kryczka 已提交
3462 3463

void RestoreCommand::Help(std::string& ret) {
3464
  BackupEngineCommand::Help(Name(), ret);
A
Andrew Kryczka 已提交
3465 3466 3467
}

void RestoreCommand::DoCommand() {
3468 3469 3470 3471 3472 3473
  Env* custom_env = backup_env_guard_.get();
  if (custom_env == nullptr) {
    Status s =
        Env::CreateFromUri(config_options_, backup_env_uri_, backup_fs_uri_,
                           &custom_env, &backup_env_guard_);
    if (!s.ok()) {
3474 3475 3476 3477
      exec_state_ = LDBCommandExecuteResult::Failed(s.ToString());
      return;
    }
  }
3478
  assert(custom_env != nullptr);
3479

A
Andrew Kryczka 已提交
3480 3481 3482
  std::unique_ptr<BackupEngineReadOnly> restore_engine;
  Status status;
  {
3483
    BackupEngineOptions opts(backup_dir_, custom_env);
3484
    opts.info_log = logger_.get();
A
Andrew Kryczka 已提交
3485 3486
    opts.max_background_operations = num_threads_;
    BackupEngineReadOnly* raw_restore_engine_ptr;
3487
    status =
3488
        BackupEngineReadOnly::Open(options_.env, opts, &raw_restore_engine_ptr);
A
Andrew Kryczka 已提交
3489 3490 3491 3492 3493
    if (status.ok()) {
      restore_engine.reset(raw_restore_engine_ptr);
    }
  }
  if (status.ok()) {
3494
    fprintf(stdout, "open restore engine OK\n");
A
Andrew Kryczka 已提交
3495 3496 3497
    status = restore_engine->RestoreDBFromLatestBackup(db_path_, db_path_);
  }
  if (status.ok()) {
3498
    fprintf(stdout, "restore from backup OK\n");
A
Andrew Kryczka 已提交
3499 3500 3501 3502 3503 3504
  } else {
    exec_state_ = LDBCommandExecuteResult::Failed(status.ToString());
  }
}

// ----------------------------------------------------------------------------
3505 3506 3507

namespace {

3508
void DumpSstFile(Options options, std::string filename, bool output_hex,
3509
                 bool show_properties, bool decode_blob_index) {
3510 3511 3512 3513 3514 3515 3516 3517
  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
3518
  ROCKSDB_NAMESPACE::SstFileDumper dumper(
3519 3520
      options, filename, Temperature::kUnknown,
      2 * 1024 * 1024 /* readahead_size */,
3521
      /* verify_checksum */ false, output_hex, decode_blob_index);
3522 3523
  Status st = dumper.ReadSequential(true, std::numeric_limits<uint64_t>::max(),
                                    false,            // has_from
3524 3525 3526 3527 3528 3529 3530 3531 3532
                                    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) {
3533
    const ROCKSDB_NAMESPACE::TableProperties* table_properties;
3534

3535
    std::shared_ptr<const ROCKSDB_NAMESPACE::TableProperties>
3536
        table_properties_from_reader;
3537
    st = dumper.ReadTableProperties(&table_properties_from_reader);
3538 3539 3540
    if (!st.ok()) {
      std::cerr << filename << ": " << st.ToString()
                << ". Try to use initial table properties" << std::endl;
3541
      table_properties = dumper.GetInitTableProperties();
3542 3543 3544 3545 3546 3547 3548 3549 3550 3551
    } 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;
    }
  }
}

3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
void DumpBlobFile(const std::string& filename, bool is_key_hex,
                  bool is_value_hex, bool dump_uncompressed_blobs) {
  using ROCKSDB_NAMESPACE::blob_db::BlobDumpTool;
  BlobDumpTool tool;
  BlobDumpTool::DisplayType blob_type = is_value_hex
                                            ? BlobDumpTool::DisplayType::kHex
                                            : BlobDumpTool::DisplayType::kRaw;
  BlobDumpTool::DisplayType show_uncompressed_blob =
      dump_uncompressed_blobs ? blob_type : BlobDumpTool::DisplayType::kNone;
  BlobDumpTool::DisplayType show_blob =
      dump_uncompressed_blobs ? BlobDumpTool::DisplayType::kNone : blob_type;

  BlobDumpTool::DisplayType show_key = is_key_hex
                                           ? BlobDumpTool::DisplayType::kHex
                                           : BlobDumpTool::DisplayType::kRaw;
  Status s = tool.Run(filename, show_key, show_blob, show_uncompressed_blob,
                      /* show_summary */ true);
  if (!s.ok()) {
    fprintf(stderr, "Failed: %s\n", s.ToString().c_str());
  }
}
3573 3574
}  // namespace

3575
DBFileDumperCommand::DBFileDumperCommand(
A
Andrew Kryczka 已提交
3576
    const std::vector<std::string>& /*params*/,
3577 3578
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
3579
    : LDBCommand(options, flags, true,
3580 3581 3582 3583 3584
                 BuildCmdLineOptions(
                     {ARG_DECODE_BLOB_INDEX, ARG_DUMP_UNCOMPRESSED_BLOBS})),
      decode_blob_index_(IsFlagPresent(flags, ARG_DECODE_BLOB_INDEX)),
      dump_uncompressed_blobs_(
          IsFlagPresent(flags, ARG_DUMP_UNCOMPRESSED_BLOBS)) {}
3585

3586
void DBFileDumperCommand::Help(std::string& ret) {
3587 3588
  ret.append("  ");
  ret.append(DBFileDumperCommand::Name());
3589
  ret.append(" [--" + ARG_DECODE_BLOB_INDEX + "] ");
3590
  ret.append(" [--" + ARG_DUMP_UNCOMPRESSED_BLOBS + "] ");
3591 3592 3593 3594 3595
  ret.append("\n");
}

void DBFileDumperCommand::DoCommand() {
  if (!db_) {
S
sdong 已提交
3596
    assert(GetExecuteState().IsFailed());
3597 3598 3599 3600
    return;
  }
  Status s;

3601 3602
  // TODO: Use --hex, --key_hex, --value_hex flags consistently for
  // dumping manifest file, sst files and blob files.
3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614
  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);
3615
  std::string manifest_filepath = db_->GetName() + "/" + manifest_filename;
3616 3617 3618 3619 3620
  // Correct concatenation of filepath and filename:
  // Check that there is no double slashes (or more!) when concatenation
  // happens.
  manifest_filepath = NormalizePath(manifest_filepath);

3621
  std::cout << manifest_filepath << std::endl;
3622
  DumpManifestFile(options_, manifest_filepath, false, false, false);
3623 3624
  std::cout << std::endl;

3625 3626 3627 3628 3629
  std::vector<ColumnFamilyMetaData> column_families;
  db_->GetAllColumnFamilyMetaData(&column_families);
  for (const auto& column_family : column_families) {
    std::cout << "Column family name: " << column_family.name << std::endl;
    std::cout << "==============================" << std::endl;
3630
    std::cout << std::endl;
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660
    std::cout << "SST Files" << std::endl;
    std::cout << "==============================" << std::endl;
    for (const LevelMetaData& level : column_family.levels) {
      for (const SstFileMetaData& sst_file : level.files) {
        std::string filename = sst_file.db_path + "/" + sst_file.name;
        // Correct concatenation of filepath and filename:
        // Check that there is no double slashes (or more!) when concatenation
        // happens.
        filename = NormalizePath(filename);
        std::cout << filename << " level:" << level.level << std::endl;
        std::cout << "------------------------------" << std::endl;
        DumpSstFile(options_, filename, false, true, decode_blob_index_);
        std::cout << std::endl;
      }
    }
    std::cout << "Blob Files" << std::endl;
    std::cout << "==============================" << std::endl;
    for (const BlobMetaData& blob_file : column_family.blob_files) {
      std::string filename =
          blob_file.blob_file_path + "/" + blob_file.blob_file_name;
      // Correct concatenation of filepath and filename:
      // Check that there is no double slashes (or more!) when concatenation
      // happens.
      filename = NormalizePath(filename);
      std::cout << filename << std::endl;
      std::cout << "------------------------------" << std::endl;
      DumpBlobFile(filename, /* is_key_hex */ false, /* is_value_hex */ false,
                   dump_uncompressed_blobs_);
      std::cout << std::endl;
    }
3661 3662 3663 3664 3665
  }
  std::cout << std::endl;

  std::cout << "Write Ahead Log Files" << std::endl;
  std::cout << "==============================" << std::endl;
3666
  ROCKSDB_NAMESPACE::VectorLogPtr wal_files;
3667 3668 3669 3670
  s = db_->GetSortedWalFiles(wal_files);
  if (!s.ok()) {
    std::cerr << "Error when getting WAL files" << std::endl;
  } else {
3671 3672 3673 3674 3675 3676
    std::string wal_dir;
    if (options_.wal_dir.empty()) {
      wal_dir = db_->GetName();
    } else {
      wal_dir = NormalizePath(options_.wal_dir + "/");
    }
3677 3678
    for (auto& wal : wal_files) {
      // TODO(qyang): option.wal_dir should be passed into ldb command
3679
      std::string filename = wal_dir + wal->PathName();
3680
      std::cout << filename << std::endl;
3681
      // TODO(myabandeh): allow configuring is_write_commited
3682
      DumpWalFile(options_, filename, true, true, true /* is_write_commited */,
3683
                  &exec_state_);
3684 3685 3686 3687
    }
  }
}

3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
const std::string DBLiveFilesMetadataDumperCommand::ARG_SORT_BY_FILENAME =
    "sort_by_filename";

DBLiveFilesMetadataDumperCommand::DBLiveFilesMetadataDumperCommand(
    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_SORT_BY_FILENAME})) {
  sort_by_filename_ = IsFlagPresent(flags, ARG_SORT_BY_FILENAME);
}

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

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

3714 3715
  std::vector<ColumnFamilyMetaData> metadata;
  db_->GetAllColumnFamilyMetaData(&metadata);
3716
  if (sort_by_filename_) {
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
    std::cout << "Live SST and Blob Files:" << std::endl;
    // tuple of <file path, level, column family name>
    std::vector<std::tuple<std::string, int, std::string>> all_files;

    for (const auto& column_metadata : metadata) {
      // Iterate Levels
      const auto& levels = column_metadata.levels;
      const std::string& cf = column_metadata.name;
      for (const auto& level_metadata : levels) {
        // Iterate SST files
        const auto& sst_files = level_metadata.files;
        int level = level_metadata.level;
        for (const auto& sst_metadata : sst_files) {
          // The SstFileMetaData.name always starts with "/",
          // however SstFileMetaData.db_path is the string provided by
          // the user as an input. Therefore we check if we can
          // concantenate the two strings directly or if we need to
          // drop a possible extra "/" at the end of SstFileMetaData.db_path.
          std::string filename =
              NormalizePath(sst_metadata.db_path + "/" + sst_metadata.name);
          all_files.emplace_back(filename, level, cf);
        }  // End of for-loop over sst files
      }    // End of for-loop over levels

      const auto& blob_files = column_metadata.blob_files;
      for (const auto& blob_metadata : blob_files) {
        // The BlobMetaData.blob_file_name always starts with "/",
        // however BlobMetaData.blob_file_path is the string provided by
        // the user as an input. Therefore we check if we can
        // concantenate the two strings directly or if we need to
        // drop a possible extra "/" at the end of BlobMetaData.blob_file_path.
        std::string filename = NormalizePath(
            blob_metadata.blob_file_path + "/" + blob_metadata.blob_file_name);
        // Level for blob files is encoded as -1
        all_files.emplace_back(filename, -1, cf);
      }  // End of for-loop over blob files
    }    // End of for-loop over column metadata

    // Sort by filename (i.e. first entry in tuple)
    std::sort(all_files.begin(), all_files.end());

    for (const auto& item : all_files) {
      const std::string& filename = std::get<0>(item);
      int level = std::get<1>(item);
      const std::string& cf = std::get<2>(item);
      if (level == -1) {  // Blob File
        std::cout << filename << ", column family '" << cf << "'" << std::endl;
      } else {  // SST file
        std::cout << filename << " : level " << level << ", column family '"
                  << cf << "'" << std::endl;
      }
3768 3769
    }
  } else {
3770 3771
    for (const auto& column_metadata : metadata) {
      std::cout << "===== Column Family: " << column_metadata.name
3772 3773
                << " =====" << std::endl;

3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807
      std::cout << "Live SST Files:" << std::endl;
      // Iterate levels
      const auto& levels = column_metadata.levels;
      for (const auto& level_metadata : levels) {
        std::cout << "---------- level " << level_metadata.level
                  << " ----------" << std::endl;
        // Iterate SST files
        const auto& sst_files = level_metadata.files;
        for (const auto& sst_metadata : sst_files) {
          // The SstFileMetaData.name always starts with "/",
          // however SstFileMetaData.db_path is the string provided by
          // the user as an input. Therefore we check if we can
          // concantenate the two strings directly or if we need to
          // drop a possible extra "/" at the end of SstFileMetaData.db_path.
          std::string filename =
              NormalizePath(sst_metadata.db_path + "/" + sst_metadata.name);
          std::cout << filename << std::endl;
        }  // End of for-loop over sst files
      }    // End of for-loop over levels

      std::cout << "Live Blob Files:" << std::endl;
      const auto& blob_files = column_metadata.blob_files;
      for (const auto& blob_metadata : blob_files) {
        // The BlobMetaData.blob_file_name always starts with "/",
        // however BlobMetaData.blob_file_path is the string provided by
        // the user as an input. Therefore we check if we can
        // concantenate the two strings directly or if we need to
        // drop a possible extra "/" at the end of BlobMetaData.blob_file_path.
        std::string filename = NormalizePath(
            blob_metadata.blob_file_path + "/" + blob_metadata.blob_file_name);
        std::cout << filename << std::endl;
      }  // End of for-loop over blob files
    }    // End of for-loop over column metadata
  }      // End of else ("not sort_by_filename")
3808 3809 3810
  std::cout << "------------------------------" << std::endl;
}

Y
Yanqin Jin 已提交
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
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_);
}

3888 3889 3890
void WriteExternalSstFilesCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
Y
Yanqin Jin 已提交
3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
}

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

4002 4003 4004
void IngestExternalSstFilesCommand::OverrideBaseOptions() {
  LDBCommand::OverrideBaseOptions();
  options_.create_if_missing = create_if_missing_;
Y
Yanqin Jin 已提交
4005 4006
}

4007 4008 4009 4010
ListFileRangeDeletesCommand::ListFileRangeDeletesCommand(
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, true, BuildCmdLineOptions({ARG_MAX_KEYS})) {
4011
  auto itr = options.find(ARG_MAX_KEYS);
4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041
  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;
  }

4042
  DBImpl* db_impl = static_cast_with_check<DBImpl>(db_->GetRootDB());
4043 4044 4045 4046 4047 4048 4049 4050 4051

  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());
4052 4053 4054 4055 4056 4057 4058
  }
}

void UnsafeRemoveSstFileCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(UnsafeRemoveSstFileCommand::Name());
  ret.append(" <SST file number>");
4059
  ret.append("  ");
4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072
  ret.append("    MUST NOT be used on a live DB.");
  ret.append("\n");
}

UnsafeRemoveSstFileCommand::UnsafeRemoveSstFileCommand(
    const std::vector<std::string>& params,
    const std::map<std::string, std::string>& options,
    const std::vector<std::string>& flags)
    : LDBCommand(options, flags, false /* is_read_only */,
                 BuildCmdLineOptions({})) {
  if (params.size() != 1) {
    exec_state_ =
        LDBCommandExecuteResult::Failed("SST file number must be specified");
4073
  } else {
4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085
    char* endptr = nullptr;
    sst_file_number_ = strtoull(params.at(0).c_str(), &endptr, 10 /* base */);
    if (endptr == nullptr || *endptr != '\0') {
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Failed to parse SST file number " + params.at(0));
    }
  }
}

void UnsafeRemoveSstFileCommand::DoCommand() {
  PrepareOptions();

4086 4087 4088
  OfflineManifestWriter w(options_, db_path_);
  if (column_families_.empty()) {
    column_families_.emplace_back(kDefaultColumnFamilyName, options_);
4089
  }
4090
  Status s = w.Recover(column_families_);
4091 4092 4093 4094 4095

  ColumnFamilyData* cfd = nullptr;
  int level = -1;
  if (s.ok()) {
    FileMetaData* metadata = nullptr;
4096 4097
    s = w.Versions().GetMetadataForFile(sst_file_number_, &level, &metadata,
                                        &cfd);
4098 4099 4100 4101 4102 4103
  }

  if (s.ok()) {
    VersionEdit edit;
    edit.SetColumnFamily(cfd->GetID());
    edit.DeleteFile(level, sst_file_number_);
4104
    s = w.LogAndApply(cfd, &edit);
4105 4106 4107 4108 4109 4110 4111
  }

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

4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168
const std::string UpdateManifestCommand::ARG_VERBOSE = "verbose";
const std::string UpdateManifestCommand::ARG_UPDATE_TEMPERATURES =
    "update_temperatures";

void UpdateManifestCommand::Help(std::string& ret) {
  ret.append("  ");
  ret.append(UpdateManifestCommand::Name());
  ret.append(" [--update_temperatures]");
  ret.append("  ");
  ret.append("    MUST NOT be used on a live DB.");
  ret.append("\n");
}

UpdateManifestCommand::UpdateManifestCommand(
    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_VERBOSE, ARG_UPDATE_TEMPERATURES})) {
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE) ||
             ParseBooleanOption(options, ARG_VERBOSE, false);
  update_temperatures_ =
      IsFlagPresent(flags, ARG_UPDATE_TEMPERATURES) ||
      ParseBooleanOption(options, ARG_UPDATE_TEMPERATURES, false);

  if (!update_temperatures_) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "No action like --update_temperatures specified for update_manifest");
  }
}

void UpdateManifestCommand::DoCommand() {
  PrepareOptions();

  auto level = verbose_ ? InfoLogLevel::INFO_LEVEL : InfoLogLevel::WARN_LEVEL;
  options_.info_log.reset(new StderrLogger(level));

  experimental::UpdateManifestForFilesStateOptions opts;
  opts.update_temperatures = update_temperatures_;
  if (column_families_.empty()) {
    column_families_.emplace_back(kDefaultColumnFamilyName, options_);
  }
  Status s = experimental::UpdateManifestForFilesState(options_, db_path_,
                                                       column_families_);

  if (!s.ok()) {
    exec_state_ = LDBCommandExecuteResult::Failed(
        "failed to update manifest: " + s.ToString());
  } else {
    exec_state_ =
        LDBCommandExecuteResult::Succeed("Manifest updates successful");
  }
}

4169
}  // namespace ROCKSDB_NAMESPACE
I
Igor Canadi 已提交
4170
#endif  // ROCKSDB_LITE