ldb_cmd.cc 33.9 KB
Newer Older
1 2 3 4
// Copyright (c) 2012 Facebook. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "util/ldb_cmd.h"
M
Mayank Agarwal 已提交
6 7 8
#include <sstream>
#include <string>
#include <stdexcept>
A
Abhishek Kona 已提交
9 10 11 12 13

#include "leveldb/write_batch.h"
#include "db/dbformat.h"
#include "db/log_reader.h"
#include "db/write_batch_internal.h"
14 15 16

namespace leveldb {

M
Mayank Agarwal 已提交
17 18 19 20 21 22 23 24 25 26 27 28
using namespace std;

vector<string> stringSplit(string arg, char delim) {
  vector<string> splits;
  stringstream ss(arg);
  string item;
  while(getline(ss, item, delim)) {
    splits.push_back(item);
  }
  return splits;
}

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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_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_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";

44
const char* LDBCommand::DELIM = " ==> ";
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
LDBCommand* LDBCommand::InitFromCmdLineArgs(int argc, char** argv) {
  vector<string> args;
  for (int i = 1; i < argc; i++) {
    args.push_back(argv[i]);
  }
  return InitFromCmdLineArgs(args);
}

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

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

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

  const string OPTION_PREFIX = "--";

  for (vector<string>::const_iterator itr = args.begin();
      itr != args.end(); itr++) {
    string arg = *itr;
M
Mayank Agarwal 已提交
80 81
    if (arg[0] == '-' && arg[1] == '-'){
      vector<string> splits = stringSplit(arg, '=');
82 83 84 85 86 87 88
      if (splits.size() == 2) {
        string optionKey = splits[0].substr(OPTION_PREFIX.size());
        options[optionKey] = splits[1];
      } else {
        string optionKey = splits[0].substr(OPTION_PREFIX.size());
        flags.push_back(optionKey);
      }
89
    } else {
90 91 92 93 94 95
      cmdTokens.push_back(string(arg));
    }
  }

  if (cmdTokens.size() < 1) {
    fprintf(stderr, "Command not specified!");
96
    return nullptr;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  }

  string cmd = cmdTokens[0];
  vector<string> cmdParams(cmdTokens.begin()+1, cmdTokens.end());

  if (cmd == GetCommand::Name()) {
    return new GetCommand(cmdParams, options, flags);
  } else if (cmd == PutCommand::Name()) {
    return new PutCommand(cmdParams, options, flags);
  } else if (cmd == BatchPutCommand::Name()) {
    return new BatchPutCommand(cmdParams, options, flags);
  } else if (cmd == ScanCommand::Name()) {
    return new ScanCommand(cmdParams, options, flags);
  } else if (cmd == DeleteCommand::Name()) {
    return new DeleteCommand(cmdParams, options, flags);
  } else if (cmd == ApproxSizeCommand::Name()) {
    return new ApproxSizeCommand(cmdParams, options, flags);
  } else if (cmd == DBQuerierCommand::Name()) {
    return new DBQuerierCommand(cmdParams, options, flags);
  } else if (cmd == CompactorCommand::Name()) {
    return new CompactorCommand(cmdParams, options, flags);
  } else if (cmd == WALDumperCommand::Name()) {
    return new WALDumperCommand(cmdParams, options, flags);
  } else if (cmd == ReduceDBLevelsCommand::Name()) {
    return new ReduceDBLevelsCommand(cmdParams, options, flags);
  } else if (cmd == DBDumperCommand::Name()) {
    return new DBDumperCommand(cmdParams, options, flags);
  } else if (cmd == DBLoaderCommand::Name()) {
    return new DBLoaderCommand(cmdParams, options, flags);
  }

128
  return nullptr;
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
}

/**
 * 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.
 */
bool LDBCommand::ParseIntOption(const map<string, string>& options,
    string option, int& value, LDBCommandExecuteResult& exec_state) {

  map<string, string>::const_iterator itr = options_.find(option);
  if (itr != options_.end()) {
    try {
M
Mayank Agarwal 已提交
144
      value = stoi(itr->second);
145
      return true;
M
Mayank Agarwal 已提交
146
    } catch(const invalid_argument&) {
147 148
      exec_state = LDBCommandExecuteResult::FAILED(option +
                      " has an invalid value.");
M
Mayank Agarwal 已提交
149 150 151
    } catch(const out_of_range&) {
      exec_state = LDBCommandExecuteResult::FAILED(option +
                      " has a value out-of-range.");
152 153
    }
  }
154
  return false;
155 156 157
}

leveldb::Options LDBCommand::PrepareOptionsForOpenDB() {
158

159 160
  leveldb::Options opt;
  opt.create_if_missing = false;
161 162 163 164 165 166

  map<string, string>::const_iterator itr;

  int bits;
  if (ParseIntOption(options_, ARG_BLOOM_BITS, bits, exec_state_)) {
    if (bits > 0) {
167
      opt.filter_policy = leveldb::NewBloomFilterPolicy(bits);
168 169 170 171 172 173 174 175 176
    } else {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_BLOOM_BITS +
                      " must be > 0.");
    }
  }

  int block_size;
  if (ParseIntOption(options_, ARG_BLOCK_SIZE, block_size, exec_state_)) {
    if (block_size > 0) {
177
      opt.block_size = block_size;
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    } else {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_BLOCK_SIZE +
                      " must be > 0.");
    }
  }

  itr = options_.find(ARG_AUTO_COMPACTION);
  if (itr != options_.end()) {
    opt.disable_auto_compactions = ! StringToBool(itr->second);
  }

  itr = options_.find(ARG_COMPRESSION_TYPE);
  if (itr != options_.end()) {
    string comp = itr->second;
    if (comp == "no") {
      opt.compression = leveldb::kNoCompression;
    } else if (comp == "snappy") {
      opt.compression = leveldb::kSnappyCompression;
    } else if (comp == "zlib") {
      opt.compression = leveldb::kZlibCompression;
    } else if (comp == "bzip2") {
      opt.compression = leveldb::kBZip2Compression;
    } else {
      // Unknown compression.
      exec_state_ = LDBCommandExecuteResult::FAILED(
                      "Unknown compression level: " + comp);
    }
  }

  int write_buffer_size;
  if (ParseIntOption(options_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
        exec_state_)) {
    if (write_buffer_size > 0) {
211
      opt.write_buffer_size = write_buffer_size;
212 213 214 215 216 217 218 219 220
    } else {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_WRITE_BUFFER_SIZE +
                      " must be > 0.");
    }
  }

  int file_size;
  if (ParseIntOption(options_, ARG_FILE_SIZE, file_size, exec_state_)) {
    if (file_size > 0) {
221 222
      opt.target_file_size_base = file_size;
    } else {
223 224
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_FILE_SIZE +
                      " must be > 0.");
225 226 227 228 229 230
    }
  }

  return opt;
}

231 232 233
bool LDBCommand::ParseKeyValue(const string& line, string* key, string* value,
                              bool is_key_hex, bool is_value_hex) {
  size_t pos = line.find(DELIM);
M
Mayank Agarwal 已提交
234
  if (pos != string::npos) {
235 236 237 238 239 240 241 242 243 244 245 246 247
    *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;
  }
}
248

249 250 251 252 253 254 255 256 257 258 259
/**
 * 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() {

  for (map<string, string>::const_iterator itr = options_.begin();
        itr != options_.end(); itr++) {
M
Mayank Agarwal 已提交
260
    if (find(valid_cmd_line_options_.begin(),
261 262 263 264 265 266
          valid_cmd_line_options_.end(), itr->first) ==
          valid_cmd_line_options_.end()) {
      fprintf(stderr, "Invalid command-line option %s\n", itr->first.c_str());
      return false;
    }
  }
267

268 269
  for (vector<string>::const_iterator itr = flags_.begin();
        itr != flags_.end(); itr++) {
M
Mayank Agarwal 已提交
270
    if (find(valid_cmd_line_options_.begin(),
271 272 273 274
          valid_cmd_line_options_.end(), *itr) ==
          valid_cmd_line_options_.end()) {
      fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
      return false;
275 276 277
    }
  }

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
  if (options_.find(ARG_DB) == options_.end()) {
    fprintf(stderr, "%s must be specified\n", ARG_DB.c_str());
    return false;
  }

  return true;
}

CompactorCommand::CompactorCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_FROM, ARG_TO, ARG_HEX, ARG_KEY_HEX,
                                   ARG_VALUE_HEX})),
    null_from_(true), null_to_(true) {

  map<string, string>::const_iterator itr = options.find(ARG_FROM);
  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_) {
306 307 308 309 310 311 312 313 314
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

315 316 317 318 319
void CompactorCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(CompactorCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
320 321
}

322
void CompactorCommand::DoCommand() {
323

324 325
  leveldb::Slice* begin = nullptr;
  leveldb::Slice* end = nullptr;
326 327 328 329 330 331 332 333 334 335 336 337 338 339
  if (!null_from_) {
    begin = new leveldb::Slice(from_);
  }
  if (!null_to_) {
    end = new leveldb::Slice(to_);
  }

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

  delete begin;
  delete end;
}

340
const string DBLoaderCommand::ARG_DISABLE_WAL = "disable_wal";
341 342
const string DBLoaderCommand::ARG_BULK_LOAD = "bulk_load";
const string DBLoaderCommand::ARG_COMPACT = "compact";
Z
Zheng Shao 已提交
343

344 345 346 347 348
DBLoaderCommand::DBLoaderCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                    ARG_FROM, ARG_TO, ARG_CREATE_IF_MISSING,
349 350 351 352
                                    ARG_DISABLE_WAL, ARG_BULK_LOAD,
                                    ARG_COMPACT})),
    create_if_missing_(false), disable_wal_(false), bulk_load_(false),
    compact_(false) {
353 354 355

  create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
356 357
  bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  compact_ = IsFlagPresent(flags, ARG_COMPACT);
Z
Zheng Shao 已提交
358 359
}

360 361 362 363 364
void DBLoaderCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DBLoaderCommand::Name());
  ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
  ret.append(" [--" + ARG_DISABLE_WAL + "]");
365 366
  ret.append(" [--" + ARG_BULK_LOAD + "]");
  ret.append(" [--" + ARG_COMPACT + "]");
367
  ret.append("\n");
Z
Zheng Shao 已提交
368 369
}

370
leveldb::Options DBLoaderCommand::PrepareOptionsForOpenDB() {
Z
Zheng Shao 已提交
371 372
  leveldb::Options opt = LDBCommand::PrepareOptionsForOpenDB();
  opt.create_if_missing = create_if_missing_;
373 374 375
  if (bulk_load_) {
    opt.PrepareForBulkLoad();
  }
Z
Zheng Shao 已提交
376 377 378
  return opt;
}

379
void DBLoaderCommand::DoCommand() {
Z
Zheng Shao 已提交
380 381 382 383 384 385 386 387 388 389
  if (!db_) {
    return;
  }

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

  int bad_lines = 0;
390
  string line;
M
Mayank Agarwal 已提交
391
  while (getline(cin, line, '\n')) {
392 393 394
    string key;
    string value;
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
Z
Zheng Shao 已提交
395 396 397 398 399 400 401 402 403
      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 ++;
    }
  }
404

Z
Zheng Shao 已提交
405
  if (bad_lines > 0) {
M
Mayank Agarwal 已提交
406
    cout << "Warning: " << bad_lines << " bad lines ignored." << endl;
Z
Zheng Shao 已提交
407
  }
408
  if (compact_) {
409
    db_->CompactRange(nullptr, nullptr);
410
  }
Z
Zheng Shao 已提交
411 412
}

413 414
const string DBDumperCommand::ARG_COUNT_ONLY = "count_only";
const string DBDumperCommand::ARG_STATS = "stats";
415

416 417 418 419 420 421
DBDumperCommand::DBDumperCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
    LDBCommand(options, flags, true,
               BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                    ARG_FROM, ARG_TO, ARG_MAX_KEYS,
                                    ARG_COUNT_ONLY, ARG_STATS})),
422 423 424 425
    null_from_(true),
    null_to_(true),
    max_keys_(-1),
    count_only_(false),
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    print_stats_(false) {

  map<string, string>::const_iterator itr = options.find(ARG_FROM);
  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 已提交
443 444
      max_keys_ = stoi(itr->second);
    } catch(const invalid_argument&) {
445 446
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has an invalid value");
M
Mayank Agarwal 已提交
447 448 449
    } catch(const out_of_range&) {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has a valuei out-of-range");
450 451 452
    }
  }

453 454 455 456
  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);

  if (is_key_hex_) {
457 458 459 460 461 462 463 464 465
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

466 467 468 469 470 471 472 473
void DBDumperCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DBDumperCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  ret.append(" [--" + ARG_COUNT_ONLY + "]");
  ret.append(" [--" + ARG_STATS + "]");
  ret.append("\n");
474 475
}

476
void DBDumperCommand::DoCommand() {
477 478 479
  if (!db_) {
    return;
  }
480 481 482
  // Parse command line args
  uint64_t count = 0;
  if (print_stats_) {
483
    string stats;
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    if (db_->GetProperty("leveldb.stats", &stats)) {
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Setup key iterator
  leveldb::Iterator* iter = db_->NewIterator(leveldb::ReadOptions());
  leveldb::Status st = iter->status();
  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_;
  for (; iter->Valid(); iter->Next()) {
    // 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;
    if (max_keys > 0) {
      --max_keys;
    }
    ++count;
    if (!count_only_) {
516
      string str = PrintKeyValue(iter->key().ToString(),
517
                                      iter->value().ToString(),
518
                                      is_key_hex_, is_value_hex_);
519
      fprintf(stdout, "%s\n", str.c_str());
520 521 522 523 524 525 526
    }
  }
  fprintf(stdout, "Keys in range: %lld\n", (long long) count);
  // Clean up
  delete iter;
}

527 528
const string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
const string  ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS = "print_old_levels";
529

530 531 532 533 534 535 536
ReduceDBLevelsCommand::ReduceDBLevelsCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_NEW_LEVELS, ARG_PRINT_OLD_LEVELS})),
    old_levels_(1 << 16),
    new_levels_(-1),
    print_old_levels_(false) {
537 538


539 540
  ParseIntOption(options_, ARG_NEW_LEVELS, new_levels_, exec_state_);
  print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
541 542 543

  if(new_levels_ <= 0) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
544
           " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
545 546 547
  }
}

548 549 550 551 552
vector<string> ReduceDBLevelsCommand::PrepareArgs(const string& db_path,
    int new_levels, bool print_old_level) {
  vector<string> ret;
  ret.push_back("reduce_levels");
  ret.push_back("--" + ARG_DB + "=" + db_path);
M
Mayank Agarwal 已提交
553
  ret.push_back("--" + ARG_NEW_LEVELS + "=" + to_string(new_levels));
554
  if(print_old_level) {
555
    ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
556 557 558 559
  }
  return ret;
}

560 561 562 563 564 565
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");
566 567
}

568
leveldb::Options ReduceDBLevelsCommand::PrepareOptionsForOpenDB() {
569
  leveldb::Options opt = LDBCommand::PrepareOptionsForOpenDB();
570 571
  opt.num_levels = old_levels_;
  // Disable size compaction
572
  opt.max_bytes_for_level_base = 1UL << 50;
573 574
  opt.max_bytes_for_level_multiplier = 1;
  opt.max_mem_compaction_level = 0;
575 576 577
  return opt;
}

578 579
Status ReduceDBLevelsCommand::GetOldNumOfLevels(leveldb::Options& opt,
    int* levels) {
580 581 582
  TableCache tc(db_path_, &opt, 10);
  const InternalKeyComparator cmp(opt.comparator);
  VersionSet versions(db_path_, &opt, &tc, &cmp);
583 584 585
  // 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.
586
  Status st = versions.Recover();
587 588 589 590
  if (!st.ok()) {
    return st;
  }
  int max = -1;
591 592
  for (int i = 0; i < versions.NumberLevels(); i++) {
    if (versions.NumLevelFiles(i)) {
593 594 595 596 597 598 599 600
      max = i;
    }
  }

  *levels = max + 1;
  return st;
}

601
void ReduceDBLevelsCommand::DoCommand() {
602 603 604 605 606 607 608 609
  if (new_levels_ <= 1) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
        "Invalid number of levels.\n");
    return;
  }

  leveldb::Status st;
  leveldb::Options opt = PrepareOptionsForOpenDB();
610 611 612 613 614 615 616
  int old_level_num = -1;
  st = GetOldNumOfLevels(opt, &old_level_num);
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
    return;
  }

617
  if (print_old_levels_) {
618 619
    fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
  }
620

621 622
  if (old_level_num <= new_levels_) {
    return;
623 624
  }

625 626 627
  old_levels_ = old_level_num;

  OpenDB();
628 629 630
  if (!db_) {
    return;
  }
631
  // Compact the whole DB to put all files to the highest level.
632
  fprintf(stdout, "Compacting the db...\n");
633
  db_->CompactRange(nullptr, nullptr);
634 635
  CloseDB();

636 637 638
  TableCache tc(db_path_, &opt, 10);
  const InternalKeyComparator cmp(opt.comparator);
  VersionSet versions(db_path_, &opt, &tc, &cmp);
639 640 641
  // 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.
642
  st = versions.Recover();
643 644 645 646 647 648 649
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
    return;
  }

  port::Mutex mu;
  mu.Lock();
650
  st = versions.ReduceNumberOfLevels(new_levels_, &mu);
651 652 653 654 655 656 657 658
  mu.Unlock();

  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
    return;
  }
}

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
class InMemoryHandler : public WriteBatch::Handler {
 public:

  virtual void Put(const Slice& key, const Slice& value) {
    putMap_[key.ToString()] = value.ToString();
  }
  virtual void Delete(const Slice& key) {
    deleteList_.push_back(key.ToString(true));
  }
  virtual ~InMemoryHandler() { };

  map<string, string> PutMap() {
    return putMap_;
  }
  vector<string> DeleteList() {
    return deleteList_;
  }

 private:
M
Mayank Agarwal 已提交
678 679
  map<string, string> putMap_;
  vector<string> deleteList_;
680 681
};

682
const string WALDumperCommand::ARG_WAL_FILE = "walfile";
683
const string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
684 685 686 687 688
const string WALDumperCommand::ARG_PRINT_HEADER = "header";

WALDumperCommand::WALDumperCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
    LDBCommand(options, flags, true,
689 690 691
               BuildCmdLineOptions(
                {ARG_WAL_FILE, ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
    print_header_(false), print_values_(false) {
692

A
Abhishek Kona 已提交
693
  wal_file_.clear();
694 695 696 697

  map<string, string>::const_iterator itr = options.find(ARG_WAL_FILE);
  if (itr != options.end()) {
    wal_file_ = itr->second;
A
Abhishek Kona 已提交
698
  }
699 700


701 702
  print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
A
Abhishek Kona 已提交
703
  if (wal_file_.empty()) {
704 705
    exec_state_ = LDBCommandExecuteResult::FAILED(
                    "Argument " + ARG_WAL_FILE + " must be specified.");
A
Abhishek Kona 已提交
706 707 708
  }
}

709 710 711 712 713
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 + "] ");
714
  ret.append(" --[ " + ARG_PRINT_VALUE + "] ");
715
  ret.append("\n");
A
Abhishek Kona 已提交
716 717
}

718
void WALDumperCommand::DoCommand() {
A
Abhishek Kona 已提交
719 720
  struct StdErrReporter : public log::Reader::Reporter {
    virtual void Corruption(size_t bytes, const Status& s) {
M
Mayank Agarwal 已提交
721
      cerr<<"Corruption detected in log file "<<s.ToString()<<"\n";
A
Abhishek Kona 已提交
722 723 724
    }
  };

725
  unique_ptr<SequentialFile> file;
A
Abhishek Kona 已提交
726 727 728 729 730 731 732
  Env* env_ = Env::Default();
  Status status = env_->NewSequentialFile(wal_file_, &file);
  if (!status.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED("Failed to open WAL file " +
      status.ToString());
  } else {
    StdErrReporter reporter;
M
Mayank Agarwal 已提交
733
    log::Reader reader(move(file), &reporter, true, 0);
734
    string scratch;
A
Abhishek Kona 已提交
735 736
    WriteBatch batch;
    Slice record;
M
Mayank Agarwal 已提交
737
    stringstream row;
A
Abhishek Kona 已提交
738
    if (print_header_) {
M
Mayank Agarwal 已提交
739
      cout<<"Sequence,Count,ByteSize,Physical Offset,Key(s)";
740
      if (print_values_) {
M
Mayank Agarwal 已提交
741
        cout << " : value ";
742
      }
M
Mayank Agarwal 已提交
743
      cout << "\n";
A
Abhishek Kona 已提交
744 745
    }
    while(reader.ReadRecord(&record, &scratch)) {
746
      row.str("");
A
Abhishek Kona 已提交
747 748 749 750 751 752 753
      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)<<",";
754
        row<<WriteBatchInternal::ByteSize(&batch)<<",";
755 756 757 758 759 760
        row<<reader.LastRecordOffset()<<",";
        InMemoryHandler handler;
        batch.Iterate(&handler);
        row << "PUT : ";
        if (print_values_) {
          for (auto& kv : handler.PutMap()) {
M
Mayank Agarwal 已提交
761 762
            string k = StringToHex(kv.first);
            string v = StringToHex(kv.second);
763 764 765 766 767 768 769 770 771 772 773 774 775 776
            row << k << " : ";
            row << v << " ";
          }
        }
        else {
          for(auto& kv : handler.PutMap()) {
            row << StringToHex(kv.first) << " ";
          }
        }
        row<<",DELETE : ";
        for(string& s : handler.DeleteList()) {
          row << StringToHex(s) << " ";
        }
        row<<"\n";
A
Abhishek Kona 已提交
777
      }
M
Mayank Agarwal 已提交
778
      cout<<row.str();
A
Abhishek Kona 已提交
779 780 781 782
    }
  }
}

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

GetCommand::GetCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
  LDBCommand(options, flags, true,
             BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {

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

void GetCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(GetCommand::Name());
  ret.append(" <key>");
  ret.append("\n");
}

void GetCommand::DoCommand() {
  string value;
  leveldb::Status st = db_->Get(leveldb::ReadOptions(), key_, &value);
  if (st.ok()) {
    fprintf(stdout, "%s\n",
              (is_value_hex_ ? StringToHex(value) : value).c_str());
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}


ApproxSizeCommand::ApproxSizeCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
  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_);
  }
}

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

void ApproxSizeCommand::DoCommand() {

  leveldb::Range ranges[1];
  ranges[0] = leveldb::Range(start_key_, end_key_);
  uint64_t sizes[1];
  db_->GetApproximateSizes(ranges, 1, sizes);
  fprintf(stdout, "%ld\n", sizes[0]);
  /* Wierd that GetApproximateSizes() returns void, although documentation
   * says that it returns a Status object.
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
  */
}


BatchPutCommand::BatchPutCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
  LDBCommand(options, flags, false,
             BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                  ARG_CREATE_IF_MISSING})) {

  if (params.size() < 2) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
        "At least one <key> <value> pair must be specified batchput.");
  } 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) {
      string key = params.at(i);
      string value = params.at(i+1);
M
Mayank Agarwal 已提交
887
      key_values_.push_back(pair<string, string>(
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
                    is_key_hex_ ? HexToString(key) : key,
                    is_value_hex_ ? HexToString(value) : value));
    }
  }
}

void BatchPutCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(BatchPutCommand::Name());
  ret.append(" <key> <value> [<key> <value>] [..]");
  ret.append("\n");
}

void BatchPutCommand::DoCommand() {
  leveldb::WriteBatch batch;

M
Mayank Agarwal 已提交
904
  for (vector<pair<string, string>>::const_iterator itr
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
        = key_values_.begin(); itr != key_values_.end(); itr++) {
      batch.Put(itr->first, itr->second);
  }
  leveldb::Status st = db_->Write(leveldb::WriteOptions(), &batch);
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}

leveldb::Options BatchPutCommand::PrepareOptionsForOpenDB() {
  leveldb::Options opt = LDBCommand::PrepareOptionsForOpenDB();
  opt.create_if_missing = IsFlagPresent(flags_, ARG_CREATE_IF_MISSING);
  return opt;
}


ScanCommand::ScanCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
    LDBCommand(options, flags, true,
               BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                    ARG_FROM, ARG_TO, ARG_MAX_KEYS})),
    start_key_specified_(false),
    end_key_specified_(false),
    max_keys_scanned_(-1) {

  map<string, string>::const_iterator itr = options.find(ARG_FROM);
  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 已提交
952 953
      max_keys_scanned_ = stoi(itr->second);
    } catch(const invalid_argument&) {
954 955
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has an invalid value");
M
Mayank Agarwal 已提交
956 957 958
    } catch(const out_of_range&) {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has a value out-of-range");
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    }
  }
}

void ScanCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ScanCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("--" + ARG_MAX_KEYS + "=N] ");
  ret.append("\n");
}

void ScanCommand::DoCommand() {

  int num_keys_scanned = 0;
  Iterator* it = db_->NewIterator(leveldb::ReadOptions());
  if (start_key_specified_) {
    it->Seek(start_key_);
  } else {
    it->SeekToFirst();
  }
  for ( ;
        it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
        it->Next()) {
    string key = it->key().ToString();
    string value = it->value().ToString();
    fprintf(stdout, "%s : %s\n",
          (is_key_hex_ ? StringToHex(key) : key).c_str(),
          (is_value_hex_ ? StringToHex(value) : value).c_str()
        );
    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;
}


DeleteCommand::DeleteCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
  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_);
    }
  }
}

void DeleteCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DeleteCommand::Name() + " <key>");
  ret.append("\n");
}

void DeleteCommand::DoCommand() {
  leveldb::Status st = db_->Delete(leveldb::WriteOptions(), key_);
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}


PutCommand::PutCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
  LDBCommand(options, flags, false,
             BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
                                  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_);
  }
}

void PutCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(PutCommand::Name());
  ret.append(" <key> <value> ");
  ret.append("\n");
}

void PutCommand::DoCommand() {
  leveldb::Status st = db_->Put(leveldb::WriteOptions(), key_, value_);
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}

leveldb::Options PutCommand::PrepareOptionsForOpenDB() {
  leveldb::Options opt = LDBCommand::PrepareOptionsForOpenDB();
  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";

DBQuerierCommand::DBQuerierCommand(const vector<string>& params,
    const map<string, string>& options, const vector<string>& flags) :
  LDBCommand(options, flags, false,
             BuildCmdLineOptions({ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX})) {

}

void DBQuerierCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DBQuerierCommand::Name());
  ret.append("\n");
  ret.append("    Starts a REPL shell.  Type help for list of available "
             "commands.");
  ret.append("\n");
}

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

  leveldb::ReadOptions read_options;
  leveldb::WriteOptions write_options;

  string line;
  string key;
  string value;
M
Mayank Agarwal 已提交
1111
  while (getline(cin, line, '\n')) {
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

    // Parse line into vector<string>
    vector<string> tokens;
    size_t pos = 0;
    while (true) {
      size_t pos2 = line.find(' ', pos);
      if (pos2 == string::npos) {
        break;
      }
      tokens.push_back(line.substr(pos, pos2-pos));
      pos = pos2 + 1;
    }
    tokens.push_back(line.substr(pos));

    const string& cmd = tokens[0];

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


1158
}