ldb_cmd.cc 64.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 10 11 12 13 14
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <inttypes.h>

A
Abhishek Kona 已提交
15
#include "db/dbformat.h"
16
#include "db/db_impl.h"
A
Abhishek Kona 已提交
17
#include "db/log_reader.h"
18
#include "db/filename.h"
19
#include "db/writebuffer.h"
A
Abhishek Kona 已提交
20
#include "db/write_batch_internal.h"
21
#include "rocksdb/write_batch.h"
I
Igor Canadi 已提交
22
#include "rocksdb/cache.h"
23
#include "rocksdb/table_properties.h"
D
Dmitri Smirnov 已提交
24
#include "port/dirent.h"
25
#include "util/coding.h"
26
#include "util/sst_dump_tool_imp.h"
S
sdong 已提交
27
#include "util/string_util.h"
28
#include "util/scoped_arena_iterator.h"
29
#include "utilities/ttl/db_ttl_impl.h"
30

S
sdong 已提交
31
#include <cstdlib>
32 33 34 35 36 37
#include <ctime>
#include <limits>
#include <sstream>
#include <string>
#include <stdexcept>

38
namespace rocksdb {
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
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";
58
const string LDBCommand::ARG_DB_WRITE_BUFFER_SIZE = "db_write_buffer_size";
59 60 61
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";
62

63
const char* LDBCommand::DELIM = " ==> ";
64

65
LDBCommand* LDBCommand::InitFromCmdLineArgs(
66 67 68 69 70 71
  int argc,
  char** argv,
  const Options& options,
  const LDBOptions& ldb_options
) {
  vector<string> args;
72 73 74
  for (int i = 1; i < argc; i++) {
    args.push_back(argv[i]);
  }
75
  return InitFromCmdLineArgs(args, options, ldb_options);
76 77 78 79 80 81
}

/**
 * Parse the command-line arguments and create the appropriate LDBCommand2
 * instance.
 * The command line arguments must be in the following format:
82 83
 * ./ldb --db=PATH_TO_DB [--commonOpt1=commonOpt1Val] ..
 *        COMMAND <PARAM1> <PARAM2> ... [-cmdSpecificOpt1=cmdSpecificOpt1Val] ..
84 85
 * This is similar to the command line format used by HBaseClientTool.
 * Command name is not included in args.
86
 * Returns nullptr if the command-line cannot be parsed.
87
 */
88
LDBCommand* LDBCommand::InitFromCmdLineArgs(
89 90 91 92 93 94
  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;
95 96

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

99
  // Everything other than option_map and flags. Represents commands
100 101
  // and their parameters.  For eg: put key1 value1 go into this vector.
  vector<string> cmdTokens;
102

103
  const string OPTION_PREFIX = "--";
104

105
  for (const auto& arg : args) {
106
    if (arg[0] == '-' && arg[1] == '-'){
I
Igor Canadi 已提交
107
      vector<string> splits = StringSplit(arg, '=');
108
      if (splits.size() == 2) {
109
        string optionKey = splits[0].substr(OPTION_PREFIX.size());
110
        option_map[optionKey] = splits[1];
111
      } else {
112
        string optionKey = splits[0].substr(OPTION_PREFIX.size());
113 114
        flags.push_back(optionKey);
      }
115
    } else {
116
      cmdTokens.push_back(arg);
117 118 119 120 121
    }
  }

  if (cmdTokens.size() < 1) {
    fprintf(stderr, "Command not specified!");
122
    return nullptr;
123 124
  }

125 126
  string cmd = cmdTokens[0];
  vector<string> cmdParams(cmdTokens.begin()+1, cmdTokens.end());
127
  LDBCommand* command = LDBCommand::SelectCommand(
128 129 130 131 132
    cmd,
    cmdParams,
    option_map,
    flags
  );
133 134

  if (command) {
135 136
    command->SetDBOptions(options);
    command->SetLDBOptions(ldb_options);
137 138 139 140 141 142
  }
  return command;
}

LDBCommand* LDBCommand::SelectCommand(
    const std::string& cmd,
143 144 145 146 147
    const vector<string>& cmdParams,
    const map<string, string>& option_map,
    const vector<string>& flags
  ) {

148
  if (cmd == GetCommand::Name()) {
149
    return new GetCommand(cmdParams, option_map, flags);
150
  } else if (cmd == PutCommand::Name()) {
151
    return new PutCommand(cmdParams, option_map, flags);
152
  } else if (cmd == BatchPutCommand::Name()) {
153
    return new BatchPutCommand(cmdParams, option_map, flags);
154
  } else if (cmd == ScanCommand::Name()) {
155
    return new ScanCommand(cmdParams, option_map, flags);
156
  } else if (cmd == DeleteCommand::Name()) {
157
    return new DeleteCommand(cmdParams, option_map, flags);
158
  } else if (cmd == ApproxSizeCommand::Name()) {
159
    return new ApproxSizeCommand(cmdParams, option_map, flags);
160
  } else if (cmd == DBQuerierCommand::Name()) {
161
    return new DBQuerierCommand(cmdParams, option_map, flags);
162
  } else if (cmd == CompactorCommand::Name()) {
163
    return new CompactorCommand(cmdParams, option_map, flags);
164
  } else if (cmd == WALDumperCommand::Name()) {
165
    return new WALDumperCommand(cmdParams, option_map, flags);
166
  } else if (cmd == ReduceDBLevelsCommand::Name()) {
167
    return new ReduceDBLevelsCommand(cmdParams, option_map, flags);
168 169
  } else if (cmd == ChangeCompactionStyleCommand::Name()) {
    return new ChangeCompactionStyleCommand(cmdParams, option_map, flags);
170
  } else if (cmd == DBDumperCommand::Name()) {
171
    return new DBDumperCommand(cmdParams, option_map, flags);
172
  } else if (cmd == DBLoaderCommand::Name()) {
173
    return new DBLoaderCommand(cmdParams, option_map, flags);
174
  } else if (cmd == ManifestDumpCommand::Name()) {
175
    return new ManifestDumpCommand(cmdParams, option_map, flags);
176 177
  } else if (cmd == ListColumnFamiliesCommand::Name()) {
    return new ListColumnFamiliesCommand(cmdParams, option_map, flags);
178 179
  } else if (cmd == DBFileDumperCommand::Name()) {
    return new DBFileDumperCommand(cmdParams, option_map, flags);
180 181
  } else if (cmd == InternalDumpCommand::Name()) {
    return new InternalDumpCommand(cmdParams, option_map, flags);
Y
Yiting Li 已提交
182 183
  } else if (cmd == CheckConsistencyCommand::Name()) {
    return new CheckConsistencyCommand(cmdParams, option_map, flags);
184
  }
185
  return nullptr;
186 187
}

188

189 190 191 192 193 194 195
/**
 * 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.
 */
196 197 198 199 200
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);
201
  if (itr != option_map_.end()) {
202
    try {
S
sdong 已提交
203 204 205
#if defined(CYGWIN)
      value = strtol(itr->second.c_str(), 0, 10);
#else
206
      value = stoi(itr->second);
S
sdong 已提交
207
#endif
208
      return true;
209
    } catch(const invalid_argument&) {
210 211
      exec_state =
          LDBCommandExecuteResult::Failed(option + " has an invalid value.");
212
    } catch(const out_of_range&) {
213 214
      exec_state = LDBCommandExecuteResult::Failed(
          option + " has a value out-of-range.");
215 216
    }
  }
217
  return false;
218 219
}

220 221 222 223 224
/**
 * Parses the specified option and fills in the value.
 * Returns true if the option is found.
 * Returns false otherwise.
 */
225 226
bool LDBCommand::ParseStringOption(const map<string, string>& options,
                                   const string& option, string* value) {
227 228 229 230 231 232 233 234
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
    *value = itr->second;
    return true;
  }
  return false;
}

235
Options LDBCommand::PrepareOptionsForOpenDB() {
236

237
  Options opt = options_;
238
  opt.create_if_missing = false;
239

240
  map<string, string>::const_iterator itr;
241

242
  BlockBasedTableOptions table_options;
S
sdong 已提交
243
  bool use_table_options = false;
244
  int bits;
245
  if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
246
    if (bits > 0) {
S
sdong 已提交
247
      use_table_options = true;
248
      table_options.filter_policy.reset(NewBloomFilterPolicy(bits));
249
    } else {
250 251
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOOM_BITS + " must be > 0.");
252 253 254 255
    }
  }

  int block_size;
256
  if (ParseIntOption(option_map_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
257
    if (block_size > 0) {
S
sdong 已提交
258
      use_table_options = true;
259
      table_options.block_size = block_size;
260
    } else {
261 262
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_BLOCK_SIZE + " must be > 0.");
263 264 265
    }
  }

S
sdong 已提交
266 267 268 269
  if (use_table_options) {
    opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  }

270 271
  itr = option_map_.find(ARG_AUTO_COMPACTION);
  if (itr != option_map_.end()) {
272 273 274
    opt.disable_auto_compactions = ! StringToBool(itr->second);
  }

275 276
  itr = option_map_.find(ARG_COMPRESSION_TYPE);
  if (itr != option_map_.end()) {
277
    string comp = itr->second;
278
    if (comp == "no") {
279
      opt.compression = kNoCompression;
280
    } else if (comp == "snappy") {
281
      opt.compression = kSnappyCompression;
282
    } else if (comp == "zlib") {
283
      opt.compression = kZlibCompression;
284
    } else if (comp == "bzip2") {
285
      opt.compression = kBZip2Compression;
A
Albert Strasheim 已提交
286 287 288 289
    } else if (comp == "lz4") {
      opt.compression = kLZ4Compression;
    } else if (comp == "lz4hc") {
      opt.compression = kLZ4HCCompression;
290 291
    } else if (comp == "zstd") {
      opt.compression = kZSTDNotFinalCompression;
292 293
    } else {
      // Unknown compression.
294 295
      exec_state_ =
          LDBCommandExecuteResult::Failed("Unknown compression level: " + comp);
296 297 298
    }
  }

299 300 301 302 303 304
  int db_write_buffer_size;
  if (ParseIntOption(option_map_, ARG_DB_WRITE_BUFFER_SIZE,
        db_write_buffer_size, exec_state_)) {
    if (db_write_buffer_size >= 0) {
      opt.db_write_buffer_size = db_write_buffer_size;
    } else {
305
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_DB_WRITE_BUFFER_SIZE +
306
                                                    " must be >= 0.");
307 308 309
    }
  }

310
  int write_buffer_size;
311 312
  if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
        exec_state_)) {
313
    if (write_buffer_size > 0) {
314
      opt.write_buffer_size = write_buffer_size;
315
    } else {
316
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_WRITE_BUFFER_SIZE +
317
                                                    " must be > 0.");
318 319 320 321
    }
  }

  int file_size;
322
  if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
323
    if (file_size > 0) {
324 325
      opt.target_file_size_base = file_size;
    } else {
326 327
      exec_state_ =
          LDBCommandExecuteResult::Failed(ARG_FILE_SIZE + " must be > 0.");
328 329 330
    }
  }

331
  if (opt.db_paths.size() == 0) {
332
    opt.db_paths.emplace_back(db_path_, std::numeric_limits<uint64_t>::max());
333 334
  }

S
sdong 已提交
335
  int fix_prefix_len;
336 337
  if (ParseIntOption(option_map_, ARG_FIX_PREFIX_LEN, fix_prefix_len,
                     exec_state_)) {
S
sdong 已提交
338 339 340 341
    if (fix_prefix_len > 0) {
      opt.prefix_extractor.reset(
          NewFixedPrefixTransform(static_cast<size_t>(fix_prefix_len)));
    } else {
342
      exec_state_ =
343
          LDBCommandExecuteResult::Failed(ARG_FIX_PREFIX_LEN + " must be > 0.");
S
sdong 已提交
344 345 346
    }
  }

347 348 349
  return opt;
}

350 351
bool LDBCommand::ParseKeyValue(const string& line, string* key, string* value,
                              bool is_key_hex, bool is_value_hex) {
352
  size_t pos = line.find(DELIM);
353
  if (pos != string::npos) {
354 355 356 357 358 359 360 361 362 363 364 365 366
    *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;
  }
}
367

368 369 370 371 372 373 374 375 376
/**
 * 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() {

377 378
  for (map<string, string>::const_iterator itr = option_map_.begin();
        itr != option_map_.end(); ++itr) {
M
Mayank Agarwal 已提交
379
    if (find(valid_cmd_line_options_.begin(),
380
          valid_cmd_line_options_.end(), itr->first) ==
381 382 383 384 385
          valid_cmd_line_options_.end()) {
      fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
      return false;
    }
  }
386

387
  for (vector<string>::const_iterator itr = flags_.begin();
388
        itr != flags_.end(); ++itr) {
M
Mayank Agarwal 已提交
389
    if (find(valid_cmd_line_options_.begin(),
390
          valid_cmd_line_options_.end(), *itr) ==
391 392 393
          valid_cmd_line_options_.end()) {
      fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
      return false;
394 395 396
    }
  }

397
  if (!NoDBOpen() && option_map_.find(ARG_DB) == option_map_.end()) {
398 399 400 401 402 403 404
    fprintf(stderr, "%s must be specified\n", ARG_DB.c_str());
    return false;
  }

  return true;
}

405 406
CompactorCommand::CompactorCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
407 408
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_FROM, ARG_TO, ARG_HEX, ARG_KEY_HEX,
409
                                    ARG_VALUE_HEX, ARG_TTL})),
410
    null_from_(true), null_to_(true) {
411 412

  map<string, string>::const_iterator itr = options.find(ARG_FROM);
413 414 415 416 417 418 419 420 421 422 423 424
  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_) {
425 426 427 428 429 430 431 432 433
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

434 435 436 437 438
void CompactorCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(CompactorCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
439 440
}

441
void CompactorCommand::DoCommand() {
442

443 444
  Slice* begin = nullptr;
  Slice* end = nullptr;
445
  if (!null_from_) {
446
    begin = new Slice(from_);
447 448
  }
  if (!null_to_) {
449
    end = new Slice(to_);
450 451
  }

452
  db_->CompactRange(CompactRangeOptions(), begin, end);
453
  exec_state_ = LDBCommandExecuteResult::Succeed("");
454 455 456 457 458

  delete begin;
  delete end;
}

459 460
// ----------------------------------------------------------------------------

461 462 463
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 已提交
464

465 466
DBLoaderCommand::DBLoaderCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
467 468 469
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                    ARG_FROM, ARG_TO, ARG_CREATE_IF_MISSING,
470 471 472 473
                                    ARG_DISABLE_WAL, ARG_BULK_LOAD,
                                    ARG_COMPACT})),
    create_if_missing_(false), disable_wal_(false), bulk_load_(false),
    compact_(false) {
474 475 476

  create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
477 478
  bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  compact_ = IsFlagPresent(flags, ARG_COMPACT);
Z
Zheng Shao 已提交
479 480
}

481 482 483 484 485 486 487 488
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 已提交
489 490
}

491 492
Options DBLoaderCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
Z
Zheng Shao 已提交
493
  opt.create_if_missing = create_if_missing_;
494 495 496
  if (bulk_load_) {
    opt.PrepareForBulkLoad();
  }
Z
Zheng Shao 已提交
497 498 499
  return opt;
}

500
void DBLoaderCommand::DoCommand() {
Z
Zheng Shao 已提交
501 502 503 504 505 506 507 508 509 510
  if (!db_) {
    return;
  }

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

  int bad_lines = 0;
511 512 513 514
  string line;
  while (getline(cin, line, '\n')) {
    string key;
    string value;
515
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
Z
Zheng Shao 已提交
516 517 518 519 520 521 522 523 524
      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 ++;
    }
  }
525

Z
Zheng Shao 已提交
526
  if (bad_lines > 0) {
527
    cout << "Warning: " << bad_lines << " bad lines ignored." << endl;
Z
Zheng Shao 已提交
528
  }
529
  if (compact_) {
530
    db_->CompactRange(CompactRangeOptions(), nullptr, nullptr);
531
  }
Z
Zheng Shao 已提交
532 533
}

534 535
// ----------------------------------------------------------------------------

536 537
namespace {

538
void DumpManifestFile(std::string file, bool verbose, bool hex, bool json) {
539 540 541
  Options options;
  EnvOptions sopt;
  std::string dbname("dummy");
542 543
  std::shared_ptr<Cache> tc(NewLRUCache(options.max_open_files - 10,
                                        options.table_cache_numshardbits));
544 545 546 547
  // 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);
548
  options.num_levels = 64;
S
sdong 已提交
549
  WriteController wc(options.delayed_write_rate);
550 551
  WriteBuffer wb(options.db_write_buffer_size);
  VersionSet versions(dbname, &options, sopt, tc.get(), &wb, &wc);
552
  Status s = versions.DumpManifest(options, file, verbose, hex, json);
553 554 555 556 557 558 559 560
  if (!s.ok()) {
    printf("Error in processing file %s %s\n", file.c_str(),
           s.ToString().c_str());
  }
}

}  // namespace

561
const string ManifestDumpCommand::ARG_VERBOSE = "verbose";
562 563
const string ManifestDumpCommand::ARG_JSON = "json";
const string ManifestDumpCommand::ARG_PATH = "path";
564

565 566 567 568
void ManifestDumpCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ManifestDumpCommand::Name());
  ret.append(" [--" + ARG_VERBOSE + "]");
569
  ret.append(" [--" + ARG_JSON + "]");
570 571
  ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  ret.append("\n");
572 573
}

574 575
ManifestDumpCommand::ManifestDumpCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
576
    LDBCommand(options, flags, false,
577
               BuildCmdLineOptions({ARG_VERBOSE, ARG_PATH, ARG_HEX, ARG_JSON})),
578
    verbose_(false),
579
    json_(false),
580 581
    path_("")
{
582
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE);
583
  json_ = IsFlagPresent(flags, ARG_JSON);
584

585
  map<string, string>::const_iterator itr = options.find(ARG_PATH);
586 587 588
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
589
      exec_state_ = LDBCommandExecuteResult::Failed("--path: missing pathname");
590 591 592 593 594 595 596 597 598 599 600 601 602 603
    }
  }
}

void ManifestDumpCommand::DoCommand() {

  std::string manifestfile;

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

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

609
    if (d == nullptr) {
610 611
      exec_state_ =
          LDBCommandExecuteResult::Failed(db_path_ + " is not a directory");
612 613 614
      return;
    }
    struct dirent* entry;
D
Dmitri Smirnov 已提交
615
    while ((entry = readdir(d.get())) != nullptr) {
616
      unsigned int match;
617
      uint64_t num;
618
      if (sscanf(entry->d_name, "MANIFEST-%" PRIu64 "%n", &num, &match) &&
619
          match == strlen(entry->d_name)) {
620 621 622 623
        if (!found) {
          manifestfile = db_path_ + "/" + std::string(entry->d_name);
          found = true;
        } else {
624
          exec_state_ = LDBCommandExecuteResult::Failed(
625
              "Multiple MANIFEST files found; use --path to select one");
626 627 628 629 630 631 632 633 634 635
          return;
        }
      }
    }
  }

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

636 637
  DumpManifestFile(manifestfile, verbose_, is_key_hex_, json_);

638 639 640 641 642 643
  if (verbose_) {
    printf("Processing Manifest file %s done\n", manifestfile.c_str());
  }
}

// ----------------------------------------------------------------------------
644

645 646 647 648 649
void ListColumnFamiliesCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ListColumnFamiliesCommand::Name());
  ret.append(" full_path_to_db_directory ");
  ret.append("\n");
650 651 652
}

ListColumnFamiliesCommand::ListColumnFamiliesCommand(
653 654
    const vector<string>& params, const map<string, string>& options,
    const vector<string>& flags)
655 656 657
    : LDBCommand(options, flags, false, {}) {

  if (params.size() != 1) {
658
    exec_state_ = LDBCommandExecuteResult::Failed(
659 660 661 662 663 664 665
        "dbname must be specified for the list_column_families command");
  } else {
    dbname_ = params[0];
  }
}

void ListColumnFamiliesCommand::DoCommand() {
666
  vector<string> column_families;
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
  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");
  }
}

// ----------------------------------------------------------------------------
686

I
Igor Canadi 已提交
687 688
namespace {

689
string ReadableTime(int unixtime) {
690 691
  char time_buffer [80];
  time_t rawtime = unixtime;
692 693 694
  struct tm tInfo;
  struct tm* timeinfo = localtime_r(&rawtime, &tInfo);
  assert(timeinfo == &tInfo);
695
  strftime(time_buffer, 80, "%c", timeinfo);
696
  return string(time_buffer);
697 698 699 700
}

// 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
701
void IncBucketCounts(vector<uint64_t>& bucket_counts, int ttl_start,
702 703 704 705
      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;
706
  bucket_counts[bucket]++;
707 708
}

709 710
void PrintBucketCounts(const vector<uint64_t>& bucket_counts, int ttl_start,
      int ttl_end, int bucket_size, int num_buckets) {
711
  int time_point = ttl_start;
712 713
  for(int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
    fprintf(stdout, "Keys in range %s to %s : %lu\n",
714
            ReadableTime(time_point).c_str(),
K
Kai Liu 已提交
715
            ReadableTime(time_point + bucket_size).c_str(),
716
            (unsigned long)bucket_counts[i]);
717
  }
718
  fprintf(stdout, "Keys in range %s to %s : %lu\n",
719
          ReadableTime(time_point).c_str(),
K
Kai Liu 已提交
720
          ReadableTime(ttl_end).c_str(),
721
          (unsigned long)bucket_counts[num_buckets - 1]);
722 723
}

I
Igor Canadi 已提交
724 725
}  // namespace

726 727 728 729
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";
730

731 732 733
InternalDumpCommand::InternalDumpCommand(const vector<string>& params,
                                         const map<string, string>& options,
                                         const vector<string>& flags) :
734
    LDBCommand(options, flags, true,
735 736 737 738
               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})),
739 740 741
    has_from_(false),
    has_to_(false),
    max_keys_(-1),
742
    delim_("."),
743
    count_only_(false),
744
    count_delim_(false),
745 746
    print_stats_(false),
    is_input_key_hex_(false) {
747 748 749 750

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

751 752
  ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
  map<string, string>::const_iterator itr = options.find(ARG_COUNT_DELIM);
753 754 755
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
756
   // fprintf(stdout,"delim = %c\n",delim_[0]);
757 758
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
759
    delim_=".";
760
  }
761 762 763

  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
764
  is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
765

766
  if (is_input_key_hex_) {
767 768 769 770 771 772 773 774 775
    if (has_from_) {
      from_ = HexToString(from_);
    }
    if (has_to_) {
      to_ = HexToString(to_);
    }
  }
}

776 777 778 779 780 781 782 783 784 785
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");
786 787 788 789 790 791 792 793
}

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

  if (print_stats_) {
794
    string stats;
795
    if (db_->GetProperty("rocksdb.stats", &stats)) {
796 797 798 799 800 801 802
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Cast as DBImpl to get internal iterator
  DBImpl* idb = dynamic_cast<DBImpl*>(db_);
  if (!idb) {
803
    exec_state_ = LDBCommandExecuteResult::Failed("DB is not DBImpl");
804 805
    return;
  }
806
  string rtype1,rtype2,row,val;
807
  rtype2 = "";
808 809
  uint64_t c=0;
  uint64_t s1=0,s2=0;
810
  // Setup internal key iterator
811
  Arena arena;
812
  ScopedArenaIterator iter(idb->NewInternalIterator(&arena));
813 814
  Status st = iter->status();
  if (!st.ok()) {
815 816
    exec_state_ =
        LDBCommandExecuteResult::Failed("Iterator error:" + st.ToString());
817 818 819
  }

  if (has_from_) {
820 821
    InternalKey ikey;
    ikey.SetMaxPossibleForUserKey(from_);
822 823 824 825 826
    iter->Seek(ikey.Encode());
  } else {
    iter->SeekToFirst();
  }

827
  long long count = 0;
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
  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;
843 844 845
    int k;
    if (count_delim_) {
      rtype1 = "";
846
      s1=0;
847 848
      row = iter->key().ToString();
      val = iter->value().ToString();
849
      for(k=0;row[k]!='\x01' && row[k]!='\0';k++)
850
        s1++;
851
      for(k=0;val[k]!='\x01' && val[k]!='\0';k++)
852
        s1++;
853 854 855 856 857 858 859
      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;
860 861 862
        rtype2 = rtype1;
      } else {
        c++;
863 864
        s2+=s1;
        rtype2=rtype1;
865 866
    }
  }
867

868
    if (!count_only_ && !count_delim_) {
869 870 871
      string key = ikey.DebugString(is_key_hex_);
      string value = iter->value().ToString(is_value_hex_);
      std::cout << key << " => " << value << "\n";
872 873 874
    }

    // Terminate if maximum number of keys have been dumped
875
    if (max_keys_ > 0 && count >= max_keys_) break;
876
  }
877 878 879
  if(count_delim_) {
    fprintf(stdout,"%s => count:%lld\tsize:%lld\n", rtype2.c_str(),
        (long long)c,(long long)s2);
880
  } else
881
  fprintf(stdout, "Internal keys in range: %lld\n", (long long) count);
882 883 884
}


885 886 887 888
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";
889

890 891
DBDumperCommand::DBDumperCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
892
    LDBCommand(options, flags, true,
893 894 895 896 897 898
               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})),
899 900 901 902
    null_from_(true),
    null_to_(true),
    max_keys_(-1),
    count_only_(false),
903
    count_delim_(false),
904 905
    print_stats_(false) {

906
  map<string, string>::const_iterator itr = options.find(ARG_FROM);
907 908 909 910 911 912 913 914 915 916 917 918 919 920
  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 已提交
921 922 923
#if defined(CYGWIN)
      max_keys_ = strtol(itr->second.c_str(), 0, 10);
#else
M
Mayank Agarwal 已提交
924
      max_keys_ = stoi(itr->second);
S
sdong 已提交
925
#endif
926
    } catch(const invalid_argument&) {
927
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
928
                                                    " has an invalid value");
929
    } catch(const out_of_range&) {
930 931
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
932 933
    }
  }
934 935 936 937 938 939
  itr = options.find(ARG_COUNT_DELIM);
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
940
    delim_=".";
941
  }
942

943 944 945 946
  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);

  if (is_key_hex_) {
947 948 949 950 951 952 953 954 955
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

956 957 958 959 960 961 962 963 964 965 966 967 968 969
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");
970 971
}

972
void DBDumperCommand::DoCommand() {
973 974 975
  if (!db_) {
    return;
  }
976 977 978
  // Parse command line args
  uint64_t count = 0;
  if (print_stats_) {
979
    string stats;
980
    if (db_->GetProperty("rocksdb.stats", &stats)) {
981 982 983 984 985
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Setup key iterator
986 987
  Iterator* iter = db_->NewIterator(ReadOptions());
  Status st = iter->status();
988
  if (!st.ok()) {
989 990
    exec_state_ =
        LDBCommandExecuteResult::Failed("Iterator error." + st.ToString());
991 992 993 994 995 996 997 998 999
  }

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

  int max_keys = max_keys_;
1000
  int ttl_start;
1001
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
1002
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
1003 1004
  }
  int ttl_end;
1005
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
1006
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
1007 1008 1009 1010 1011 1012 1013 1014
  }
  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;
1015
  if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
1016 1017 1018
      bucket_size <= 0) {
    bucket_size = time_range; // Will have just 1 bucket by default
  }
1019
  //cretaing variables for row count of each type
1020
  string rtype1,rtype2,row,val;
1021
  rtype2 = "";
1022 1023
  uint64_t c=0;
  uint64_t s1=0,s2=0;
1024

1025
  // At this point, bucket_size=0 => time_range=0
1026 1027 1028
  int num_buckets = (bucket_size >= time_range)
                        ? 1
                        : ((time_range + bucket_size - 1) / bucket_size);
1029
  vector<uint64_t> bucket_counts(num_buckets, 0);
1030
  if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
1031 1032 1033 1034
    fprintf(stdout, "Dumping key-values from %s to %s\n",
            ReadableTime(ttl_start).c_str(), ReadableTime(ttl_end).c_str());
  }

1035
  for (; iter->Valid(); iter->Next()) {
1036
    int rawtime = 0;
1037 1038 1039 1040 1041 1042
    // 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;
1043
    if (is_db_ttl_) {
1044 1045
      TtlIterator* it_ttl = dynamic_cast<TtlIterator*>(iter);
      assert(it_ttl);
1046 1047
      rawtime = it_ttl->timestamp();
      if (rawtime < ttl_start || rawtime >= ttl_end) {
1048 1049 1050
        continue;
      }
    }
1051 1052 1053
    if (max_keys > 0) {
      --max_keys;
    }
1054
    if (is_db_ttl_ && num_buckets > 1) {
1055
      IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
1056 1057
                      rawtime, num_buckets);
    }
1058
    ++count;
1059 1060 1061 1062 1063
    if (count_delim_) {
      rtype1 = "";
      row = iter->key().ToString();
      val = iter->value().ToString();
      s1 = row.size()+val.size();
1064 1065 1066 1067 1068 1069 1070
      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;
1071 1072
        rtype2 = rtype1;
      } else {
1073 1074 1075
          c++;
          s2+=s1;
          rtype2=rtype1;
1076
      }
1077

1078 1079
    }

1080 1081


1082
    if (!count_only_ && !count_delim_) {
1083 1084 1085
      if (is_db_ttl_ && timestamp_) {
        fprintf(stdout, "%s ", ReadableTime(rawtime).c_str());
      }
1086
      string str = PrintKeyValue(iter->key().ToString(),
1087 1088
                                 iter->value().ToString(), is_key_hex_,
                                 is_value_hex_);
1089
      fprintf(stdout, "%s\n", str.c_str());
1090 1091
    }
  }
1092

1093
  if (num_buckets > 1 && is_db_ttl_) {
1094
    PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
1095
                      num_buckets);
1096 1097 1098
  } else if(count_delim_) {
    fprintf(stdout,"%s => count:%lld\tsize:%lld\n",rtype2.c_str(),
        (long long )c,(long long)s2);
1099
  } else {
1100
    fprintf(stdout, "Keys in range: %lld\n", (long long) count);
1101
  }
1102 1103 1104 1105
  // Clean up
  delete iter;
}

1106 1107
const string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
const string  ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS = "print_old_levels";
1108

1109 1110
ReduceDBLevelsCommand::ReduceDBLevelsCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1111 1112
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_NEW_LEVELS, ARG_PRINT_OLD_LEVELS})),
I
Igor Canadi 已提交
1113
    old_levels_(1 << 7),
1114 1115
    new_levels_(-1),
    print_old_levels_(false) {
1116 1117


1118
  ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
1119
  print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
1120

1121
  if(new_levels_ <= 0) {
1122
    exec_state_ = LDBCommandExecuteResult::Failed(
1123
        " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
1124 1125 1126
  }
}

1127
vector<string> ReduceDBLevelsCommand::PrepareArgs(const string& db_path,
1128
    int new_levels, bool print_old_level) {
1129
  vector<string> ret;
1130
  ret.push_back("reduce_levels");
1131
  ret.push_back("--" + ARG_DB + "=" + db_path);
S
sdong 已提交
1132
  ret.push_back("--" + ARG_NEW_LEVELS + "=" + rocksdb::ToString(new_levels));
1133
  if(print_old_level) {
1134
    ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
1135 1136 1137 1138
  }
  return ret;
}

1139 1140 1141 1142 1143 1144
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");
1145 1146
}

1147 1148
Options ReduceDBLevelsCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1149
  opt.num_levels = old_levels_;
1150
  opt.max_bytes_for_level_multiplier_additional.resize(opt.num_levels, 1);
1151
  // Disable size compaction
I
Igor Canadi 已提交
1152
  opt.max_bytes_for_level_base = 1ULL << 50;
1153
  opt.max_bytes_for_level_multiplier = 1;
1154 1155 1156
  return opt;
}

1157
Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt,
1158
    int* levels) {
H
Haobo Xu 已提交
1159
  EnvOptions soptions;
I
Igor Canadi 已提交
1160
  std::shared_ptr<Cache> tc(
1161
      NewLRUCache(opt.max_open_files - 10, opt.table_cache_numshardbits));
1162
  const InternalKeyComparator cmp(opt.comparator);
S
sdong 已提交
1163
  WriteController wc(opt.delayed_write_rate);
1164 1165
  WriteBuffer wb(opt.db_write_buffer_size);
  VersionSet versions(db_path_, &opt, soptions, tc.get(), &wb, &wc);
I
Igor Canadi 已提交
1166
  std::vector<ColumnFamilyDescriptor> dummy;
1167
  ColumnFamilyDescriptor dummy_descriptor(kDefaultColumnFamilyName,
I
Igor Canadi 已提交
1168 1169
                                          ColumnFamilyOptions(opt));
  dummy.push_back(dummy_descriptor);
1170 1171 1172
  // 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 已提交
1173
  Status st = versions.Recover(dummy);
1174 1175 1176 1177
  if (!st.ok()) {
    return st;
  }
  int max = -1;
1178
  auto default_cfd = versions.GetColumnFamilySet()->GetDefault();
I
Igor Canadi 已提交
1179
  for (int i = 0; i < default_cfd->NumberLevels(); i++) {
S
sdong 已提交
1180
    if (default_cfd->current()->storage_info()->NumLevelFiles(i)) {
1181 1182 1183 1184 1185 1186 1187 1188
      max = i;
    }
  }

  *levels = max + 1;
  return st;
}

1189
void ReduceDBLevelsCommand::DoCommand() {
1190
  if (new_levels_ <= 1) {
1191 1192
    exec_state_ =
        LDBCommandExecuteResult::Failed("Invalid number of levels.\n");
1193 1194 1195
    return;
  }

1196 1197
  Status st;
  Options opt = PrepareOptionsForOpenDB();
1198 1199 1200
  int old_level_num = -1;
  st = GetOldNumOfLevels(opt, &old_level_num);
  if (!st.ok()) {
1201
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1202 1203 1204
    return;
  }

1205
  if (print_old_levels_) {
1206
    fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
1207
  }
1208

1209 1210
  if (old_level_num <= new_levels_) {
    return;
1211 1212
  }

1213 1214 1215
  old_levels_ = old_level_num;

  OpenDB();
1216 1217 1218
  if (!db_) {
    return;
  }
1219
  // Compact the whole DB to put all files to the highest level.
1220
  fprintf(stdout, "Compacting the db...\n");
1221
  db_->CompactRange(CompactRangeOptions(), nullptr, nullptr);
1222 1223
  CloseDB();

H
Haobo Xu 已提交
1224
  EnvOptions soptions;
1225
  st = VersionSet::ReduceNumberOfLevels(db_path_, &opt, soptions, new_levels_);
1226
  if (!st.ok()) {
1227
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1228 1229 1230 1231
    return;
  }
}

1232
const string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
1233
  "old_compaction_style";
1234
const string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
1235 1236 1237
  "new_compaction_style";

ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
1238 1239
      const vector<string>& params, const map<string, string>& options,
      const vector<string>& flags) :
1240 1241 1242 1243 1244 1245
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_OLD_COMPACTION_STYLE,
                                    ARG_NEW_COMPACTION_STYLE})),
    old_compaction_style_(-1),
    new_compaction_style_(-1) {

1246 1247
  ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
    exec_state_);
1248 1249
  if (old_compaction_style_ != kCompactionStyleLevel &&
     old_compaction_style_ != kCompactionStyleUniversal) {
1250
    exec_state_ = LDBCommandExecuteResult::Failed(
1251 1252
        "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
        "style. Check ldb help for proper compaction style value.\n");
1253 1254 1255
    return;
  }

1256 1257
  ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
    exec_state_);
1258 1259
  if (new_compaction_style_ != kCompactionStyleLevel &&
     new_compaction_style_ != kCompactionStyleUniversal) {
1260
    exec_state_ = LDBCommandExecuteResult::Failed(
1261 1262
        "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
        "style. Check ldb help for proper compaction style value.\n");
1263 1264 1265 1266
    return;
  }

  if (new_compaction_style_ == old_compaction_style_) {
1267
    exec_state_ = LDBCommandExecuteResult::Failed(
1268 1269
        "Old compaction style is the same as new compaction style. "
        "Nothing to do.\n");
1270 1271 1272 1273 1274
    return;
  }

  if (old_compaction_style_ == kCompactionStyleUniversal &&
      new_compaction_style_ == kCompactionStyleLevel) {
1275
    exec_state_ = LDBCommandExecuteResult::Failed(
1276 1277
        "Convert from universal compaction to level compaction. "
        "Nothing to do.\n");
1278 1279 1280 1281
    return;
  }
}

1282 1283 1284 1285 1286 1287 1288 1289
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");
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
}

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++) {
1314
    db_->GetProperty("rocksdb.num-files-at-level" + NumberToString(i),
1315 1316
                     &property);

1317
    // format print string
1318
    char buf[100];
1319
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
1320 1321 1322 1323 1324 1325
    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
1326 1327 1328 1329
  CompactRangeOptions compact_options;
  compact_options.change_level = true;
  compact_options.target_level = 0;
  db_->CompactRange(compact_options, nullptr, nullptr);
1330 1331 1332 1333 1334

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

1338
    // format print string
1339
    char buf[100];
1340
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
1341 1342 1343 1344 1345 1346
    files_per_level += buf;

    num_files = atoi(property.c_str());

    // level 0 should have only 1 file
    if (i == 0 && num_files != 1) {
1347 1348 1349 1350
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level 0 after compaction is " +
          ToString(num_files) + ", not 1.\n");
1351 1352 1353 1354
      return;
    }
    // other levels should have no file
    if (i > 0 && num_files != 0) {
1355 1356 1357 1358 1359
      exec_state_ = LDBCommandExecuteResult::Failed(
          "Number of db files at "
          "level " +
          ToString(i) + " after compaction is " + ToString(num_files) +
          ", not 0.\n");
1360 1361 1362 1363 1364 1365 1366 1367
      return;
    }
  }

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

1368 1369 1370 1371 1372
// ----------------------------------------------------------------------------

namespace {

struct StdErrReporter : public log::Reader::Reporter {
I
Igor Sugak 已提交
1373
  virtual void Corruption(size_t bytes, const Status& s) override {
1374 1375 1376 1377
    cerr << "Corruption detected in log file " << s.ToString() << "\n";
  }
};

1378 1379
class InMemoryHandler : public WriteBatch::Handler {
 public:
1380
  InMemoryHandler(stringstream& row, bool print_values) : Handler(), row_(row) {
1381 1382
    print_values_ = print_values;
  }
1383

1384
  void commonPutMerge(const Slice& key, const Slice& value) {
1385
    string k = LDBCommand::StringToHex(key.ToString());
1386
    if (print_values_) {
1387
      string v = LDBCommand::StringToHex(value.ToString());
1388 1389 1390 1391 1392
      row_ << k << " : ";
      row_ << v << " ";
    } else {
      row_ << k << " ";
    }
1393
  }
1394

I
Igor Sugak 已提交
1395
  virtual void Put(const Slice& key, const Slice& value) override {
1396 1397
    row_ << "PUT : ";
    commonPutMerge(key, value);
1398 1399
  }

I
Igor Sugak 已提交
1400
  virtual void Merge(const Slice& key, const Slice& value) override {
1401 1402
    row_ << "MERGE : ";
    commonPutMerge(key, value);
1403
  }
1404

I
Igor Sugak 已提交
1405
  virtual void Delete(const Slice& key) override {
1406
    row_ <<",DELETE : ";
1407
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
1408 1409
  }

1410
  virtual ~InMemoryHandler() {}
1411

1412
 private:
1413
  stringstream & row_;
1414
  bool print_values_;
1415 1416
};

1417 1418 1419 1420
void DumpWalFile(std::string wal_file, bool print_header, bool print_values,
                 LDBCommandExecuteResult* exec_state) {
  Env* env_ = Env::Default();
  EnvOptions soptions;
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
  unique_ptr<SequentialFileReader> wal_file_reader;

  Status status;
  {
    unique_ptr<SequentialFile> file;
    status = env_->NewSequentialFile(wal_file, &file, soptions);
    if (status.ok()) {
      wal_file_reader.reset(new SequentialFileReader(std::move(file)));
    }
  }
1431 1432
  if (!status.ok()) {
    if (exec_state) {
1433
      *exec_state = LDBCommandExecuteResult::Failed("Failed to open WAL file " +
1434 1435 1436 1437 1438 1439 1440
                                                    status.ToString());
    } else {
      cerr << "Error: Failed to open WAL file " << status.ToString()
           << std::endl;
    }
  } else {
    StdErrReporter reporter;
1441
    log::Reader reader(move(wal_file_reader), &reporter, true, 0);
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
    string scratch;
    WriteBatch batch;
    Slice record;
    stringstream row;
    if (print_header) {
      cout << "Sequence,Count,ByteSize,Physical Offset,Key(s)";
      if (print_values) {
        cout << " : value ";
      }
      cout << "\n";
    }
    while (reader.ReadRecord(&record, &scratch)) {
      row.str("");
      if (record.size() < 12) {
        reporter.Corruption(record.size(),
                            Status::Corruption("log record too small"));
      } else {
        WriteBatchInternal::SetContents(&batch, record);
        row << WriteBatchInternal::Sequence(&batch) << ",";
        row << WriteBatchInternal::Count(&batch) << ",";
        row << WriteBatchInternal::ByteSize(&batch) << ",";
        row << reader.LastRecordOffset() << ",";
        InMemoryHandler handler(row, print_values);
        batch.Iterate(&handler);
        row << "\n";
      }
      cout << row.str();
    }
  }
}

}  // namespace

1475 1476 1477
const string WALDumperCommand::ARG_WAL_FILE = "walfile";
const string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
const string WALDumperCommand::ARG_PRINT_HEADER = "header";
1478

1479 1480
WALDumperCommand::WALDumperCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1481
    LDBCommand(options, flags, true,
1482 1483 1484
               BuildCmdLineOptions(
                {ARG_WAL_FILE, ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
    print_header_(false), print_values_(false) {
1485

A
Abhishek Kona 已提交
1486
  wal_file_.clear();
1487

1488
  map<string, string>::const_iterator itr = options.find(ARG_WAL_FILE);
1489 1490
  if (itr != options.end()) {
    wal_file_ = itr->second;
A
Abhishek Kona 已提交
1491
  }
1492 1493


1494 1495
  print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
A
Abhishek Kona 已提交
1496
  if (wal_file_.empty()) {
1497 1498
    exec_state_ = LDBCommandExecuteResult::Failed("Argument " + ARG_WAL_FILE +
                                                  " must be specified.");
A
Abhishek Kona 已提交
1499 1500 1501
  }
}

1502 1503 1504 1505 1506 1507 1508
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 已提交
1509 1510
}

1511
void WALDumperCommand::DoCommand() {
1512
  DumpWalFile(wal_file_, print_header_, print_values_, &exec_state_);
A
Abhishek Kona 已提交
1513 1514
}

1515
// ----------------------------------------------------------------------------
1516

1517 1518
GetCommand::GetCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1519 1520 1521
  LDBCommand(options, flags, true, BuildCmdLineOptions({ARG_TTL, ARG_HEX,
                                                        ARG_KEY_HEX,
                                                        ARG_VALUE_HEX})) {
1522 1523

  if (params.size() != 1) {
1524
    exec_state_ = LDBCommandExecuteResult::Failed(
1525
        "<key> must be specified for the get command");
1526 1527 1528 1529 1530 1531 1532 1533 1534
  } else {
    key_ = params.at(0);
  }

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

1535 1536 1537 1538 1539 1540
void GetCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(GetCommand::Name());
  ret.append(" <key>");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
1541 1542 1543
}

void GetCommand::DoCommand() {
1544
  string value;
1545
  Status st = db_->Get(ReadOptions(), key_, &value);
1546 1547 1548 1549
  if (st.ok()) {
    fprintf(stdout, "%s\n",
              (is_value_hex_ ? StringToHex(value) : value).c_str());
  } else {
1550
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1551 1552 1553
  }
}

1554
// ----------------------------------------------------------------------------
1555

1556 1557
ApproxSizeCommand::ApproxSizeCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1558 1559 1560 1561 1562 1563 1564
  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 {
1565 1566
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_FROM + " must be specified for approxsize command");
1567 1568 1569 1570 1571 1572
    return;
  }

  if (options.find(ARG_TO) != options.end()) {
    end_key_ = options.find(ARG_TO)->second;
  } else {
1573 1574
    exec_state_ = LDBCommandExecuteResult::Failed(
        ARG_TO + " must be specified for approxsize command");
1575 1576 1577 1578 1579 1580 1581 1582 1583
    return;
  }

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

1584 1585 1586 1587 1588
void ApproxSizeCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ApproxSizeCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
1589 1590 1591 1592
}

void ApproxSizeCommand::DoCommand() {

1593 1594
  Range ranges[1];
  ranges[0] = Range(start_key_, end_key_);
1595 1596
  uint64_t sizes[1];
  db_->GetApproximateSizes(ranges, 1, sizes);
K
Kai Liu 已提交
1597
  fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
1598
  /* Weird that GetApproximateSizes() returns void, although documentation
1599 1600
   * says that it returns a Status object.
  if (!st.ok()) {
1601
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1602 1603 1604 1605
  }
  */
}

1606
// ----------------------------------------------------------------------------
1607

1608 1609 1610 1611 1612
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})) {
1613 1614

  if (params.size() < 2) {
1615
    exec_state_ = LDBCommandExecuteResult::Failed(
1616
        "At least one <key> <value> pair must be specified batchput.");
1617
  } else if (params.size() % 2 != 0) {
1618
    exec_state_ = LDBCommandExecuteResult::Failed(
1619 1620 1621
        "Equal number of <key>s and <value>s must be specified for batchput.");
  } else {
    for (size_t i = 0; i < params.size(); i += 2) {
1622 1623 1624
      string key = params.at(i);
      string value = params.at(i+1);
      key_values_.push_back(pair<string, string>(
1625 1626 1627 1628 1629 1630
                    is_key_hex_ ? HexToString(key) : key,
                    is_value_hex_ ? HexToString(value) : value));
    }
  }
}

1631 1632 1633 1634 1635 1636
void BatchPutCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(BatchPutCommand::Name());
  ret.append(" <key> <value> [<key> <value>] [..]");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
1637 1638 1639
}

void BatchPutCommand::DoCommand() {
1640
  WriteBatch batch;
1641

1642
  for (vector<pair<string, string>>::const_iterator itr
1643
        = key_values_.begin(); itr != key_values_.end(); ++itr) {
1644
      batch.Put(itr->first, itr->second);
1645
  }
1646
  Status st = db_->Write(WriteOptions(), &batch);
1647 1648 1649
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
1650
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1651 1652 1653
  }
}

1654 1655
Options BatchPutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1656 1657 1658 1659
  opt.create_if_missing = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  return opt;
}

1660
// ----------------------------------------------------------------------------
1661

1662 1663
ScanCommand::ScanCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1664
    LDBCommand(options, flags, true,
1665 1666 1667
               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})),
1668 1669 1670 1671
    start_key_specified_(false),
    end_key_specified_(false),
    max_keys_scanned_(-1) {

1672
  map<string, string>::const_iterator itr = options.find(ARG_FROM);
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
  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 {
S
sdong 已提交
1692 1693 1694
#if defined(CYGWIN)
      max_keys_scanned_ = strtol(itr->second.c_str(), 0, 10);
#else
M
Mayank Agarwal 已提交
1695
      max_keys_scanned_ = stoi(itr->second);
S
sdong 已提交
1696
#endif
1697
    } catch(const invalid_argument&) {
1698
      exec_state_ = LDBCommandExecuteResult::Failed(ARG_MAX_KEYS +
1699
                                                    " has an invalid value");
1700
    } catch(const out_of_range&) {
1701 1702
      exec_state_ = LDBCommandExecuteResult::Failed(
          ARG_MAX_KEYS + " has a value out-of-range");
1703 1704 1705 1706
    }
  }
}

1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
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");
1717 1718 1719 1720 1721
}

void ScanCommand::DoCommand() {

  int num_keys_scanned = 0;
1722
  Iterator* it = db_->NewIterator(ReadOptions());
1723 1724 1725 1726 1727
  if (start_key_specified_) {
    it->Seek(start_key_);
  } else {
    it->SeekToFirst();
  }
1728
  int ttl_start;
1729
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
1730
    ttl_start = DBWithTTLImpl::kMinTimestamp;  // TTL introduction time
1731 1732
  }
  int ttl_end;
1733
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
1734
    ttl_end = DBWithTTLImpl::kMaxTimestamp;  // Max time allowed by TTL feature
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
  }
  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());
  }
1745
  for ( ;
1746 1747 1748
        it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
        it->Next()) {
    string key = ldb_options_.key_formatter->Format(it->key());
1749
    if (is_db_ttl_) {
1750 1751
      TtlIterator* it_ttl = dynamic_cast<TtlIterator*>(it);
      assert(it_ttl);
1752 1753
      int rawtime = it_ttl->timestamp();
      if (rawtime < ttl_start || rawtime >= ttl_end) {
1754 1755 1756 1757 1758 1759
        continue;
      }
      if (timestamp_) {
        fprintf(stdout, "%s ", ReadableTime(rawtime).c_str());
      }
    }
1760
    string value = it->value().ToString();
1761
    fprintf(stdout, "%s : %s\n",
1762
            (is_key_hex_ ? "0x" + it->key().ToString(true) : key).c_str(),
1763 1764
            (is_value_hex_ ? StringToHex(value) : value).c_str()
        );
1765 1766 1767 1768 1769 1770
    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
1771
    exec_state_ = LDBCommandExecuteResult::Failed(it->status().ToString());
1772 1773 1774 1775
  }
  delete it;
}

1776
// ----------------------------------------------------------------------------
1777

1778 1779
DeleteCommand::DeleteCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1780 1781 1782 1783
  LDBCommand(options, flags, false,
             BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {

  if (params.size() != 1) {
1784
    exec_state_ = LDBCommandExecuteResult::Failed(
1785
        "KEY must be specified for the delete command");
1786 1787 1788 1789 1790 1791 1792 1793
  } else {
    key_ = params.at(0);
    if (is_key_hex_) {
      key_ = HexToString(key_);
    }
  }
}

1794 1795 1796 1797
void DeleteCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DeleteCommand::Name() + " <key>");
  ret.append("\n");
1798 1799 1800
}

void DeleteCommand::DoCommand() {
1801
  Status st = db_->Delete(WriteOptions(), key_);
1802 1803 1804
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
1805
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1806 1807 1808 1809
  }
}


1810 1811
PutCommand::PutCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1812
  LDBCommand(options, flags, false,
1813
             BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
1814 1815 1816
                                  ARG_CREATE_IF_MISSING})) {

  if (params.size() != 2) {
1817
    exec_state_ = LDBCommandExecuteResult::Failed(
1818
        "<key> and <value> must be specified for the put command");
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
  } else {
    key_ = params.at(0);
    value_ = params.at(1);
  }

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

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

1833 1834 1835 1836 1837 1838
void PutCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(PutCommand::Name());
  ret.append(" <key> <value> ");
  ret.append(" [--" + ARG_TTL + "]");
  ret.append("\n");
1839 1840 1841
}

void PutCommand::DoCommand() {
1842
  Status st = db_->Put(WriteOptions(), key_, value_);
1843 1844 1845
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
1846
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
1847 1848 1849
  }
}

1850 1851
Options PutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1852 1853 1854 1855
  opt.create_if_missing = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  return opt;
}

1856
// ----------------------------------------------------------------------------
1857 1858 1859 1860 1861 1862

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

1863 1864
DBQuerierCommand::DBQuerierCommand(const vector<string>& params,
    const map<string, string>& options, const vector<string>& flags) :
1865
  LDBCommand(options, flags, false,
1866 1867
             BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
                                  ARG_VALUE_HEX})) {
1868 1869 1870

}

1871 1872 1873 1874 1875 1876
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 "
1877
             "commands.");
1878
  ret.append("\n");
1879 1880 1881 1882 1883 1884
}

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

1886 1887
  ReadOptions read_options;
  WriteOptions write_options;
1888

1889 1890 1891 1892 1893 1894 1895
  string line;
  string key;
  string value;
  while (getline(cin, line, '\n')) {

    // Parse line into vector<string>
    vector<string> tokens;
1896 1897 1898
    size_t pos = 0;
    while (true) {
      size_t pos2 = line.find(' ', pos);
1899
      if (pos2 == string::npos) {
1900 1901 1902 1903 1904 1905 1906
        break;
      }
      tokens.push_back(line.substr(pos, pos2-pos));
      pos = pos2 + 1;
    }
    tokens.push_back(line.substr(pos));

1907
    const string& cmd = tokens[0];
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937

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

1938 1939
// ----------------------------------------------------------------------------

1940 1941
CheckConsistencyCommand::CheckConsistencyCommand(const vector<string>& params,
    const map<string, string>& options, const vector<string>& flags) :
Y
Yiting Li 已提交
1942 1943 1944 1945
  LDBCommand(options, flags, false,
             BuildCmdLineOptions({})) {
}

1946 1947 1948 1949
void CheckConsistencyCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(CheckConsistencyCommand::Name());
  ret.append("\n");
Y
Yiting Li 已提交
1950
}
1951

Y
Yiting Li 已提交
1952 1953
void CheckConsistencyCommand::DoCommand() {
  Options opt = PrepareOptionsForOpenDB();
I
Igor Canadi 已提交
1954
  opt.paranoid_checks = true;
Y
Yiting Li 已提交
1955 1956 1957
  if (!exec_state_.IsNotStarted()) {
    return;
  }
I
Igor Canadi 已提交
1958 1959 1960
  DB* db;
  Status st = DB::OpenForReadOnly(opt, db_path_, &db, false);
  delete db;
Y
Yiting Li 已提交
1961 1962 1963
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
1964
    exec_state_ = LDBCommandExecuteResult::Failed(st.ToString());
Y
Yiting Li 已提交
1965
  }
1966
}
Y
Yiting Li 已提交
1967

1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
// ----------------------------------------------------------------------------

namespace {

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

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

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

}  // namespace

DBFileDumperCommand::DBFileDumperCommand(const vector<string>& params,
                                         const map<string, string>& options,
                                         const vector<string>& flags)
    : LDBCommand(options, flags, true, BuildCmdLineOptions({})) {}

void DBFileDumperCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DBFileDumperCommand::Name());
  ret.append("\n");
}

void DBFileDumperCommand::DoCommand() {
  if (!db_) {
    return;
  }
  Status s;

  std::cout << "Manifest File" << std::endl;
  std::cout << "==============================" << std::endl;
  std::string manifest_filename;
  s = ReadFileToString(db_->GetEnv(), CurrentFileName(db_->GetName()),
                       &manifest_filename);
  if (!s.ok() || manifest_filename.empty() ||
      manifest_filename.back() != '\n') {
    std::cerr << "Error when reading CURRENT file "
              << CurrentFileName(db_->GetName()) << std::endl;
  }
  // remove the trailing '\n'
  manifest_filename.resize(manifest_filename.size() - 1);
  string manifest_filepath = db_->GetName() + "/" + manifest_filename;
  std::cout << manifest_filepath << std::endl;
2048
  DumpManifestFile(manifest_filepath, false, false, false);
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
  std::cout << std::endl;

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

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

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