ldb_cmd.cc 57.6 KB
Newer Older
1 2 3 4 5
//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
I
Igor Canadi 已提交
6
#ifndef ROCKSDB_LITE
7
#include "util/ldb_cmd.h"
A
Abhishek Kona 已提交
8 9

#include "db/dbformat.h"
10
#include "db/db_impl.h"
A
Abhishek Kona 已提交
11
#include "db/log_reader.h"
12
#include "db/filename.h"
A
Abhishek Kona 已提交
13
#include "db/write_batch_internal.h"
14
#include "rocksdb/write_batch.h"
I
Igor Canadi 已提交
15
#include "rocksdb/cache.h"
16
#include "util/coding.h"
17
#include "util/scoped_arena_iterator.h"
18
#include "utilities/ttl/db_ttl_impl.h"
19

20 21 22 23 24 25 26
#include <ctime>
#include <dirent.h>
#include <limits>
#include <sstream>
#include <string>
#include <stdexcept>

27
namespace rocksdb {
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
using namespace std;

const string LDBCommand::ARG_DB = "db";
const string LDBCommand::ARG_HEX = "hex";
const string LDBCommand::ARG_KEY_HEX = "key_hex";
const string LDBCommand::ARG_VALUE_HEX = "value_hex";
const string LDBCommand::ARG_TTL = "ttl";
const string LDBCommand::ARG_TTL_START = "start_time";
const string LDBCommand::ARG_TTL_END = "end_time";
const string LDBCommand::ARG_TIMESTAMP = "timestamp";
const string LDBCommand::ARG_FROM = "from";
const string LDBCommand::ARG_TO = "to";
const string LDBCommand::ARG_MAX_KEYS = "max_keys";
const string LDBCommand::ARG_BLOOM_BITS = "bloom_bits";
const string LDBCommand::ARG_FIX_PREFIX_LEN = "fix_prefix_len";
const string LDBCommand::ARG_COMPRESSION_TYPE = "compression_type";
const string LDBCommand::ARG_BLOCK_SIZE = "block_size";
const string LDBCommand::ARG_AUTO_COMPACTION = "auto_compaction";
const string LDBCommand::ARG_WRITE_BUFFER_SIZE = "write_buffer_size";
const string LDBCommand::ARG_FILE_SIZE = "file_size";
const string LDBCommand::ARG_CREATE_IF_MISSING = "create_if_missing";
50

51
const char* LDBCommand::DELIM = " ==> ";
52

53
LDBCommand* LDBCommand::InitFromCmdLineArgs(
54 55 56 57 58 59
  int argc,
  char** argv,
  const Options& options,
  const LDBOptions& ldb_options
) {
  vector<string> args;
60 61 62
  for (int i = 1; i < argc; i++) {
    args.push_back(argv[i]);
  }
63
  return InitFromCmdLineArgs(args, options, ldb_options);
64 65 66 67 68 69
}

/**
 * Parse the command-line arguments and create the appropriate LDBCommand2
 * instance.
 * The command line arguments must be in the following format:
70 71
 * ./ldb --db=PATH_TO_DB [--commonOpt1=commonOpt1Val] ..
 *        COMMAND <PARAM1> <PARAM2> ... [-cmdSpecificOpt1=cmdSpecificOpt1Val] ..
72 73
 * This is similar to the command line format used by HBaseClientTool.
 * Command name is not included in args.
74
 * Returns nullptr if the command-line cannot be parsed.
75
 */
76
LDBCommand* LDBCommand::InitFromCmdLineArgs(
77 78 79 80 81 82
  const vector<string>& args,
  const Options& options,
  const LDBOptions& ldb_options
) {
  // --x=y command line arguments are added as x->y map entries.
  map<string, string> option_map;
83 84

  // Command-line arguments of the form --hex end up in this array as hex
85
  vector<string> flags;
86

87
  // Everything other than option_map and flags. Represents commands
88 89
  // and their parameters.  For eg: put key1 value1 go into this vector.
  vector<string> cmdTokens;
90

91
  const string OPTION_PREFIX = "--";
92

93
  for (const auto& arg : args) {
94 95
    if (arg[0] == '-' && arg[1] == '-'){
      vector<string> splits = stringSplit(arg, '=');
96
      if (splits.size() == 2) {
97
        string optionKey = splits[0].substr(OPTION_PREFIX.size());
98
        option_map[optionKey] = splits[1];
99
      } else {
100
        string optionKey = splits[0].substr(OPTION_PREFIX.size());
101 102
        flags.push_back(optionKey);
      }
103
    } else {
104
      cmdTokens.push_back(arg);
105 106 107 108 109
    }
  }

  if (cmdTokens.size() < 1) {
    fprintf(stderr, "Command not specified!");
110
    return nullptr;
111 112
  }

113 114
  string cmd = cmdTokens[0];
  vector<string> cmdParams(cmdTokens.begin()+1, cmdTokens.end());
115
  LDBCommand* command = LDBCommand::SelectCommand(
116 117 118 119 120
    cmd,
    cmdParams,
    option_map,
    flags
  );
121 122

  if (command) {
123 124
    command->SetDBOptions(options);
    command->SetLDBOptions(ldb_options);
125 126 127 128 129 130
  }
  return command;
}

LDBCommand* LDBCommand::SelectCommand(
    const std::string& cmd,
131 132 133 134 135
    const vector<string>& cmdParams,
    const map<string, string>& option_map,
    const vector<string>& flags
  ) {

136
  if (cmd == GetCommand::Name()) {
137
    return new GetCommand(cmdParams, option_map, flags);
138
  } else if (cmd == PutCommand::Name()) {
139
    return new PutCommand(cmdParams, option_map, flags);
140
  } else if (cmd == BatchPutCommand::Name()) {
141
    return new BatchPutCommand(cmdParams, option_map, flags);
142
  } else if (cmd == ScanCommand::Name()) {
143
    return new ScanCommand(cmdParams, option_map, flags);
144
  } else if (cmd == DeleteCommand::Name()) {
145
    return new DeleteCommand(cmdParams, option_map, flags);
146
  } else if (cmd == ApproxSizeCommand::Name()) {
147
    return new ApproxSizeCommand(cmdParams, option_map, flags);
148
  } else if (cmd == DBQuerierCommand::Name()) {
149
    return new DBQuerierCommand(cmdParams, option_map, flags);
150
  } else if (cmd == CompactorCommand::Name()) {
151
    return new CompactorCommand(cmdParams, option_map, flags);
152
  } else if (cmd == WALDumperCommand::Name()) {
153
    return new WALDumperCommand(cmdParams, option_map, flags);
154
  } else if (cmd == ReduceDBLevelsCommand::Name()) {
155
    return new ReduceDBLevelsCommand(cmdParams, option_map, flags);
156 157
  } else if (cmd == ChangeCompactionStyleCommand::Name()) {
    return new ChangeCompactionStyleCommand(cmdParams, option_map, flags);
158
  } else if (cmd == DBDumperCommand::Name()) {
159
    return new DBDumperCommand(cmdParams, option_map, flags);
160
  } else if (cmd == DBLoaderCommand::Name()) {
161
    return new DBLoaderCommand(cmdParams, option_map, flags);
162
  } else if (cmd == ManifestDumpCommand::Name()) {
163
    return new ManifestDumpCommand(cmdParams, option_map, flags);
164 165
  } else if (cmd == ListColumnFamiliesCommand::Name()) {
    return new ListColumnFamiliesCommand(cmdParams, option_map, flags);
166 167
  } else if (cmd == InternalDumpCommand::Name()) {
    return new InternalDumpCommand(cmdParams, option_map, flags);
Y
Yiting Li 已提交
168 169
  } else if (cmd == CheckConsistencyCommand::Name()) {
    return new CheckConsistencyCommand(cmdParams, option_map, flags);
170
  }
171
  return nullptr;
172 173
}

174

175 176 177 178 179 180 181
/**
 * 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.
 */
182 183 184 185 186
bool LDBCommand::ParseIntOption(const map<string, string>& options,
                                const string& option, int& value,
                                LDBCommandExecuteResult& exec_state) {

  map<string, string>::const_iterator itr = option_map_.find(option);
187
  if (itr != option_map_.end()) {
188
    try {
189
      value = stoi(itr->second);
190
      return true;
191 192 193 194 195 196
    } catch(const invalid_argument&) {
      exec_state = LDBCommandExecuteResult::FAILED(option +
                      " has an invalid value.");
    } catch(const out_of_range&) {
      exec_state = LDBCommandExecuteResult::FAILED(option +
                      " has a value out-of-range.");
197 198
    }
  }
199
  return false;
200 201
}

202 203 204 205 206
/**
 * Parses the specified option and fills in the value.
 * Returns true if the option is found.
 * Returns false otherwise.
 */
207 208
bool LDBCommand::ParseStringOption(const map<string, string>& options,
                                   const string& option, string* value) {
209 210 211 212 213 214 215 216
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
    *value = itr->second;
    return true;
  }
  return false;
}

217
Options LDBCommand::PrepareOptionsForOpenDB() {
218

219
  Options opt = options_;
220
  opt.create_if_missing = false;
221

222
  map<string, string>::const_iterator itr;
223

224
  BlockBasedTableOptions table_options;
S
sdong 已提交
225
  bool use_table_options = false;
226
  int bits;
227
  if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
228
    if (bits > 0) {
S
sdong 已提交
229
      use_table_options = true;
230
      table_options.filter_policy.reset(NewBloomFilterPolicy(bits));
231 232 233 234 235 236 237
    } else {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_BLOOM_BITS +
                      " must be > 0.");
    }
  }

  int block_size;
238
  if (ParseIntOption(option_map_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
239
    if (block_size > 0) {
S
sdong 已提交
240
      use_table_options = true;
241
      table_options.block_size = block_size;
242 243 244 245 246 247
    } else {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_BLOCK_SIZE +
                      " must be > 0.");
    }
  }

S
sdong 已提交
248 249 250 251
  if (use_table_options) {
    opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  }

252 253
  itr = option_map_.find(ARG_AUTO_COMPACTION);
  if (itr != option_map_.end()) {
254 255 256
    opt.disable_auto_compactions = ! StringToBool(itr->second);
  }

257 258
  itr = option_map_.find(ARG_COMPRESSION_TYPE);
  if (itr != option_map_.end()) {
259
    string comp = itr->second;
260
    if (comp == "no") {
261
      opt.compression = kNoCompression;
262
    } else if (comp == "snappy") {
263
      opt.compression = kSnappyCompression;
264
    } else if (comp == "zlib") {
265
      opt.compression = kZlibCompression;
266
    } else if (comp == "bzip2") {
267
      opt.compression = kBZip2Compression;
A
Albert Strasheim 已提交
268 269 270 271
    } else if (comp == "lz4") {
      opt.compression = kLZ4Compression;
    } else if (comp == "lz4hc") {
      opt.compression = kLZ4HCCompression;
272 273 274 275 276 277 278 279
    } else {
      // Unknown compression.
      exec_state_ = LDBCommandExecuteResult::FAILED(
                      "Unknown compression level: " + comp);
    }
  }

  int write_buffer_size;
280 281
  if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
        exec_state_)) {
282
    if (write_buffer_size > 0) {
283
      opt.write_buffer_size = write_buffer_size;
284 285 286 287 288 289 290
    } else {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_WRITE_BUFFER_SIZE +
                      " must be > 0.");
    }
  }

  int file_size;
291
  if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
292
    if (file_size > 0) {
293 294
      opt.target_file_size_base = file_size;
    } else {
295 296
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_FILE_SIZE +
                      " must be > 0.");
297 298 299
    }
  }

300
  if (opt.db_paths.size() == 0) {
301
    opt.db_paths.emplace_back(db_path_, std::numeric_limits<uint64_t>::max());
302 303
  }

S
sdong 已提交
304
  int fix_prefix_len;
305 306
  if (ParseIntOption(option_map_, ARG_FIX_PREFIX_LEN, fix_prefix_len,
                     exec_state_)) {
S
sdong 已提交
307 308 309 310
    if (fix_prefix_len > 0) {
      opt.prefix_extractor.reset(
          NewFixedPrefixTransform(static_cast<size_t>(fix_prefix_len)));
    } else {
311
      exec_state_ =
S
sdong 已提交
312 313 314 315
          LDBCommandExecuteResult::FAILED(ARG_FIX_PREFIX_LEN + " must be > 0.");
    }
  }

316 317 318
  return opt;
}

319 320
bool LDBCommand::ParseKeyValue(const string& line, string* key, string* value,
                              bool is_key_hex, bool is_value_hex) {
321
  size_t pos = line.find(DELIM);
322
  if (pos != string::npos) {
323 324 325 326 327 328 329 330 331 332 333 334 335
    *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;
  }
}
336

337 338 339 340 341 342 343 344 345
/**
 * 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() {

346 347
  for (map<string, string>::const_iterator itr = option_map_.begin();
        itr != option_map_.end(); ++itr) {
M
Mayank Agarwal 已提交
348
    if (find(valid_cmd_line_options_.begin(),
349
          valid_cmd_line_options_.end(), itr->first) ==
350 351 352 353 354
          valid_cmd_line_options_.end()) {
      fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
      return false;
    }
  }
355

356
  for (vector<string>::const_iterator itr = flags_.begin();
357
        itr != flags_.end(); ++itr) {
M
Mayank Agarwal 已提交
358
    if (find(valid_cmd_line_options_.begin(),
359
          valid_cmd_line_options_.end(), *itr) ==
360 361 362
          valid_cmd_line_options_.end()) {
      fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
      return false;
363 364 365
    }
  }

366
  if (!NoDBOpen() && option_map_.find(ARG_DB) == option_map_.end()) {
367 368 369 370 371 372 373
    fprintf(stderr, "%s must be specified\n", ARG_DB.c_str());
    return false;
  }

  return true;
}

374 375
CompactorCommand::CompactorCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
376 377
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_FROM, ARG_TO, ARG_HEX, ARG_KEY_HEX,
378
                                    ARG_VALUE_HEX, ARG_TTL})),
379
    null_from_(true), null_to_(true) {
380 381

  map<string, string>::const_iterator itr = options.find(ARG_FROM);
382 383 384 385 386 387 388 389 390 391 392 393
  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_) {
394 395 396 397 398 399 400 401 402
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

403 404 405 406 407
void CompactorCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(CompactorCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
408 409
}

410
void CompactorCommand::DoCommand() {
411

412 413
  Slice* begin = nullptr;
  Slice* end = nullptr;
414
  if (!null_from_) {
415
    begin = new Slice(from_);
416 417
  }
  if (!null_to_) {
418
    end = new Slice(to_);
419 420 421 422 423 424 425 426 427
  }

  db_->CompactRange(begin, end);
  exec_state_ = LDBCommandExecuteResult::SUCCEED("");

  delete begin;
  delete end;
}

428 429 430
const string DBLoaderCommand::ARG_DISABLE_WAL = "disable_wal";
const string DBLoaderCommand::ARG_BULK_LOAD = "bulk_load";
const string DBLoaderCommand::ARG_COMPACT = "compact";
Z
Zheng Shao 已提交
431

432 433
DBLoaderCommand::DBLoaderCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
434 435 436
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                    ARG_FROM, ARG_TO, ARG_CREATE_IF_MISSING,
437 438 439 440
                                    ARG_DISABLE_WAL, ARG_BULK_LOAD,
                                    ARG_COMPACT})),
    create_if_missing_(false), disable_wal_(false), bulk_load_(false),
    compact_(false) {
441 442 443

  create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
444 445
  bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  compact_ = IsFlagPresent(flags, ARG_COMPACT);
Z
Zheng Shao 已提交
446 447
}

448 449 450 451 452 453 454 455
void DBLoaderCommand::Help(string& ret) {
  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 已提交
456 457
}

458 459
Options DBLoaderCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
Z
Zheng Shao 已提交
460
  opt.create_if_missing = create_if_missing_;
461 462 463
  if (bulk_load_) {
    opt.PrepareForBulkLoad();
  }
Z
Zheng Shao 已提交
464 465 466
  return opt;
}

467
void DBLoaderCommand::DoCommand() {
Z
Zheng Shao 已提交
468 469 470 471 472 473 474 475 476 477
  if (!db_) {
    return;
  }

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

  int bad_lines = 0;
478 479 480 481
  string line;
  while (getline(cin, line, '\n')) {
    string key;
    string value;
482
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
Z
Zheng Shao 已提交
483 484 485 486 487 488 489 490 491
      db_->Put(write_options, Slice(key), Slice(value));
    } 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 ++;
    }
  }
492

Z
Zheng Shao 已提交
493
  if (bad_lines > 0) {
494
    cout << "Warning: " << bad_lines << " bad lines ignored." << endl;
Z
Zheng Shao 已提交
495
  }
496
  if (compact_) {
497
    db_->CompactRange(nullptr, nullptr);
498
  }
Z
Zheng Shao 已提交
499 500
}

501 502
// ----------------------------------------------------------------------------

503 504
const string ManifestDumpCommand::ARG_VERBOSE = "verbose";
const string ManifestDumpCommand::ARG_PATH    = "path";
505

506 507 508 509 510 511
void ManifestDumpCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ManifestDumpCommand::Name());
  ret.append(" [--" + ARG_VERBOSE + "]");
  ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  ret.append("\n");
512 513
}

514 515
ManifestDumpCommand::ManifestDumpCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
516
    LDBCommand(options, flags, false,
517
               BuildCmdLineOptions({ARG_VERBOSE, ARG_PATH, ARG_HEX})),
518
    verbose_(false),
519 520
    path_("")
{
521 522
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE);

523
  map<string, string>::const_iterator itr = options.find(ARG_PATH);
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
      exec_state_ = LDBCommandExecuteResult::FAILED("--path: missing pathname");
    }
  }
}

void ManifestDumpCommand::DoCommand() {

  std::string manifestfile;

  if (!path_.empty()) {
    manifestfile = path_;
  } else {
    bool found = false;
    // We need to find the manifest file by searching the directory
    // containing the db for files of the form MANIFEST_[0-9]+
    DIR* d = opendir(db_path_.c_str());
    if (d == nullptr) {
      exec_state_ = LDBCommandExecuteResult::FAILED(
        db_path_ + " is not a directory");
      return;
    }
    struct dirent* entry;
    while ((entry = readdir(d)) != nullptr) {
      unsigned int match;
      unsigned long long num;
K
Kai Liu 已提交
552 553 554 555
      if (sscanf(entry->d_name,
                 "MANIFEST-%ln%ln",
                 (unsigned long*)&num,
                 (unsigned long*)&match)
556 557 558 559 560 561 562
          && match == strlen(entry->d_name)) {
        if (!found) {
          manifestfile = db_path_ + "/" + std::string(entry->d_name);
          found = true;
        } else {
          exec_state_ = LDBCommandExecuteResult::FAILED(
            "Multiple MANIFEST files found; use --path to select one");
563
          closedir(d);
564 565 566 567 568 569 570 571 572 573 574 575
          return;
        }
      }
    }
    closedir(d);
  }

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

  Options options;
H
Haobo Xu 已提交
576
  EnvOptions sopt;
577 578
  std::string file(manifestfile);
  std::string dbname("dummy");
I
Igor Canadi 已提交
579 580 581
  std::shared_ptr<Cache> tc(NewLRUCache(
      options.max_open_files - 10, options.table_cache_numshardbits,
      options.table_cache_remove_scan_count_limit));
S
sdong 已提交
582 583 584 585
  // 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);
586 587
  WriteController wc;
  VersionSet versions(dbname, &options, sopt, tc.get(), &wc);
J
Jonah Cohen 已提交
588
  Status s = versions.DumpManifest(options, file, verbose_, is_key_hex_);
589 590 591 592 593 594 595 596 597 598
  if (!s.ok()) {
    printf("Error in processing file %s %s\n", manifestfile.c_str(),
           s.ToString().c_str());
  }
  if (verbose_) {
    printf("Processing Manifest file %s done\n", manifestfile.c_str());
  }
}

// ----------------------------------------------------------------------------
599

600 601 602 603 604
void ListColumnFamiliesCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ListColumnFamiliesCommand::Name());
  ret.append(" full_path_to_db_directory ");
  ret.append("\n");
605 606 607
}

ListColumnFamiliesCommand::ListColumnFamiliesCommand(
608 609
    const vector<string>& params, const map<string, string>& options,
    const vector<string>& flags)
610 611 612 613 614 615 616 617 618 619 620
    : LDBCommand(options, flags, false, {}) {

  if (params.size() != 1) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
        "dbname must be specified for the list_column_families command");
  } else {
    dbname_ = params[0];
  }
}

void ListColumnFamiliesCommand::DoCommand() {
621
  vector<string> column_families;
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
  Status s = DB::ListColumnFamilies(DBOptions(), dbname_, &column_families);
  if (!s.ok()) {
    printf("Error in processing db %s %s\n", dbname_.c_str(),
           s.ToString().c_str());
  } else {
    printf("Column families in %s: \n{", dbname_.c_str());
    bool first = true;
    for (auto cf : column_families) {
      if (!first) {
        printf(", ");
      }
      first = false;
      printf("%s", cf.c_str());
    }
    printf("}\n");
  }
}

// ----------------------------------------------------------------------------
641

I
Igor Canadi 已提交
642 643
namespace {

644
string ReadableTime(int unixtime) {
645 646 647 648
  char time_buffer [80];
  time_t rawtime = unixtime;
  struct tm * timeinfo = localtime(&rawtime);
  strftime(time_buffer, 80, "%c", timeinfo);
649
  return string(time_buffer);
650 651 652 653
}

// 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
654
void IncBucketCounts(vector<uint64_t>& bucket_counts, int ttl_start,
655 656 657 658
      int time_range, int bucket_size, int timekv, int num_buckets) {
  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;
659
  bucket_counts[bucket]++;
660 661
}

662 663
void PrintBucketCounts(const vector<uint64_t>& bucket_counts, int ttl_start,
      int ttl_end, int bucket_size, int num_buckets) {
664
  int time_point = ttl_start;
665 666
  for(int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
    fprintf(stdout, "Keys in range %s to %s : %lu\n",
667
            ReadableTime(time_point).c_str(),
K
Kai Liu 已提交
668
            ReadableTime(time_point + bucket_size).c_str(),
669
            (unsigned long)bucket_counts[i]);
670
  }
671
  fprintf(stdout, "Keys in range %s to %s : %lu\n",
672
          ReadableTime(time_point).c_str(),
K
Kai Liu 已提交
673
          ReadableTime(ttl_end).c_str(),
674
          (unsigned long)bucket_counts[num_buckets - 1]);
675 676
}

I
Igor Canadi 已提交
677 678
}  // namespace

679 680 681 682
const string InternalDumpCommand::ARG_COUNT_ONLY = "count_only";
const string InternalDumpCommand::ARG_COUNT_DELIM = "count_delim";
const string InternalDumpCommand::ARG_STATS = "stats";
const string InternalDumpCommand::ARG_INPUT_KEY_HEX = "input_key_hex";
683

684 685 686
InternalDumpCommand::InternalDumpCommand(const vector<string>& params,
                                         const map<string, string>& options,
                                         const vector<string>& flags) :
687
    LDBCommand(options, flags, true,
688 689 690 691
               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})),
692 693 694
    has_from_(false),
    has_to_(false),
    max_keys_(-1),
695
    delim_("."),
696
    count_only_(false),
697
    count_delim_(false),
698 699
    print_stats_(false),
    is_input_key_hex_(false) {
700 701 702 703

  has_from_ = ParseStringOption(options, ARG_FROM, &from_);
  has_to_ = ParseStringOption(options, ARG_TO, &to_);

704 705
  ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
  map<string, string>::const_iterator itr = options.find(ARG_COUNT_DELIM);
706 707 708
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
709
   // fprintf(stdout,"delim = %c\n",delim_[0]);
710 711
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
712
    delim_=".";
713
  }
714 715 716

  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
717
  is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
718

719
  if (is_input_key_hex_) {
720 721 722 723 724 725 726 727 728
    if (has_from_) {
      from_ = HexToString(from_);
    }
    if (has_to_) {
      to_ = HexToString(to_);
    }
  }
}

729 730 731 732 733 734 735 736 737 738
void InternalDumpCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(InternalDumpCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append(" [--" + ARG_INPUT_KEY_HEX + "]");
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  ret.append(" [--" + ARG_COUNT_ONLY + "]");
  ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
  ret.append(" [--" + ARG_STATS + "]");
  ret.append("\n");
739 740 741 742 743 744 745 746
}

void InternalDumpCommand::DoCommand() {
  if (!db_) {
    return;
  }

  if (print_stats_) {
747
    string stats;
748
    if (db_->GetProperty("rocksdb.stats", &stats)) {
749 750 751 752 753 754 755 756 757 758
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Cast as DBImpl to get internal iterator
  DBImpl* idb = dynamic_cast<DBImpl*>(db_);
  if (!idb) {
    exec_state_ = LDBCommandExecuteResult::FAILED("DB is not DBImpl");
    return;
  }
759
  string rtype1,rtype2,row,val;
760
  rtype2 = "";
761 762
  uint64_t c=0;
  uint64_t s1=0,s2=0;
763
  // Setup internal key iterator
764 765
  Arena arena;
  ScopedArenaIterator iter(idb->TEST_NewInternalIterator(&arena));
766 767 768 769 770 771 772 773 774 775 776 777 778
  Status st = iter->status();
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED("Iterator error:"
                                                  + st.ToString());
  }

  if (has_from_) {
    InternalKey ikey(from_, kMaxSequenceNumber, kValueTypeForSeek);
    iter->Seek(ikey.Encode());
  } else {
    iter->SeekToFirst();
  }

779
  long long count = 0;
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
  for (; iter->Valid(); iter->Next()) {
    ParsedInternalKey ikey;
    if (!ParseInternalKey(iter->key(), &ikey)) {
      fprintf(stderr, "Internal Key [%s] parse error!\n",
              iter->key().ToString(true /* in hex*/).data());
      // TODO: add error counter
      continue;
    }

    // If end marker was specified, we stop before it
    if (has_to_ && options_.comparator->Compare(ikey.user_key, to_) >= 0) {
      break;
    }

    ++count;
795 796 797
    int k;
    if (count_delim_) {
      rtype1 = "";
798
      s1=0;
799 800
      row = iter->key().ToString();
      val = iter->value().ToString();
801
      for(k=0;row[k]!='\x01' && row[k]!='\0';k++)
802
        s1++;
803
      for(k=0;val[k]!='\x01' && val[k]!='\0';k++)
804
        s1++;
805 806 807 808 809 810 811
      for(int j=0;row[j]!=delim_[0] && row[j]!='\0' && row[j]!='\x01';j++)
        rtype1+=row[j];
      if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
        fprintf(stdout,"%s => count:%lld\tsize:%lld\n",rtype2.c_str(),
            (long long)c,(long long)s2);
        c=1;
        s2=s1;
812 813 814
        rtype2 = rtype1;
      } else {
        c++;
815 816
        s2+=s1;
        rtype2=rtype1;
817 818
    }
  }
819

820
    if (!count_only_ && !count_delim_) {
821 822 823
      string key = ikey.DebugString(is_key_hex_);
      string value = iter->value().ToString(is_value_hex_);
      std::cout << key << " => " << value << "\n";
824 825 826
    }

    // Terminate if maximum number of keys have been dumped
827
    if (max_keys_ > 0 && count >= max_keys_) break;
828
  }
829 830 831
  if(count_delim_) {
    fprintf(stdout,"%s => count:%lld\tsize:%lld\n", rtype2.c_str(),
        (long long)c,(long long)s2);
832
  } else
833
  fprintf(stdout, "Internal keys in range: %lld\n", (long long) count);
834 835 836
}


837 838 839 840
const string DBDumperCommand::ARG_COUNT_ONLY = "count_only";
const string DBDumperCommand::ARG_COUNT_DELIM = "count_delim";
const string DBDumperCommand::ARG_STATS = "stats";
const string DBDumperCommand::ARG_TTL_BUCKET = "bucket";
841

842 843
DBDumperCommand::DBDumperCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
844
    LDBCommand(options, flags, true,
845 846 847 848 849 850
               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})),
851 852 853 854
    null_from_(true),
    null_to_(true),
    max_keys_(-1),
    count_only_(false),
855
    count_delim_(false),
856 857
    print_stats_(false) {

858
  map<string, string>::const_iterator itr = options.find(ARG_FROM);
859 860 861 862 863 864 865 866 867 868 869 870 871 872
  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 {
M
Mayank Agarwal 已提交
873
      max_keys_ = stoi(itr->second);
874
    } catch(const invalid_argument&) {
875 876
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has an invalid value");
877
    } catch(const out_of_range&) {
M
Mayank Agarwal 已提交
878
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
879
                        " has a value out-of-range");
880 881
    }
  }
882 883 884 885 886 887
  itr = options.find(ARG_COUNT_DELIM);
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
888
    delim_=".";
889
  }
890

891 892 893 894
  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);

  if (is_key_hex_) {
895 896 897 898 899 900 901 902 903
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

904 905 906 907 908 909 910 911 912 913 914 915 916 917
void DBDumperCommand::Help(string& ret) {
  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]");
  ret.append("\n");
918 919
}

920
void DBDumperCommand::DoCommand() {
921 922 923
  if (!db_) {
    return;
  }
924 925 926
  // Parse command line args
  uint64_t count = 0;
  if (print_stats_) {
927
    string stats;
928
    if (db_->GetProperty("rocksdb.stats", &stats)) {
929 930 931 932 933
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Setup key iterator
934 935
  Iterator* iter = db_->NewIterator(ReadOptions());
  Status st = iter->status();
936 937 938 939 940 941 942 943 944 945 946 947
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED("Iterator error."
        + st.ToString());
  }

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

  int max_keys = max_keys_;
948
  int ttl_start;
949
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
950
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
951 952
  }
  int ttl_end;
953
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
954
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
955 956 957 958 959 960 961 962
  }
  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;
963
  if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
964 965 966
      bucket_size <= 0) {
    bucket_size = time_range; // Will have just 1 bucket by default
  }
967
  //cretaing variables for row count of each type
968
  string rtype1,rtype2,row,val;
969
  rtype2 = "";
970 971
  uint64_t c=0;
  uint64_t s1=0,s2=0;
972

973
  // At this point, bucket_size=0 => time_range=0
974 975 976
  int num_buckets = (bucket_size >= time_range)
                        ? 1
                        : ((time_range + bucket_size - 1) / bucket_size);
977
  vector<uint64_t> bucket_counts(num_buckets, 0);
978
  if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
979 980 981 982
    fprintf(stdout, "Dumping key-values from %s to %s\n",
            ReadableTime(ttl_start).c_str(), ReadableTime(ttl_end).c_str());
  }

983
  for (; iter->Valid(); iter->Next()) {
984
    int rawtime = 0;
985 986 987 988 989 990
    // 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;
991
    if (is_db_ttl_) {
992 993
      TtlIterator* it_ttl = dynamic_cast<TtlIterator*>(iter);
      assert(it_ttl);
994 995
      rawtime = it_ttl->timestamp();
      if (rawtime < ttl_start || rawtime >= ttl_end) {
996 997 998
        continue;
      }
    }
999 1000 1001
    if (max_keys > 0) {
      --max_keys;
    }
1002
    if (is_db_ttl_ && num_buckets > 1) {
1003
      IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
1004 1005
                      rawtime, num_buckets);
    }
1006
    ++count;
1007 1008 1009 1010 1011
    if (count_delim_) {
      rtype1 = "";
      row = iter->key().ToString();
      val = iter->value().ToString();
      s1 = row.size()+val.size();
1012 1013 1014 1015 1016 1017 1018
      for(int j=0;row[j]!=delim_[0] && row[j]!='\0';j++)
        rtype1+=row[j];
      if(rtype2.compare("") && rtype2.compare(rtype1)!=0) {
        fprintf(stdout,"%s => count:%lld\tsize:%lld\n",rtype2.c_str(),
            (long long )c,(long long)s2);
        c=1;
        s2=s1;
1019 1020
        rtype2 = rtype1;
      } else {
1021 1022 1023
          c++;
          s2+=s1;
          rtype2=rtype1;
1024
      }
1025

1026 1027
    }

1028 1029


1030
    if (!count_only_ && !count_delim_) {
1031 1032 1033
      if (is_db_ttl_ && timestamp_) {
        fprintf(stdout, "%s ", ReadableTime(rawtime).c_str());
      }
1034
      string str = PrintKeyValue(iter->key().ToString(),
1035 1036
                                 iter->value().ToString(), is_key_hex_,
                                 is_value_hex_);
1037
      fprintf(stdout, "%s\n", str.c_str());
1038 1039
    }
  }
1040

1041
  if (num_buckets > 1 && is_db_ttl_) {
1042
    PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
1043
                      num_buckets);
1044 1045 1046
  } else if(count_delim_) {
    fprintf(stdout,"%s => count:%lld\tsize:%lld\n",rtype2.c_str(),
        (long long )c,(long long)s2);
1047
  } else {
1048
    fprintf(stdout, "Keys in range: %lld\n", (long long) count);
1049
  }
1050 1051 1052 1053
  // Clean up
  delete iter;
}

1054 1055
const string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
const string  ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS = "print_old_levels";
1056

1057 1058
ReduceDBLevelsCommand::ReduceDBLevelsCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1059 1060 1061 1062 1063
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_NEW_LEVELS, ARG_PRINT_OLD_LEVELS})),
    old_levels_(1 << 16),
    new_levels_(-1),
    print_old_levels_(false) {
1064 1065


1066
  ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
1067
  print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
1068

1069
  if(new_levels_ <= 0) {
1070
    exec_state_ = LDBCommandExecuteResult::FAILED(
1071
           " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
1072 1073 1074
  }
}

1075
vector<string> ReduceDBLevelsCommand::PrepareArgs(const string& db_path,
1076
    int new_levels, bool print_old_level) {
1077
  vector<string> ret;
1078
  ret.push_back("reduce_levels");
1079 1080 1081
  ret.push_back("--" + ARG_DB + "=" + db_path);
  ret.push_back("--" + ARG_NEW_LEVELS + "=" + to_string(new_levels));
  if(print_old_level) {
1082
    ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
1083 1084 1085 1086
  }
  return ret;
}

1087 1088 1089 1090 1091 1092
void ReduceDBLevelsCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ReduceDBLevelsCommand::Name());
  ret.append(" --" + ARG_NEW_LEVELS + "=<New number of levels>");
  ret.append(" [--" + ARG_PRINT_OLD_LEVELS + "]");
  ret.append("\n");
1093 1094
}

1095 1096
Options ReduceDBLevelsCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1097
  opt.num_levels = old_levels_;
1098
  opt.max_bytes_for_level_multiplier_additional.resize(opt.num_levels, 1);
1099
  // Disable size compaction
I
Igor Canadi 已提交
1100
  opt.max_bytes_for_level_base = 1ULL << 50;
1101 1102
  opt.max_bytes_for_level_multiplier = 1;
  opt.max_mem_compaction_level = 0;
1103 1104 1105
  return opt;
}

1106
Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt,
1107
    int* levels) {
H
Haobo Xu 已提交
1108
  EnvOptions soptions;
I
Igor Canadi 已提交
1109 1110 1111
  std::shared_ptr<Cache> tc(
      NewLRUCache(opt.max_open_files - 10, opt.table_cache_numshardbits,
                  opt.table_cache_remove_scan_count_limit));
1112
  const InternalKeyComparator cmp(opt.comparator);
1113 1114
  WriteController wc;
  VersionSet versions(db_path_, &opt, soptions, tc.get(), &wc);
I
Igor Canadi 已提交
1115
  std::vector<ColumnFamilyDescriptor> dummy;
1116
  ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName,
I
Igor Canadi 已提交
1117 1118
                                          ColumnFamilyOptions(opt));
  dummy.push_back(dummy_descriptor);
1119 1120 1121
  // 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 已提交
1122
  Status st = versions.Recover(dummy);
1123 1124 1125 1126
  if (!st.ok()) {
    return st;
  }
  int max = -1;
1127
  auto default_cfd = versions.GetColumnFamilySet()->GetDefault();
I
Igor Canadi 已提交
1128
  for (int i = 0; i < default_cfd->NumberLevels(); i++) {
S
sdong 已提交
1129
    if (default_cfd->current()->storage_info()->NumLevelFiles(i)) {
1130 1131 1132 1133 1134 1135 1136 1137
      max = i;
    }
  }

  *levels = max + 1;
  return st;
}

1138
void ReduceDBLevelsCommand::DoCommand() {
1139 1140 1141 1142 1143 1144
  if (new_levels_ <= 1) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
        "Invalid number of levels.\n");
    return;
  }

1145 1146
  Status st;
  Options opt = PrepareOptionsForOpenDB();
1147 1148 1149 1150 1151 1152 1153
  int old_level_num = -1;
  st = GetOldNumOfLevels(opt, &old_level_num);
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
    return;
  }

1154
  if (print_old_levels_) {
1155
    fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
1156
  }
1157

1158 1159
  if (old_level_num <= new_levels_) {
    return;
1160 1161
  }

1162 1163 1164
  old_levels_ = old_level_num;

  OpenDB();
1165 1166 1167
  if (!db_) {
    return;
  }
1168
  // Compact the whole DB to put all files to the highest level.
1169
  fprintf(stdout, "Compacting the db...\n");
1170
  db_->CompactRange(nullptr, nullptr);
1171 1172
  CloseDB();

H
Haobo Xu 已提交
1173
  EnvOptions soptions;
1174
  st = VersionSet::ReduceNumberOfLevels(db_path_, &opt, soptions, new_levels_);
1175 1176 1177 1178 1179 1180
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
    return;
  }
}

1181
const string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
1182
  "old_compaction_style";
1183
const string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
1184 1185 1186
  "new_compaction_style";

ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
1187 1188
      const vector<string>& params, const map<string, string>& options,
      const vector<string>& flags) :
1189 1190 1191 1192 1193 1194
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_OLD_COMPACTION_STYLE,
                                    ARG_NEW_COMPACTION_STYLE})),
    old_compaction_style_(-1),
    new_compaction_style_(-1) {

1195 1196
  ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
    exec_state_);
1197 1198 1199 1200 1201 1202 1203 1204
  if (old_compaction_style_ != kCompactionStyleLevel &&
     old_compaction_style_ != kCompactionStyleUniversal) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
      "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
      "style. Check ldb help for proper compaction style value.\n");
    return;
  }

1205 1206
  ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
    exec_state_);
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
  if (new_compaction_style_ != kCompactionStyleLevel &&
     new_compaction_style_ != kCompactionStyleUniversal) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
      "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
      "style. Check ldb help for proper compaction style value.\n");
    return;
  }

  if (new_compaction_style_ == old_compaction_style_) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
      "Old compaction style is the same as new compaction style. "
      "Nothing to do.\n");
    return;
  }

  if (old_compaction_style_ == kCompactionStyleUniversal &&
      new_compaction_style_ == kCompactionStyleLevel) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
      "Convert from universal compaction to level compaction. "
      "Nothing to do.\n");
    return;
  }
}

1231 1232 1233 1234 1235 1236 1237 1238
void ChangeCompactionStyleCommand::Help(string& ret) {
  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");
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
}

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

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

  return opt;
}

void ChangeCompactionStyleCommand::DoCommand() {
  // print db stats before we have made any change
  std::string property;
  std::string files_per_level;
  for (int i = 0; i < db_->NumberLevels(); i++) {
1263
    db_->GetProperty("rocksdb.num-files-at-level" + NumberToString(i),
1264 1265
                     &property);

1266
    // format print string
1267
    char buf[100];
1268
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
    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
  db_->CompactRange(nullptr, nullptr,
                    true /* reduce level */,
                    0    /* reduce to level 0 */);

  // verify compaction result
  files_per_level = "";
  int num_files = 0;
  for (int i = 0; i < db_->NumberLevels(); i++) {
1283
    db_->GetProperty("rocksdb.num-files-at-level" + NumberToString(i),
1284 1285
                     &property);

1286
    // format print string
1287
    char buf[100];
1288
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
1289 1290 1291 1292 1293 1294 1295
    files_per_level += buf;

    num_files = atoi(property.c_str());

    // level 0 should have only 1 file
    if (i == 0 && num_files != 1) {
      exec_state_ = LDBCommandExecuteResult::FAILED("Number of db files at "
1296 1297
        "level 0 after compaction is " + std::to_string(num_files) +
        ", not 1.\n");
1298 1299 1300 1301 1302
      return;
    }
    // other levels should have no file
    if (i > 0 && num_files != 0) {
      exec_state_ = LDBCommandExecuteResult::FAILED("Number of db files at "
1303 1304
        "level " + std::to_string(i) + " after compaction is " +
        std::to_string(num_files) + ", not 0.\n");
1305 1306 1307 1308 1309 1310 1311 1312
      return;
    }
  }

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

1313 1314
class InMemoryHandler : public WriteBatch::Handler {
 public:
1315
  InMemoryHandler(stringstream& row, bool print_values) : Handler(),row_(row) {
1316 1317
    print_values_ = print_values;
  }
1318

1319
  void commonPutMerge(const Slice& key, const Slice& value) {
1320
    string k = LDBCommand::StringToHex(key.ToString());
1321
    if (print_values_) {
1322
      string v = LDBCommand::StringToHex(value.ToString());
1323 1324 1325 1326 1327
      row_ << k << " : ";
      row_ << v << " ";
    } else {
      row_ << k << " ";
    }
1328
  }
1329 1330 1331 1332

  virtual void Put(const Slice& key, const Slice& value) {
    row_ << "PUT : ";
    commonPutMerge(key, value);
1333 1334
  }

1335 1336 1337
  virtual void Merge(const Slice& key, const Slice& value) {
    row_ << "MERGE : ";
    commonPutMerge(key, value);
1338
  }
1339 1340

  virtual void Delete(const Slice& key) {
1341
    row_ <<",DELETE : ";
1342
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
1343 1344
  }

1345 1346
  virtual ~InMemoryHandler() { };

1347
 private:
1348
  stringstream & row_;
1349
  bool print_values_;
1350 1351
};

1352 1353 1354
const string WALDumperCommand::ARG_WAL_FILE = "walfile";
const string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
const string WALDumperCommand::ARG_PRINT_HEADER = "header";
1355

1356 1357
WALDumperCommand::WALDumperCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1358
    LDBCommand(options, flags, true,
1359 1360 1361
               BuildCmdLineOptions(
                {ARG_WAL_FILE, ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
    print_header_(false), print_values_(false) {
1362

A
Abhishek Kona 已提交
1363
  wal_file_.clear();
1364

1365
  map<string, string>::const_iterator itr = options.find(ARG_WAL_FILE);
1366 1367
  if (itr != options.end()) {
    wal_file_ = itr->second;
A
Abhishek Kona 已提交
1368
  }
1369 1370


1371 1372
  print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
A
Abhishek Kona 已提交
1373
  if (wal_file_.empty()) {
1374 1375
    exec_state_ = LDBCommandExecuteResult::FAILED(
                    "Argument " + ARG_WAL_FILE + " must be specified.");
A
Abhishek Kona 已提交
1376 1377 1378
  }
}

1379 1380 1381 1382 1383 1384 1385
void WALDumperCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(WALDumperCommand::Name());
  ret.append(" --" + ARG_WAL_FILE + "=<write_ahead_log_file_path>");
  ret.append(" [--" + ARG_PRINT_HEADER + "] ");
  ret.append(" [--" + ARG_PRINT_VALUE + "] ");
  ret.append("\n");
A
Abhishek Kona 已提交
1386 1387
}

1388
void WALDumperCommand::DoCommand() {
A
Abhishek Kona 已提交
1389 1390
  struct StdErrReporter : public log::Reader::Reporter {
    virtual void Corruption(size_t bytes, const Status& s) {
1391
      cerr<<"Corruption detected in log file "<<s.ToString()<<"\n";
A
Abhishek Kona 已提交
1392 1393 1394
    }
  };

1395
  unique_ptr<SequentialFile> file;
A
Abhishek Kona 已提交
1396
  Env* env_ = Env::Default();
H
Haobo Xu 已提交
1397
  EnvOptions soptions;
1398
  Status status = env_->NewSequentialFile(wal_file_, &file, soptions);
A
Abhishek Kona 已提交
1399
  if (!status.ok()) {
1400 1401
    exec_state_ = LDBCommandExecuteResult::FAILED("Failed to open WAL file " +
      status.ToString());
A
Abhishek Kona 已提交
1402 1403
  } else {
    StdErrReporter reporter;
M
Mayank Agarwal 已提交
1404
    log::Reader reader(move(file), &reporter, true, 0);
1405
    string scratch;
A
Abhishek Kona 已提交
1406 1407
    WriteBatch batch;
    Slice record;
1408
    stringstream row;
A
Abhishek Kona 已提交
1409
    if (print_header_) {
1410
      cout<<"Sequence,Count,ByteSize,Physical Offset,Key(s)";
1411
      if (print_values_) {
1412
        cout << " : value ";
1413
      }
1414
      cout << "\n";
A
Abhishek Kona 已提交
1415 1416
    }
    while(reader.ReadRecord(&record, &scratch)) {
1417
      row.str("");
A
Abhishek Kona 已提交
1418 1419 1420 1421 1422
      if (record.size() < 12) {
        reporter.Corruption(
            record.size(), Status::Corruption("log record too small"));
      } else {
        WriteBatchInternal::SetContents(&batch, record);
1423 1424 1425 1426
        row<<WriteBatchInternal::Sequence(&batch)<<",";
        row<<WriteBatchInternal::Count(&batch)<<",";
        row<<WriteBatchInternal::ByteSize(&batch)<<",";
        row<<reader.LastRecordOffset()<<",";
1427
        InMemoryHandler handler(row, print_values_);
1428
        batch.Iterate(&handler);
1429
        row<<"\n";
A
Abhishek Kona 已提交
1430
      }
1431
      cout<<row.str();
A
Abhishek Kona 已提交
1432 1433 1434 1435
    }
  }
}

1436

1437 1438
GetCommand::GetCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1439 1440 1441
  LDBCommand(options, flags, true, BuildCmdLineOptions({ARG_TTL, ARG_HEX,
                                                        ARG_KEY_HEX,
                                                        ARG_VALUE_HEX})) {
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454

  if (params.size() != 1) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
                    "<key> must be specified for the get command");
  } else {
    key_ = params.at(0);
  }

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

1455 1456 1457 1458 1459 1460
void GetCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(GetCommand::Name());
  ret.append(" <key>");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
1461 1462 1463
}

void GetCommand::DoCommand() {
1464
  string value;
1465
  Status st = db_->Get(ReadOptions(), key_, &value);
1466 1467 1468 1469 1470 1471 1472 1473 1474
  if (st.ok()) {
    fprintf(stdout, "%s\n",
              (is_value_hex_ ? StringToHex(value) : value).c_str());
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}


1475 1476
ApproxSizeCommand::ApproxSizeCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
  LDBCommand(options, flags, true,
             BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                  ARG_FROM, ARG_TO})) {

  if (options.find(ARG_FROM) != options.end()) {
    start_key_ = options.find(ARG_FROM)->second;
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(ARG_FROM +
                    " must be specified for approxsize command");
    return;
  }

  if (options.find(ARG_TO) != options.end()) {
    end_key_ = options.find(ARG_TO)->second;
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(ARG_TO +
                    " must be specified for approxsize command");
    return;
  }

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

1503 1504 1505 1506 1507
void ApproxSizeCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ApproxSizeCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
1508 1509 1510 1511
}

void ApproxSizeCommand::DoCommand() {

1512 1513
  Range ranges[1];
  ranges[0] = Range(start_key_, end_key_);
1514 1515
  uint64_t sizes[1];
  db_->GetApproximateSizes(ranges, 1, sizes);
K
Kai Liu 已提交
1516
  fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
1517
  /* Weird that GetApproximateSizes() returns void, although documentation
1518 1519 1520 1521 1522 1523 1524 1525
   * says that it returns a Status object.
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
  */
}


1526 1527 1528 1529 1530
BatchPutCommand::BatchPutCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
  LDBCommand(options, flags, false,
             BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                  ARG_CREATE_IF_MISSING})) {
1531 1532 1533

  if (params.size() < 2) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
1534
        "At least one <key> <value> pair must be specified batchput.");
1535 1536 1537 1538 1539
  } else if (params.size() % 2 != 0) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
        "Equal number of <key>s and <value>s must be specified for batchput.");
  } else {
    for (size_t i = 0; i < params.size(); i += 2) {
1540 1541 1542
      string key = params.at(i);
      string value = params.at(i+1);
      key_values_.push_back(pair<string, string>(
1543 1544 1545 1546 1547 1548
                    is_key_hex_ ? HexToString(key) : key,
                    is_value_hex_ ? HexToString(value) : value));
    }
  }
}

1549 1550 1551 1552 1553 1554
void BatchPutCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(BatchPutCommand::Name());
  ret.append(" <key> <value> [<key> <value>] [..]");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
1555 1556 1557
}

void BatchPutCommand::DoCommand() {
1558
  WriteBatch batch;
1559

1560
  for (vector<pair<string, string>>::const_iterator itr
1561
        = key_values_.begin(); itr != key_values_.end(); ++itr) {
1562
      batch.Put(itr->first, itr->second);
1563
  }
1564
  Status st = db_->Write(WriteOptions(), &batch);
1565 1566 1567 1568 1569 1570 1571
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}

1572 1573
Options BatchPutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1574 1575 1576 1577 1578
  opt.create_if_missing = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  return opt;
}


1579 1580
ScanCommand::ScanCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1581
    LDBCommand(options, flags, true,
1582 1583 1584
               BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_TO,
                                    ARG_VALUE_HEX, ARG_FROM, ARG_TIMESTAMP,
                                    ARG_MAX_KEYS, ARG_TTL_START, ARG_TTL_END})),
1585 1586 1587 1588
    start_key_specified_(false),
    end_key_specified_(false),
    max_keys_scanned_(-1) {

1589
  map<string, string>::const_iterator itr = options.find(ARG_FROM);
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
  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;
  }

  itr = options.find(ARG_MAX_KEYS);
  if (itr != options.end()) {
    try {
M
Mayank Agarwal 已提交
1609
      max_keys_scanned_ = stoi(itr->second);
1610
    } catch(const invalid_argument&) {
1611 1612
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has an invalid value");
1613
    } catch(const out_of_range&) {
M
Mayank Agarwal 已提交
1614 1615
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has a value out-of-range");
1616 1617 1618 1619
    }
  }
}

1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
void ScanCommand::Help(string& ret) {
  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]");
  ret.append("\n");
1630 1631 1632 1633 1634
}

void ScanCommand::DoCommand() {

  int num_keys_scanned = 0;
1635
  Iterator* it = db_->NewIterator(ReadOptions());
1636 1637 1638 1639 1640
  if (start_key_specified_) {
    it->Seek(start_key_);
  } else {
    it->SeekToFirst();
  }
1641
  int ttl_start;
1642
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
1643
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
1644 1645
  }
  int ttl_end;
1646
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
1647
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
  }
  if (ttl_end < ttl_start) {
    fprintf(stderr, "Error: End time can't be less than start time\n");
    delete it;
    return;
  }
  if (is_db_ttl_ && timestamp_) {
    fprintf(stdout, "Scanning key-values from %s to %s\n",
            ReadableTime(ttl_start).c_str(), ReadableTime(ttl_end).c_str());
  }
1658
  for ( ;
1659 1660 1661
        it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
        it->Next()) {
    string key = ldb_options_.key_formatter->Format(it->key());
1662
    if (is_db_ttl_) {
1663 1664
      TtlIterator* it_ttl = dynamic_cast<TtlIterator*>(it);
      assert(it_ttl);
1665 1666
      int rawtime = it_ttl->timestamp();
      if (rawtime < ttl_start || rawtime >= ttl_end) {
1667 1668 1669 1670 1671 1672
        continue;
      }
      if (timestamp_) {
        fprintf(stdout, "%s ", ReadableTime(rawtime).c_str());
      }
    }
1673
    string value = it->value().ToString();
1674
    fprintf(stdout, "%s : %s\n",
1675
            (is_key_hex_ ? "0x" + it->key().ToString(true) : key).c_str(),
1676 1677
            (is_value_hex_ ? StringToHex(value) : value).c_str()
        );
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
    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
    exec_state_ = LDBCommandExecuteResult::FAILED(it->status().ToString());
  }
  delete it;
}


1690 1691
DeleteCommand::DeleteCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
  LDBCommand(options, flags, false,
             BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {

  if (params.size() != 1) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
                    "KEY must be specified for the delete command");
  } else {
    key_ = params.at(0);
    if (is_key_hex_) {
      key_ = HexToString(key_);
    }
  }
}

1706 1707 1708 1709
void DeleteCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DeleteCommand::Name() + " <key>");
  ret.append("\n");
1710 1711 1712
}

void DeleteCommand::DoCommand() {
1713
  Status st = db_->Delete(WriteOptions(), key_);
1714 1715 1716 1717 1718 1719 1720 1721
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}


1722 1723
PutCommand::PutCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1724
  LDBCommand(options, flags, false,
1725
             BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
                                  ARG_CREATE_IF_MISSING})) {

  if (params.size() != 2) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
                    "<key> and <value> must be specified for the put command");
  } else {
    key_ = params.at(0);
    value_ = params.at(1);
  }

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

  if (is_value_hex_) {
    value_ = HexToString(value_);
  }
}

1745 1746 1747 1748 1749 1750
void PutCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(PutCommand::Name());
  ret.append(" <key> <value> ");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
1751 1752 1753
}

void PutCommand::DoCommand() {
1754
  Status st = db_->Put(WriteOptions(), key_, value_);
1755 1756 1757 1758 1759 1760 1761
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}

1762 1763
Options PutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
  opt.create_if_missing = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  return opt;
}


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

1774 1775
DBQuerierCommand::DBQuerierCommand(const vector<string>& params,
    const map<string, string>& options, const vector<string>& flags) :
1776
  LDBCommand(options, flags, false,
1777 1778
             BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
                                  ARG_VALUE_HEX})) {
1779 1780 1781

}

1782 1783 1784 1785 1786 1787
void DBQuerierCommand::Help(string& ret) {
  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 "
1788
             "commands.");
1789
  ret.append("\n");
1790 1791 1792 1793 1794 1795
}

void DBQuerierCommand::DoCommand() {
  if (!db_) {
    return;
  }
1796

1797 1798
  ReadOptions read_options;
  WriteOptions write_options;
1799

1800 1801 1802 1803 1804 1805 1806
  string line;
  string key;
  string value;
  while (getline(cin, line, '\n')) {

    // Parse line into vector<string>
    vector<string> tokens;
1807 1808 1809
    size_t pos = 0;
    while (true) {
      size_t pos2 = line.find(' ', pos);
1810
      if (pos2 == string::npos) {
1811 1812 1813 1814 1815 1816 1817
        break;
      }
      tokens.push_back(line.substr(pos, pos2-pos));
      pos = pos2 + 1;
    }
    tokens.push_back(line.substr(pos));

1818
    const string& cmd = tokens[0];
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848

    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]);
      db_->Delete(write_options, Slice(key));
      fprintf(stdout, "Successfully deleted %s\n", tokens[1].c_str());
    } else if (cmd == PUT_CMD && tokens.size() == 3) {
      key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
      value = (is_value_hex_ ? HexToString(tokens[2]) : tokens[2]);
      db_->Put(write_options, Slice(key), Slice(value));
      fprintf(stdout, "Successfully put %s %s\n",
              tokens[1].c_str(), tokens[2].c_str());
    } else if (cmd == GET_CMD && tokens.size() == 2) {
      key = (is_key_hex_ ? HexToString(tokens[1]) : tokens[1]);
      if (db_->Get(read_options, Slice(key), &value).ok()) {
        fprintf(stdout, "%s\n", PrintKeyValue(key, value,
              is_key_hex_, is_value_hex_).c_str());
      } else {
        fprintf(stdout, "Not found %s\n", tokens[1].c_str());
      }
    } else {
      fprintf(stdout, "Unknown command %s\n", line.c_str());
    }
  }
}

1849 1850
CheckConsistencyCommand::CheckConsistencyCommand(const vector<string>& params,
    const map<string, string>& options, const vector<string>& flags) :
Y
Yiting Li 已提交
1851 1852 1853 1854
  LDBCommand(options, flags, false,
             BuildCmdLineOptions({})) {
}

1855 1856 1857 1858
void CheckConsistencyCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(CheckConsistencyCommand::Name());
  ret.append("\n");
Y
Yiting Li 已提交
1859
}
1860

Y
Yiting Li 已提交
1861 1862
void CheckConsistencyCommand::DoCommand() {
  Options opt = PrepareOptionsForOpenDB();
I
Igor Canadi 已提交
1863
  opt.paranoid_checks = true;
Y
Yiting Li 已提交
1864 1865 1866
  if (!exec_state_.IsNotStarted()) {
    return;
  }
I
Igor Canadi 已提交
1867 1868 1869
  DB* db;
  Status st = DB::OpenForReadOnly(opt, db_path_, &db, false);
  delete db;
Y
Yiting Li 已提交
1870 1871 1872 1873 1874
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
1875
}
Y
Yiting Li 已提交
1876 1877

}   // namespace rocksdb
I
Igor Canadi 已提交
1878
#endif  // ROCKSDB_LITE