ldb_cmd.cc 53.8 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.
//
6
#include "util/ldb_cmd.h"
A
Abhishek Kona 已提交
7 8

#include "db/dbformat.h"
9
#include "db/db_impl.h"
A
Abhishek Kona 已提交
10
#include "db/log_reader.h"
11
#include "db/filename.h"
A
Abhishek Kona 已提交
12
#include "db/write_batch_internal.h"
13
#include "rocksdb/write_batch.h"
14 15 16 17 18 19 20
#include "util/coding.h"

#include <ctime>
#include <dirent.h>
#include <sstream>
#include <string>
#include <stdexcept>
21

22
namespace rocksdb {
23

M
Mayank Agarwal 已提交
24 25
using namespace std;

26 27 28 29
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";
30
const string LDBCommand::ARG_TTL = "ttl";
31 32 33
const string LDBCommand::ARG_TTL_START = "start_time";
const string LDBCommand::ARG_TTL_END = "end_time";
const string LDBCommand::ARG_TIMESTAMP = "timestamp";
34 35 36 37 38 39 40 41 42 43 44
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";

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

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

/**
 * 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.
67
 * Returns nullptr if the command-line cannot be parsed.
68
 */
69 70
LDBCommand* LDBCommand::InitFromCmdLineArgs(
  const vector<string>& args,
71
  const Options& options
72
) {
73
  // --x=y command line arguments are added as x->y map entries.
74
  map<string, string> option_map;
75 76 77 78

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

79
  // Everything other than option_map and flags. Represents commands
80 81 82 83 84
  // and their parameters.  For eg: put key1 value1 go into this vector.
  vector<string> cmdTokens;

  const string OPTION_PREFIX = "--";

85
  for (const auto& arg : args) {
M
Mayank Agarwal 已提交
86 87
    if (arg[0] == '-' && arg[1] == '-'){
      vector<string> splits = stringSplit(arg, '=');
88 89
      if (splits.size() == 2) {
        string optionKey = splits[0].substr(OPTION_PREFIX.size());
90
        option_map[optionKey] = splits[1];
91 92 93 94
      } else {
        string optionKey = splits[0].substr(OPTION_PREFIX.size());
        flags.push_back(optionKey);
      }
95
    } else {
96
      cmdTokens.push_back(arg);
97 98 99 100 101
    }
  }

  if (cmdTokens.size() < 1) {
    fprintf(stderr, "Command not specified!");
102
    return nullptr;
103 104 105 106
  }

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

  if (command) {
    command->SetOptions(options);
  }
  return command;
}

LDBCommand* LDBCommand::SelectCommand(
    const std::string& cmd,
122 123 124
    const vector<string>& cmdParams,
    const map<string, string>& option_map,
    const vector<string>& flags
125
  ) {
126 127

  if (cmd == GetCommand::Name()) {
128
    return new GetCommand(cmdParams, option_map, flags);
129
  } else if (cmd == PutCommand::Name()) {
130
    return new PutCommand(cmdParams, option_map, flags);
131
  } else if (cmd == BatchPutCommand::Name()) {
132
    return new BatchPutCommand(cmdParams, option_map, flags);
133
  } else if (cmd == ScanCommand::Name()) {
134
    return new ScanCommand(cmdParams, option_map, flags);
135
  } else if (cmd == DeleteCommand::Name()) {
136
    return new DeleteCommand(cmdParams, option_map, flags);
137
  } else if (cmd == ApproxSizeCommand::Name()) {
138
    return new ApproxSizeCommand(cmdParams, option_map, flags);
139
  } else if (cmd == DBQuerierCommand::Name()) {
140
    return new DBQuerierCommand(cmdParams, option_map, flags);
141
  } else if (cmd == CompactorCommand::Name()) {
142
    return new CompactorCommand(cmdParams, option_map, flags);
143
  } else if (cmd == WALDumperCommand::Name()) {
144
    return new WALDumperCommand(cmdParams, option_map, flags);
145
  } else if (cmd == ReduceDBLevelsCommand::Name()) {
146
    return new ReduceDBLevelsCommand(cmdParams, option_map, flags);
147 148
  } else if (cmd == ChangeCompactionStyleCommand::Name()) {
    return new ChangeCompactionStyleCommand(cmdParams, option_map, flags);
149
  } else if (cmd == DBDumperCommand::Name()) {
150
    return new DBDumperCommand(cmdParams, option_map, flags);
151
  } else if (cmd == DBLoaderCommand::Name()) {
152
    return new DBLoaderCommand(cmdParams, option_map, flags);
153
  } else if (cmd == ManifestDumpCommand::Name()) {
154
    return new ManifestDumpCommand(cmdParams, option_map, flags);
155 156
  } else if (cmd == InternalDumpCommand::Name()) {
    return new InternalDumpCommand(cmdParams, option_map, flags);
157
  }
158
  return nullptr;
159 160
}

161

162 163 164 165 166 167 168 169
/**
 * 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,
170 171
                                const string& option, int& value,
                                LDBCommandExecuteResult& exec_state) {
172

173 174
  map<string, string>::const_iterator itr = option_map_.find(option);
  if (itr != option_map_.end()) {
175
    try {
M
Mayank Agarwal 已提交
176
      value = stoi(itr->second);
177
      return true;
M
Mayank Agarwal 已提交
178
    } catch(const invalid_argument&) {
179 180
      exec_state = LDBCommandExecuteResult::FAILED(option +
                      " has an invalid value.");
M
Mayank Agarwal 已提交
181 182 183
    } catch(const out_of_range&) {
      exec_state = LDBCommandExecuteResult::FAILED(option +
                      " has a value out-of-range.");
184 185
    }
  }
186
  return false;
187 188
}

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
/**
 * Parses the specified option and fills in the value.
 * Returns true if the option is found.
 * Returns false otherwise.
 */
bool LDBCommand::ParseStringOption(const map<string, string>& options,
                                   const string& option, string* value) {
  auto itr = option_map_.find(option);
  if (itr != option_map_.end()) {
    *value = itr->second;
    return true;
  }
  return false;
}

204
Options LDBCommand::PrepareOptionsForOpenDB() {
205

206
  Options opt = options_;
207
  opt.create_if_missing = false;
208 209 210 211

  map<string, string>::const_iterator itr;

  int bits;
212
  if (ParseIntOption(option_map_, ARG_BLOOM_BITS, bits, exec_state_)) {
213
    if (bits > 0) {
214
      opt.filter_policy = NewBloomFilterPolicy(bits);
215 216 217 218 219 220 221
    } else {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_BLOOM_BITS +
                      " must be > 0.");
    }
  }

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

231 232
  itr = option_map_.find(ARG_AUTO_COMPACTION);
  if (itr != option_map_.end()) {
233 234 235
    opt.disable_auto_compactions = ! StringToBool(itr->second);
  }

236 237
  itr = option_map_.find(ARG_COMPRESSION_TYPE);
  if (itr != option_map_.end()) {
238 239
    string comp = itr->second;
    if (comp == "no") {
240
      opt.compression = kNoCompression;
241
    } else if (comp == "snappy") {
242
      opt.compression = kSnappyCompression;
243
    } else if (comp == "zlib") {
244
      opt.compression = kZlibCompression;
245
    } else if (comp == "bzip2") {
246
      opt.compression = kBZip2Compression;
247 248 249 250 251 252 253 254
    } else {
      // Unknown compression.
      exec_state_ = LDBCommandExecuteResult::FAILED(
                      "Unknown compression level: " + comp);
    }
  }

  int write_buffer_size;
255
  if (ParseIntOption(option_map_, ARG_WRITE_BUFFER_SIZE, write_buffer_size,
256 257
        exec_state_)) {
    if (write_buffer_size > 0) {
258
      opt.write_buffer_size = write_buffer_size;
259 260 261 262 263 264 265
    } else {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_WRITE_BUFFER_SIZE +
                      " must be > 0.");
    }
  }

  int file_size;
266
  if (ParseIntOption(option_map_, ARG_FILE_SIZE, file_size, exec_state_)) {
267
    if (file_size > 0) {
268 269
      opt.target_file_size_base = file_size;
    } else {
270 271
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_FILE_SIZE +
                      " must be > 0.");
272 273 274 275 276 277
    }
  }

  return opt;
}

278 279 280
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 已提交
281
  if (pos != string::npos) {
282 283 284 285 286 287 288 289 290 291 292 293 294
    *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;
  }
}
295

296 297 298 299 300 301 302 303 304
/**
 * 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() {

305 306
  for (map<string, string>::const_iterator itr = option_map_.begin();
        itr != option_map_.end(); itr++) {
M
Mayank Agarwal 已提交
307
    if (find(valid_cmd_line_options_.begin(),
308 309 310 311 312 313
          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;
    }
  }
314

315 316
  for (vector<string>::const_iterator itr = flags_.begin();
        itr != flags_.end(); itr++) {
M
Mayank Agarwal 已提交
317
    if (find(valid_cmd_line_options_.begin(),
318 319 320 321
          valid_cmd_line_options_.end(), *itr) ==
          valid_cmd_line_options_.end()) {
      fprintf(stderr, "Invalid command-line flag %s\n", itr->c_str());
      return false;
322 323 324
    }
  }

325
  if (!NoDBOpen() && option_map_.find(ARG_DB) == option_map_.end()) {
326 327 328 329 330 331 332 333 334 335 336
    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,
337
                                    ARG_VALUE_HEX, ARG_TTL})),
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    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_) {
353 354 355 356 357 358 359 360 361
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

362 363 364 365 366
void CompactorCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(CompactorCommand::Name());
  ret.append(HelpRangeCmdArgs());
  ret.append("\n");
367 368
}

369
void CompactorCommand::DoCommand() {
370

371 372
  Slice* begin = nullptr;
  Slice* end = nullptr;
373
  if (!null_from_) {
374
    begin = new Slice(from_);
375 376
  }
  if (!null_to_) {
377
    end = new Slice(to_);
378 379 380 381 382 383 384 385 386
  }

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

  delete begin;
  delete end;
}

387
const string DBLoaderCommand::ARG_DISABLE_WAL = "disable_wal";
388 389
const string DBLoaderCommand::ARG_BULK_LOAD = "bulk_load";
const string DBLoaderCommand::ARG_COMPACT = "compact";
Z
Zheng Shao 已提交
390

391 392 393 394 395
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,
396 397 398 399
                                    ARG_DISABLE_WAL, ARG_BULK_LOAD,
                                    ARG_COMPACT})),
    create_if_missing_(false), disable_wal_(false), bulk_load_(false),
    compact_(false) {
400 401 402

  create_if_missing_ = IsFlagPresent(flags, ARG_CREATE_IF_MISSING);
  disable_wal_ = IsFlagPresent(flags, ARG_DISABLE_WAL);
403 404
  bulk_load_ = IsFlagPresent(flags, ARG_BULK_LOAD);
  compact_ = IsFlagPresent(flags, ARG_COMPACT);
Z
Zheng Shao 已提交
405 406
}

407 408 409 410 411
void DBLoaderCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DBLoaderCommand::Name());
  ret.append(" [--" + ARG_CREATE_IF_MISSING + "]");
  ret.append(" [--" + ARG_DISABLE_WAL + "]");
412 413
  ret.append(" [--" + ARG_BULK_LOAD + "]");
  ret.append(" [--" + ARG_COMPACT + "]");
414
  ret.append("\n");
Z
Zheng Shao 已提交
415 416
}

417 418
Options DBLoaderCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
Z
Zheng Shao 已提交
419
  opt.create_if_missing = create_if_missing_;
420 421 422
  if (bulk_load_) {
    opt.PrepareForBulkLoad();
  }
Z
Zheng Shao 已提交
423 424 425
  return opt;
}

426
void DBLoaderCommand::DoCommand() {
Z
Zheng Shao 已提交
427 428 429 430 431 432 433 434 435 436
  if (!db_) {
    return;
  }

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

  int bad_lines = 0;
437
  string line;
M
Mayank Agarwal 已提交
438
  while (getline(cin, line, '\n')) {
439 440 441
    string key;
    string value;
    if (ParseKeyValue(line, &key, &value, is_key_hex_, is_value_hex_)) {
Z
Zheng Shao 已提交
442 443 444 445 446 447 448 449 450
      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 ++;
    }
  }
451

Z
Zheng Shao 已提交
452
  if (bad_lines > 0) {
M
Mayank Agarwal 已提交
453
    cout << "Warning: " << bad_lines << " bad lines ignored." << endl;
Z
Zheng Shao 已提交
454
  }
455
  if (compact_) {
456
    db_->CompactRange(nullptr, nullptr);
457
  }
Z
Zheng Shao 已提交
458 459
}

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
// ----------------------------------------------------------------------------

const string ManifestDumpCommand::ARG_VERBOSE = "verbose";
const string ManifestDumpCommand::ARG_PATH    = "path";

void ManifestDumpCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ManifestDumpCommand::Name());
  ret.append(" [--" + ARG_VERBOSE + "]");
  ret.append(" [--" + ARG_PATH + "=<path_to_manifest_file>]");
  ret.append("\n");
}

ManifestDumpCommand::ManifestDumpCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
    LDBCommand(options, flags, false,
476
               BuildCmdLineOptions({ARG_VERBOSE, ARG_PATH, ARG_HEX})),
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    verbose_(false),
    path_("")
{
  verbose_ = IsFlagPresent(flags, ARG_VERBOSE);

  map<string, string>::const_iterator itr = options.find(ARG_PATH);
  if (itr != options.end()) {
    path_ = itr->second;
    if (path_.empty()) {
      exec_state_ = LDBCommandExecuteResult::FAILED("--path: missing pathname");
    }
  }
}

void ManifestDumpCommand::DoCommand() {

  std::string manifestfile;

  if (!path_.empty()) {
    manifestfile = path_;
  } else {
    bool found = false;
    // We need to find the manifest file by searching the directory
    // containing the db for files of the form MANIFEST_[0-9]+
    DIR* d = opendir(db_path_.c_str());
    if (d == nullptr) {
      exec_state_ = LDBCommandExecuteResult::FAILED(
        db_path_ + " is not a directory");
      return;
    }
    struct dirent* entry;
    while ((entry = readdir(d)) != nullptr) {
      unsigned int match;
      unsigned long long num;
K
Kai Liu 已提交
511 512 513 514
      if (sscanf(entry->d_name,
                 "MANIFEST-%ln%ln",
                 (unsigned long*)&num,
                 (unsigned long*)&match)
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
          && match == strlen(entry->d_name)) {
        if (!found) {
          manifestfile = db_path_ + "/" + std::string(entry->d_name);
          found = true;
        } else {
          exec_state_ = LDBCommandExecuteResult::FAILED(
            "Multiple MANIFEST files found; use --path to select one");
          return;
        }
      }
    }
    closedir(d);
  }

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

  Options options;
H
Haobo Xu 已提交
534
  EnvOptions sopt;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
  std::string file(manifestfile);
  std::string dbname("dummy");
  TableCache* tc = new TableCache(dbname, &options, sopt, 10);
  const InternalKeyComparator* cmp =
    new InternalKeyComparator(options.comparator);

  VersionSet* versions = new VersionSet(dbname, &options, sopt, tc, cmp);
  Status s = versions->DumpManifest(options, file, verbose_, is_key_hex_);
  if (!s.ok()) {
    printf("Error in processing file %s %s\n", manifestfile.c_str(),
           s.ToString().c_str());
  }
  if (verbose_) {
    printf("Processing Manifest file %s done\n", manifestfile.c_str());
  }
}

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

554 555 556 557 558 559 560 561 562 563
string ReadableTime(int unixtime) {
  char time_buffer [80];
  time_t rawtime = unixtime;
  struct tm * timeinfo = localtime(&rawtime);
  strftime(time_buffer, 80, "%c", timeinfo);
  return string(time_buffer);
}

// 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
564 565 566 567 568 569
void IncBucketCounts(vector<uint64_t>& bucket_counts, int ttl_start,
      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;
  bucket_counts[bucket]++;
570 571
}

572 573
void PrintBucketCounts(const vector<uint64_t>& bucket_counts, int ttl_start,
      int ttl_end, int bucket_size, int num_buckets) {
574 575
  int time_point = ttl_start;
  for(int i = 0; i < num_buckets - 1; i++, time_point += bucket_size) {
K
Kai Liu 已提交
576
    fprintf(stdout, "Keys in range %s to %s : %lu\n",
577
            ReadableTime(time_point).c_str(),
K
Kai Liu 已提交
578 579
            ReadableTime(time_point + bucket_size).c_str(),
            (unsigned long)bucket_counts[i]);
580
  }
K
Kai Liu 已提交
581
  fprintf(stdout, "Keys in range %s to %s : %lu\n",
582
          ReadableTime(time_point).c_str(),
K
Kai Liu 已提交
583 584
          ReadableTime(ttl_end).c_str(),
          (unsigned long)bucket_counts[num_buckets - 1]);
585 586
}

587
const string InternalDumpCommand::ARG_COUNT_ONLY = "count_only";
588
const string InternalDumpCommand::ARG_COUNT_DELIM = "count_delim";
589
const string InternalDumpCommand::ARG_STATS = "stats";
590
const string InternalDumpCommand::ARG_INPUT_KEY_HEX = "input_key_hex";
591 592 593 594 595 596 597

InternalDumpCommand::InternalDumpCommand(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,
598
                                     ARG_COUNT_ONLY, ARG_COUNT_DELIM, ARG_STATS,
599
                                     ARG_INPUT_KEY_HEX})),
600 601 602
    has_from_(false),
    has_to_(false),
    max_keys_(-1),
603
    delim_("."),
604
    count_only_(false),
605
    count_delim_(false),
606 607
    print_stats_(false),
    is_input_key_hex_(false) {
608 609 610 611 612

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

  ParseIntOption(options, ARG_MAX_KEYS, max_keys_, exec_state_);
613 614 615 616 617 618 619 620 621
  map<string, string>::const_iterator itr = options.find(ARG_COUNT_DELIM);
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
   // fprintf(stdout,"delim = %c\n",delim_[0]);
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
    delim_=".";
  }
622 623 624

  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);
625
  is_input_key_hex_ = IsFlagPresent(flags, ARG_INPUT_KEY_HEX);
626

627
  if (is_input_key_hex_) {
628 629 630 631 632 633 634 635 636 637 638 639 640
    if (has_from_) {
      from_ = HexToString(from_);
    }
    if (has_to_) {
      to_ = HexToString(to_);
    }
  }
}

void InternalDumpCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(InternalDumpCommand::Name());
  ret.append(HelpRangeCmdArgs());
641
  ret.append(" [--" + ARG_INPUT_KEY_HEX + "]");
642 643
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
  ret.append(" [--" + ARG_COUNT_ONLY + "]");
644
  ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
645 646 647 648 649 650 651 652 653 654 655
  ret.append(" [--" + ARG_STATS + "]");
  ret.append("\n");
}

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

  if (print_stats_) {
    string stats;
656
    if (db_->GetProperty("rocksdb.stats", &stats)) {
657 658 659 660 661 662 663 664 665 666
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Cast as DBImpl to get internal iterator
  DBImpl* idb = dynamic_cast<DBImpl*>(db_);
  if (!idb) {
    exec_state_ = LDBCommandExecuteResult::FAILED("DB is not DBImpl");
    return;
  }
667 668 669 670
  string rtype1,rtype2,row,val;
  rtype2 = "";
  uint64_t c=0;
  uint64_t s1=0,s2=0;
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
  // Setup internal key iterator
  auto iter = unique_ptr<Iterator>(idb->TEST_NewInternalIterator());
  Status st = iter->status();
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED("Iterator error:"
                                                  + st.ToString());
  }

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

  long long count = 0;
  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;
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    int k;
    if (count_delim_) {
      rtype1 = "";
      s1=0;
      row = iter->key().ToString();
      val = iter->value().ToString();
      for(k=0;row[k]!='\x01' && row[k]!='\0';k++)
        s1++;
      for(k=0;val[k]!='\x01' && val[k]!='\0';k++)
        s1++;
      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;
        rtype2 = rtype1;
      } else {
        c++;
        s2+=s1;
        rtype2=rtype1;
    }
  }
726

727
    if (!count_only_ && !count_delim_) {
728 729
      string key = ikey.DebugString(is_key_hex_);
      string value = iter->value().ToString(is_value_hex_);
730
      std::cout << key << " => " << value << "\n";
731 732 733 734 735
    }

    // Terminate if maximum number of keys have been dumped
    if (max_keys_ > 0 && count >= max_keys_) break;
  }
736 737 738 739
  if(count_delim_) {
    fprintf(stdout,"%s => count:%lld\tsize:%lld\n", rtype2.c_str(),
        (long long)c,(long long)s2);
  } else
740 741 742 743
  fprintf(stdout, "Internal keys in range: %lld\n", (long long) count);
}


744
const string DBDumperCommand::ARG_COUNT_ONLY = "count_only";
745
const string DBDumperCommand::ARG_COUNT_DELIM = "count_delim";
746
const string DBDumperCommand::ARG_STATS = "stats";
747
const string DBDumperCommand::ARG_TTL_BUCKET = "bucket";
748

749 750 751
DBDumperCommand::DBDumperCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
    LDBCommand(options, flags, true,
752 753
               BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
                                    ARG_VALUE_HEX, ARG_FROM, ARG_TO,
754 755 756 757
                                    ARG_MAX_KEYS, ARG_COUNT_ONLY,
                                    ARG_COUNT_DELIM, ARG_STATS, ARG_TTL_START,
                                    ARG_TTL_END, ARG_TTL_BUCKET,
                                    ARG_TIMESTAMP})),
758 759 760 761
    null_from_(true),
    null_to_(true),
    max_keys_(-1),
    count_only_(false),
762
    count_delim_(false),
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    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 已提交
780 781
      max_keys_ = stoi(itr->second);
    } catch(const invalid_argument&) {
782 783
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has an invalid value");
M
Mayank Agarwal 已提交
784 785
    } catch(const out_of_range&) {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
786
                        " has a value out-of-range");
787 788
    }
  }
789 790 791 792 793 794 795 796
  itr = options.find(ARG_COUNT_DELIM);
  if (itr != options.end()) {
    delim_ = itr->second;
    count_delim_ = true;
  } else {
    count_delim_ = IsFlagPresent(flags, ARG_COUNT_DELIM);
    delim_=".";
  }
797

798 799 800 801
  print_stats_ = IsFlagPresent(flags, ARG_STATS);
  count_only_ = IsFlagPresent(flags, ARG_COUNT_ONLY);

  if (is_key_hex_) {
802 803 804 805 806 807 808 809 810
    if (!null_from_) {
      from_ = HexToString(from_);
    }
    if (!null_to_) {
      to_ = HexToString(to_);
    }
  }
}

811 812 813 814
void DBDumperCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DBDumperCommand::Name());
  ret.append(HelpRangeCmdArgs());
815
  ret.append(" [--" + ARG_TTL + "]");
816
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>]");
817
  ret.append(" [--" + ARG_TIMESTAMP + "]");
818
  ret.append(" [--" + ARG_COUNT_ONLY + "]");
819
  ret.append(" [--" + ARG_COUNT_DELIM + "=<char>]");
820
  ret.append(" [--" + ARG_STATS + "]");
821
  ret.append(" [--" + ARG_TTL_BUCKET + "=<N>]");
822 823
  ret.append(" [--" + ARG_TTL_START + "=<N>:- is inclusive]");
  ret.append(" [--" + ARG_TTL_END + "=<N>:- is exclusive]");
824
  ret.append("\n");
825 826
}

827
void DBDumperCommand::DoCommand() {
828 829 830
  if (!db_) {
    return;
  }
831 832 833
  // Parse command line args
  uint64_t count = 0;
  if (print_stats_) {
834
    string stats;
835
    if (db_->GetProperty("rocksdb.stats", &stats)) {
836 837 838 839 840
      fprintf(stdout, "%s\n", stats.c_str());
    }
  }

  // Setup key iterator
841 842
  Iterator* iter = db_->NewIterator(ReadOptions());
  Status st = iter->status();
843 844 845 846 847 848 849 850 851 852 853 854
  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_;
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
  int ttl_start;
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
    ttl_start = DBWithTTL::kMinTimestamp; // TTL introduction time
  }
  int ttl_end;
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
    ttl_end = DBWithTTL::kMaxTimestamp; // Max time allowed by TTL feature
  }
  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;
  if (!ParseIntOption(option_map_, ARG_TTL_BUCKET, bucket_size, exec_state_) ||
      bucket_size <= 0) {
    bucket_size = time_range; // Will have just 1 bucket by default
  }
874 875 876 877 878 879
  //cretaing variables for row count of each type
  string rtype1,rtype2,row,val;
  rtype2 = "";
  uint64_t c=0;
  uint64_t s1=0,s2=0;

880
  // At this point, bucket_size=0 => time_range=0
881 882 883
  uint64_t num_buckets = (bucket_size >= time_range) ? 1 :
    ((time_range + bucket_size - 1) / bucket_size);
  vector<uint64_t> bucket_counts(num_buckets, 0);
884
  if (is_db_ttl_ && !count_only_ && timestamp_ && !count_delim_) {
885 886 887 888
    fprintf(stdout, "Dumping key-values from %s to %s\n",
            ReadableTime(ttl_start).c_str(), ReadableTime(ttl_end).c_str());
  }

889
  for (; iter->Valid(); iter->Next()) {
890
    int rawtime = 0;
891 892 893 894 895 896
    // 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;
897
    if (is_db_ttl_) {
898 899
      TtlIterator* it_ttl = dynamic_cast<TtlIterator*>(iter);
      assert(it_ttl);
900 901
      rawtime = it_ttl->timestamp();
      if (rawtime < ttl_start || rawtime >= ttl_end) {
902 903 904
        continue;
      }
    }
905 906 907
    if (max_keys > 0) {
      --max_keys;
    }
908
    if (is_db_ttl_ && num_buckets > 1) {
909
      IncBucketCounts(bucket_counts, ttl_start, time_range, bucket_size,
910 911
                      rawtime, num_buckets);
    }
912
    ++count;
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    if (count_delim_) {
      rtype1 = "";
      row = iter->key().ToString();
      val = iter->value().ToString();
      s1 = row.size()+val.size();
      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;
        rtype2 = rtype1;
      } else {
          c++;
          s2+=s1;
          rtype2=rtype1;
      }

    }



    if (!count_only_ && !count_delim_) {
937 938 939
      if (is_db_ttl_ && timestamp_) {
        fprintf(stdout, "%s ", ReadableTime(rawtime).c_str());
      }
940
      string str = PrintKeyValue(iter->key().ToString(),
941 942
                                 iter->value().ToString(), is_key_hex_,
                                 is_value_hex_);
943
      fprintf(stdout, "%s\n", str.c_str());
944 945
    }
  }
946

947
  if (num_buckets > 1 && is_db_ttl_) {
948
    PrintBucketCounts(bucket_counts, ttl_start, ttl_end, bucket_size,
949
                      num_buckets);
950 951 952
  } else if(count_delim_) {
    fprintf(stdout,"%s => count:%lld\tsize:%lld\n",rtype2.c_str(),
        (long long )c,(long long)s2);
953 954 955
  } else {
    fprintf(stdout, "Keys in range: %lld\n", (long long) count);
  }
956 957 958 959
  // Clean up
  delete iter;
}

960 961
const string ReduceDBLevelsCommand::ARG_NEW_LEVELS = "new_levels";
const string  ReduceDBLevelsCommand::ARG_PRINT_OLD_LEVELS = "print_old_levels";
962

963 964 965 966 967 968 969
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) {
970 971


972
  ParseIntOption(option_map_, ARG_NEW_LEVELS, new_levels_, exec_state_);
973
  print_old_levels_ = IsFlagPresent(flags, ARG_PRINT_OLD_LEVELS);
974 975 976

  if(new_levels_ <= 0) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
977
           " Use --" + ARG_NEW_LEVELS + " to specify a new level number\n");
978 979 980
  }
}

981 982 983 984 985
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 已提交
986
  ret.push_back("--" + ARG_NEW_LEVELS + "=" + to_string(new_levels));
987
  if(print_old_level) {
988
    ret.push_back("--" + ARG_PRINT_OLD_LEVELS);
989 990 991 992
  }
  return ret;
}

993 994 995 996 997 998
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");
999 1000
}

1001 1002
Options ReduceDBLevelsCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1003
  opt.num_levels = old_levels_;
1004
  opt.max_bytes_for_level_multiplier_additional.resize(opt.num_levels, 1);
1005
  // Disable size compaction
1006
  opt.max_bytes_for_level_base = 1UL << 50;
1007 1008
  opt.max_bytes_for_level_multiplier = 1;
  opt.max_mem_compaction_level = 0;
1009 1010 1011
  return opt;
}

1012
Status ReduceDBLevelsCommand::GetOldNumOfLevels(Options& opt,
1013
    int* levels) {
H
Haobo Xu 已提交
1014
  EnvOptions soptions;
1015
  TableCache tc(db_path_, &opt, soptions, 10);
1016
  const InternalKeyComparator cmp(opt.comparator);
1017
  VersionSet versions(db_path_, &opt, soptions, &tc, &cmp);
1018 1019 1020
  // 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.
1021
  Status st = versions.Recover();
1022 1023 1024 1025
  if (!st.ok()) {
    return st;
  }
  int max = -1;
1026
  for (int i = 0; i < versions.NumberLevels(); i++) {
1027
    if (versions.current()->NumLevelFiles(i)) {
1028 1029 1030 1031 1032 1033 1034 1035
      max = i;
    }
  }

  *levels = max + 1;
  return st;
}

1036
void ReduceDBLevelsCommand::DoCommand() {
1037 1038 1039 1040 1041 1042
  if (new_levels_ <= 1) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
        "Invalid number of levels.\n");
    return;
  }

1043 1044
  Status st;
  Options opt = PrepareOptionsForOpenDB();
1045 1046 1047 1048 1049 1050 1051
  int old_level_num = -1;
  st = GetOldNumOfLevels(opt, &old_level_num);
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
    return;
  }

1052
  if (print_old_levels_) {
1053 1054
    fprintf(stdout, "The old number of levels in use is %d\n", old_level_num);
  }
1055

1056 1057
  if (old_level_num <= new_levels_) {
    return;
1058 1059
  }

1060 1061 1062
  old_levels_ = old_level_num;

  OpenDB();
1063 1064 1065
  if (!db_) {
    return;
  }
1066
  // Compact the whole DB to put all files to the highest level.
1067
  fprintf(stdout, "Compacting the db...\n");
1068
  db_->CompactRange(nullptr, nullptr);
1069 1070
  CloseDB();

H
Haobo Xu 已提交
1071
  EnvOptions soptions;
1072
  TableCache tc(db_path_, &opt, soptions, 10);
1073
  const InternalKeyComparator cmp(opt.comparator);
1074
  VersionSet versions(db_path_, &opt, soptions, &tc, &cmp);
1075 1076 1077
  // 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.
1078
  st = versions.Recover();
1079 1080 1081 1082 1083 1084 1085
  if (!st.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
    return;
  }

  port::Mutex mu;
  mu.Lock();
1086
  st = versions.ReduceNumberOfLevels(new_levels_, &mu);
1087 1088 1089 1090 1091 1092 1093 1094
  mu.Unlock();

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

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 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 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
const string ChangeCompactionStyleCommand::ARG_OLD_COMPACTION_STYLE =
  "old_compaction_style";
const string ChangeCompactionStyleCommand::ARG_NEW_COMPACTION_STYLE =
  "new_compaction_style";

ChangeCompactionStyleCommand::ChangeCompactionStyleCommand(
      const vector<string>& params, const map<string, string>& options,
      const vector<string>& flags) :
    LDBCommand(options, flags, false,
               BuildCmdLineOptions({ARG_OLD_COMPACTION_STYLE,
                                    ARG_NEW_COMPACTION_STYLE})),
    old_compaction_style_(-1),
    new_compaction_style_(-1) {

  ParseIntOption(option_map_, ARG_OLD_COMPACTION_STYLE, old_compaction_style_,
    exec_state_);
  if (old_compaction_style_ != kCompactionStyleLevel &&
     old_compaction_style_ != kCompactionStyleUniversal) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
      "Use --" + ARG_OLD_COMPACTION_STYLE + " to specify old compaction " +
      "style. Check ldb help for proper compaction style value.\n");
    return;
  }

  ParseIntOption(option_map_, ARG_NEW_COMPACTION_STYLE, new_compaction_style_,
    exec_state_);
  if (new_compaction_style_ != kCompactionStyleLevel &&
     new_compaction_style_ != kCompactionStyleUniversal) {
    exec_state_ = LDBCommandExecuteResult::FAILED(
      "Use --" + ARG_NEW_COMPACTION_STYLE + " to specify new compaction " +
      "style. Check ldb help for proper compaction style value.\n");
    return;
  }

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

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

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

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++) {
1177
    db_->GetProperty("rocksdb.num-files-at-level" + NumberToString(i),
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
                     &property);

    // format print string
    char buf[100];
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
    files_per_level += buf;
  }
  fprintf(stdout, "files per level before compaction: %s\n",
          files_per_level.c_str());

  // manual compact into a single file and move the file to level 0
  db_->CompactRange(nullptr, nullptr,
                    true /* reduce level */,
                    0    /* reduce to level 0 */);

  // verify compaction result
  files_per_level = "";
  int num_files = 0;
  for (int i = 0; i < db_->NumberLevels(); i++) {
1197
    db_->GetProperty("rocksdb.num-files-at-level" + NumberToString(i),
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
                     &property);

    // format print string
    char buf[100];
    snprintf(buf, sizeof(buf), "%s%s", (i ? "," : ""), property.c_str());
    files_per_level += buf;

    num_files = atoi(property.c_str());

    // level 0 should have only 1 file
    if (i == 0 && num_files != 1) {
      exec_state_ = LDBCommandExecuteResult::FAILED("Number of db files at "
        "level 0 after compaction is " + std::to_string(num_files) +
        ", not 1.\n");
      return;
    }
    // other levels should have no file
    if (i > 0 && num_files != 0) {
      exec_state_ = LDBCommandExecuteResult::FAILED("Number of db files at "
        "level " + std::to_string(i) + " after compaction is " +
        std::to_string(num_files) + ", not 0.\n");
      return;
    }
  }

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

1227 1228
class InMemoryHandler : public WriteBatch::Handler {
 public:
1229 1230 1231
  InMemoryHandler(stringstream& row, bool print_values) : Handler(),row_(row) {
    print_values_ = print_values;
  }
1232

1233 1234 1235 1236 1237 1238 1239 1240 1241
  void commonPutMerge(const Slice& key, const Slice& value) {
    string k = LDBCommand::StringToHex(key.ToString());
    if (print_values_) {
      string v = LDBCommand::StringToHex(value.ToString());
      row_ << k << " : ";
      row_ << v << " ";
    } else {
      row_ << k << " ";
    }
1242
  }
1243 1244 1245 1246

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

1249 1250 1251
  virtual void Merge(const Slice& key, const Slice& value) {
    row_ << "MERGE : ";
    commonPutMerge(key, value);
1252
  }
1253 1254 1255 1256

  virtual void Delete(const Slice& key) {
    row_ <<",DELETE : ";
    row_ << LDBCommand::StringToHex(key.ToString()) << " ";
1257 1258
  }

1259 1260
  virtual ~InMemoryHandler() { };

1261
 private:
1262 1263
  stringstream & row_;
  bool print_values_;
1264 1265
};

1266
const string WALDumperCommand::ARG_WAL_FILE = "walfile";
1267
const string WALDumperCommand::ARG_PRINT_VALUE = "print_value";
1268 1269 1270 1271 1272
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,
1273 1274 1275
               BuildCmdLineOptions(
                {ARG_WAL_FILE, ARG_PRINT_HEADER, ARG_PRINT_VALUE})),
    print_header_(false), print_values_(false) {
1276

A
Abhishek Kona 已提交
1277
  wal_file_.clear();
1278 1279 1280 1281

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


1285 1286
  print_header_ = IsFlagPresent(flags, ARG_PRINT_HEADER);
  print_values_ = IsFlagPresent(flags, ARG_PRINT_VALUE);
A
Abhishek Kona 已提交
1287
  if (wal_file_.empty()) {
1288 1289
    exec_state_ = LDBCommandExecuteResult::FAILED(
                    "Argument " + ARG_WAL_FILE + " must be specified.");
A
Abhishek Kona 已提交
1290 1291 1292
  }
}

1293 1294 1295 1296
void WALDumperCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(WALDumperCommand::Name());
  ret.append(" --" + ARG_WAL_FILE + "=<write_ahead_log_file_path>");
1297 1298
  ret.append(" [--" + ARG_PRINT_HEADER + "] ");
  ret.append(" [--" + ARG_PRINT_VALUE + "] ");
1299
  ret.append("\n");
A
Abhishek Kona 已提交
1300 1301
}

1302
void WALDumperCommand::DoCommand() {
A
Abhishek Kona 已提交
1303 1304
  struct StdErrReporter : public log::Reader::Reporter {
    virtual void Corruption(size_t bytes, const Status& s) {
M
Mayank Agarwal 已提交
1305
      cerr<<"Corruption detected in log file "<<s.ToString()<<"\n";
A
Abhishek Kona 已提交
1306 1307 1308
    }
  };

1309
  unique_ptr<SequentialFile> file;
A
Abhishek Kona 已提交
1310
  Env* env_ = Env::Default();
H
Haobo Xu 已提交
1311
  EnvOptions soptions;
1312
  Status status = env_->NewSequentialFile(wal_file_, &file, soptions);
A
Abhishek Kona 已提交
1313 1314 1315 1316 1317
  if (!status.ok()) {
    exec_state_ = LDBCommandExecuteResult::FAILED("Failed to open WAL file " +
      status.ToString());
  } else {
    StdErrReporter reporter;
M
Mayank Agarwal 已提交
1318
    log::Reader reader(move(file), &reporter, true, 0);
1319
    string scratch;
A
Abhishek Kona 已提交
1320 1321
    WriteBatch batch;
    Slice record;
M
Mayank Agarwal 已提交
1322
    stringstream row;
A
Abhishek Kona 已提交
1323
    if (print_header_) {
M
Mayank Agarwal 已提交
1324
      cout<<"Sequence,Count,ByteSize,Physical Offset,Key(s)";
1325
      if (print_values_) {
M
Mayank Agarwal 已提交
1326
        cout << " : value ";
1327
      }
M
Mayank Agarwal 已提交
1328
      cout << "\n";
A
Abhishek Kona 已提交
1329 1330
    }
    while(reader.ReadRecord(&record, &scratch)) {
1331
      row.str("");
A
Abhishek Kona 已提交
1332 1333 1334 1335 1336 1337 1338
      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)<<",";
1339
        row<<WriteBatchInternal::ByteSize(&batch)<<",";
1340
        row<<reader.LastRecordOffset()<<",";
1341
        InMemoryHandler handler(row, print_values_);
1342 1343
        batch.Iterate(&handler);
        row<<"\n";
A
Abhishek Kona 已提交
1344
      }
M
Mayank Agarwal 已提交
1345
      cout<<row.str();
A
Abhishek Kona 已提交
1346 1347 1348 1349
    }
  }
}

1350 1351 1352

GetCommand::GetCommand(const vector<string>& params,
      const map<string, string>& options, const vector<string>& flags) :
1353 1354 1355
  LDBCommand(options, flags, true, BuildCmdLineOptions({ARG_TTL, ARG_HEX,
                                                        ARG_KEY_HEX,
                                                        ARG_VALUE_HEX})) {
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372

  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>");
1373
  ret.append(" [--" + ARG_TTL + "]");
1374 1375 1376 1377 1378
  ret.append("\n");
}

void GetCommand::DoCommand() {
  string value;
1379
  Status st = db_->Get(ReadOptions(), key_, &value);
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
  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() {

1426 1427
  Range ranges[1];
  ranges[0] = Range(start_key_, end_key_);
1428 1429
  uint64_t sizes[1];
  db_->GetApproximateSizes(ranges, 1, sizes);
K
Kai Liu 已提交
1430
  fprintf(stdout, "%lu\n", (unsigned long)sizes[0]);
1431
  /* Weird that GetApproximateSizes() returns void, although documentation
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
   * 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,
1443
             BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
                                  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 已提交
1456
      key_values_.push_back(pair<string, string>(
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
                    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>] [..]");
1467
  ret.append(" [--" + ARG_TTL + "]");
1468 1469 1470 1471
  ret.append("\n");
}

void BatchPutCommand::DoCommand() {
1472
  WriteBatch batch;
1473

M
Mayank Agarwal 已提交
1474
  for (vector<pair<string, string>>::const_iterator itr
1475 1476 1477
        = key_values_.begin(); itr != key_values_.end(); itr++) {
      batch.Put(itr->first, itr->second);
  }
1478
  Status st = db_->Write(WriteOptions(), &batch);
1479 1480 1481 1482 1483 1484 1485
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}

1486 1487
Options BatchPutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1488 1489 1490 1491 1492 1493 1494 1495
  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,
1496 1497 1498
               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})),
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    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 已提交
1523 1524
      max_keys_scanned_ = stoi(itr->second);
    } catch(const invalid_argument&) {
1525 1526
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has an invalid value");
M
Mayank Agarwal 已提交
1527 1528 1529
    } catch(const out_of_range&) {
      exec_state_ = LDBCommandExecuteResult::FAILED(ARG_MAX_KEYS +
                        " has a value out-of-range");
1530 1531 1532 1533 1534 1535 1536 1537
    }
  }
}

void ScanCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(ScanCommand::Name());
  ret.append(HelpRangeCmdArgs());
1538 1539 1540
  ret.append(" [--" + ARG_TTL + "]");
  ret.append(" [--" + ARG_TIMESTAMP + "]");
  ret.append(" [--" + ARG_MAX_KEYS + "=<N>q] ");
1541 1542
  ret.append(" [--" + ARG_TTL_START + "=<N>:- is inclusive]");
  ret.append(" [--" + ARG_TTL_END + "=<N>:- is exclusive]");
1543 1544 1545 1546 1547 1548
  ret.append("\n");
}

void ScanCommand::DoCommand() {

  int num_keys_scanned = 0;
1549
  Iterator* it = db_->NewIterator(ReadOptions());
1550 1551 1552 1553 1554
  if (start_key_specified_) {
    it->Seek(start_key_);
  } else {
    it->SeekToFirst();
  }
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
  int ttl_start;
  if (!ParseIntOption(option_map_, ARG_TTL_START, ttl_start, exec_state_)) {
    ttl_start = DBWithTTL::kMinTimestamp; // TTL introduction time
  }
  int ttl_end;
  if (!ParseIntOption(option_map_, ARG_TTL_END, ttl_end, exec_state_)) {
    ttl_end = DBWithTTL::kMaxTimestamp; // Max time allowed by TTL feature
  }
  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());
  }
1572 1573 1574 1575
  for ( ;
        it->Valid() && (!end_key_specified_ || it->key().ToString() < end_key_);
        it->Next()) {
    string key = it->key().ToString();
1576
    if (is_db_ttl_) {
1577 1578
      TtlIterator* it_ttl = dynamic_cast<TtlIterator*>(it);
      assert(it_ttl);
1579 1580
      int rawtime = it_ttl->timestamp();
      if (rawtime < ttl_start || rawtime >= ttl_end) {
1581 1582 1583 1584 1585 1586
        continue;
      }
      if (timestamp_) {
        fprintf(stdout, "%s ", ReadableTime(rawtime).c_str());
      }
    }
1587
    string value = it->value().ToString();
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    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() {
1627
  Status st = db_->Delete(WriteOptions(), key_);
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
  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,
1639
             BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX, ARG_VALUE_HEX,
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
                                  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> ");
1663
  ret.append(" [--" + ARG_TTL + "]");
1664 1665 1666 1667
  ret.append("\n");
}

void PutCommand::DoCommand() {
1668
  Status st = db_->Put(WriteOptions(), key_, value_);
1669 1670 1671 1672 1673 1674 1675
  if (st.ok()) {
    fprintf(stdout, "OK\n");
  } else {
    exec_state_ = LDBCommandExecuteResult::FAILED(st.ToString());
  }
}

1676 1677
Options PutCommand::PrepareOptionsForOpenDB() {
  Options opt = LDBCommand::PrepareOptionsForOpenDB();
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
  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,
1691 1692
             BuildCmdLineOptions({ARG_TTL, ARG_HEX, ARG_KEY_HEX,
                                  ARG_VALUE_HEX})) {
1693 1694 1695 1696 1697 1698

}

void DBQuerierCommand::Help(string& ret) {
  ret.append("  ");
  ret.append(DBQuerierCommand::Name());
1699
  ret.append(" [--" + ARG_TTL + "]");
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
  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;
  }

1711 1712
  ReadOptions read_options;
  WriteOptions write_options;
1713 1714 1715 1716

  string line;
  string key;
  string value;
M
Mayank Agarwal 已提交
1717
  while (getline(cin, line, '\n')) {
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763

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


1764
}