internal_stats.cc 36.2 KB
Newer Older
I
Igor Canadi 已提交
1 2 3 4 5 6 7 8 9
//  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.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/internal_stats.h"
L
liuhuahang 已提交
10 11

#ifndef __STDC_FORMAT_MACROS
I
Igor Canadi 已提交
12
#define __STDC_FORMAT_MACROS
L
liuhuahang 已提交
13 14
#endif

I
Igor Canadi 已提交
15
#include <inttypes.h>
16
#include <string>
17
#include <algorithm>
18
#include <utility>
I
Igor Canadi 已提交
19
#include <vector>
20
#include "db/column_family.h"
21

22
#include "db/db_impl.h"
23
#include "util/string_util.h"
I
Igor Canadi 已提交
24 25 26

namespace rocksdb {

27
#ifndef ROCKSDB_LITE
L
Lei Jin 已提交
28 29 30
namespace {
const double kMB = 1048576.0;
const double kGB = kMB * 1024;
31
const double kMicrosInSec = 1000000.0;
L
Lei Jin 已提交
32

33
void PrintLevelStatsHeader(char* buf, size_t len, const std::string& cf_name) {
L
Lei Jin 已提交
34 35
  snprintf(
      buf, len,
36
      "\n** Compaction Stats [%s] **\n"
37
      "Level    Files   Size(MB) Score Read(GB)  Rn(GB) Rnp1(GB) "
38
      "Write(GB) Wnew(GB) Moved(GB) W-Amp Rd(MB/s) Wr(MB/s) "
39
      "Comp(sec) Comp(cnt) Avg(sec) KeyIn KeyDrop\n"
L
Lei Jin 已提交
40
      "--------------------------------------------------------------------"
41
      "-----------------------------------------------------------"
42
      "--------------------------------------\n",
43
      cf_name.c_str());
L
Lei Jin 已提交
44 45 46
}

void PrintLevelStats(char* buf, size_t len, const std::string& name,
47 48 49
  int num_files, int being_compacted, double total_file_size,
  double score, double w_amp,
  const InternalStats::CompactionStats& stats) {
50 51 52 53
  uint64_t bytes_read =
      stats.bytes_read_non_output_levels + stats.bytes_read_output_level;
  int64_t bytes_new =
      stats.bytes_written - stats.bytes_read_output_level;
54
  double elapsed = (stats.micros + 1) / kMicrosInSec;
55 56 57
  std::string num_input_records = NumberToHumanString(stats.num_input_records);
  std::string num_dropped_records =
      NumberToHumanString(stats.num_dropped_records);
L
Lei Jin 已提交
58 59

  snprintf(buf, len,
A
Andres Noetzli 已提交
60
           "%4s %6d/%-3d %8.2f %5.1f " /* Level, Files, Size(MB), Score */
S
sdong 已提交
61 62 63 64 65
           "%8.1f "                    /* Read(GB) */
           "%7.1f "                    /* Rn(GB) */
           "%8.1f "                    /* Rnp1(GB) */
           "%9.1f "                    /* Write(GB) */
           "%8.1f "                    /* Wnew(GB) */
66
           "%9.1f "                    /* Moved(GB) */
S
sdong 已提交
67 68 69
           "%5.1f "                    /* W-Amp */
           "%8.1f "                    /* Rd(MB/s) */
           "%8.1f "                    /* Wr(MB/s) */
70
           "%9.0f "                    /* Comp(sec) */
S
sdong 已提交
71 72
           "%9d "                      /* Comp(cnt) */
           "%8.3f "                    /* Avg(sec) */
73 74
           "%7s "   /* KeyIn */
           "%6s\n", /* KeyDrop */
75 76 77
           name.c_str(),
           num_files, being_compacted, total_file_size / kMB, score,
           bytes_read / kGB, stats.bytes_read_non_output_levels / kGB,
78
           stats.bytes_read_output_level / kGB, stats.bytes_written / kGB,
79 80 81 82
           bytes_new / kGB, stats.bytes_moved / kGB, w_amp,
           bytes_read / kMB / elapsed, stats.bytes_written / kMB / elapsed,
           stats.micros / kMicrosInSec, stats.count,
           stats.count == 0 ? 0 : stats.micros / kMicrosInSec / stats.count,
83
           num_input_records.c_str(), num_dropped_records.c_str());
L
Lei Jin 已提交
84
}
85 86 87 88 89 90 91 92 93 94 95 96 97

// Assumes that trailing numbers represent an optional argument. This requires
// property names to not end with numbers.
std::pair<Slice, Slice> GetPropertyNameAndArg(const Slice& property) {
  Slice name = property, arg = property;
  size_t sfx_len = 0;
  while (sfx_len < property.size() &&
         isdigit(property[property.size() - sfx_len - 1])) {
    ++sfx_len;
  }
  name.remove_suffix(sfx_len);
  arg.remove_prefix(property.size() - sfx_len);
  return {name, arg};
L
Lei Jin 已提交
98
}
99
}  // anonymous namespace
L
Lei Jin 已提交
100

101 102 103
static const std::string rocksdb_prefix = "rocksdb.";

static const std::string num_files_at_level_prefix = "num-files-at-level";
104
static const std::string allstats = "stats";
105 106 107 108 109
static const std::string sstables = "sstables";
static const std::string cfstats = "cfstats";
static const std::string dbstats = "dbstats";
static const std::string levelstats = "levelstats";
static const std::string num_immutable_mem_table = "num-immutable-mem-table";
110 111
static const std::string num_immutable_mem_table_flushed =
    "num-immutable-mem-table-flushed";
112 113 114 115 116
static const std::string mem_table_flush_pending = "mem-table-flush-pending";
static const std::string compaction_pending = "compaction-pending";
static const std::string background_errors = "background-errors";
static const std::string cur_size_active_mem_table =
                          "cur-size-active-mem-table";
117 118
static const std::string cur_size_all_mem_tables = "cur-size-all-mem-tables";
static const std::string size_all_mem_tables = "size-all-mem-tables";
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
static const std::string num_entries_active_mem_table =
                          "num-entries-active-mem-table";
static const std::string num_entries_imm_mem_tables =
                          "num-entries-imm-mem-tables";
static const std::string num_deletes_active_mem_table =
                          "num-deletes-active-mem-table";
static const std::string num_deletes_imm_mem_tables =
                          "num-deletes-imm-mem-tables";
static const std::string estimate_num_keys = "estimate-num-keys";
static const std::string estimate_table_readers_mem =
                          "estimate-table-readers-mem";
static const std::string is_file_deletions_enabled =
                          "is-file-deletions-enabled";
static const std::string num_snapshots = "num-snapshots";
static const std::string oldest_snapshot_time = "oldest-snapshot-time";
static const std::string num_live_versions = "num-live-versions";
135 136
static const std::string current_version_number =
    "current-super-version-number";
A
Andres Notzli 已提交
137
static const std::string estimate_live_data_size = "estimate-live-data-size";
138
static const std::string base_level = "base-level";
139
static const std::string total_sst_files_size = "total-sst-files-size";
140 141
static const std::string estimate_pending_comp_bytes =
    "estimate-pending-compaction-bytes";
142 143 144 145
static const std::string aggregated_table_properties =
    "aggregated-table-properties";
static const std::string aggregated_table_properties_at_level =
    aggregated_table_properties + "-at-level";
146 147
static const std::string num_running_compactions = "num-running-compactions";
static const std::string num_running_flushes = "num-running-flushes";
148 149 150

const std::string DB::Properties::kNumFilesAtLevelPrefix =
                      rocksdb_prefix + num_files_at_level_prefix;
151
const std::string DB::Properties::kStats = rocksdb_prefix + allstats;
152 153 154
const std::string DB::Properties::kSSTables = rocksdb_prefix + sstables;
const std::string DB::Properties::kCFStats = rocksdb_prefix + cfstats;
const std::string DB::Properties::kDBStats = rocksdb_prefix + dbstats;
155
const std::string DB::Properties::kLevelStats = rocksdb_prefix + levelstats;
156 157
const std::string DB::Properties::kNumImmutableMemTable =
                      rocksdb_prefix + num_immutable_mem_table;
158
const std::string DB::Properties::kNumImmutableMemTableFlushed =
159
    rocksdb_prefix + num_immutable_mem_table_flushed;
160 161 162 163
const std::string DB::Properties::kMemTableFlushPending =
                      rocksdb_prefix + mem_table_flush_pending;
const std::string DB::Properties::kCompactionPending =
                      rocksdb_prefix + compaction_pending;
164 165 166 167
const std::string DB::Properties::kNumRunningCompactions =
    rocksdb_prefix + num_running_compactions;
const std::string DB::Properties::kNumRunningFlushes =
    rocksdb_prefix + num_running_flushes;
168 169 170 171 172
const std::string DB::Properties::kBackgroundErrors =
                      rocksdb_prefix + background_errors;
const std::string DB::Properties::kCurSizeActiveMemTable =
                      rocksdb_prefix + cur_size_active_mem_table;
const std::string DB::Properties::kCurSizeAllMemTables =
173
    rocksdb_prefix + cur_size_all_mem_tables;
174 175
const std::string DB::Properties::kSizeAllMemTables =
    rocksdb_prefix + size_all_mem_tables;
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
const std::string DB::Properties::kNumEntriesActiveMemTable =
                      rocksdb_prefix + num_entries_active_mem_table;
const std::string DB::Properties::kNumEntriesImmMemTables =
                      rocksdb_prefix + num_entries_imm_mem_tables;
const std::string DB::Properties::kNumDeletesActiveMemTable =
                      rocksdb_prefix + num_deletes_active_mem_table;
const std::string DB::Properties::kNumDeletesImmMemTables =
                      rocksdb_prefix + num_deletes_imm_mem_tables;
const std::string DB::Properties::kEstimateNumKeys =
                      rocksdb_prefix + estimate_num_keys;
const std::string DB::Properties::kEstimateTableReadersMem =
                      rocksdb_prefix + estimate_table_readers_mem;
const std::string DB::Properties::kIsFileDeletionsEnabled =
                      rocksdb_prefix + is_file_deletions_enabled;
const std::string DB::Properties::kNumSnapshots =
                      rocksdb_prefix + num_snapshots;
const std::string DB::Properties::kOldestSnapshotTime =
                      rocksdb_prefix + oldest_snapshot_time;
const std::string DB::Properties::kNumLiveVersions =
                      rocksdb_prefix + num_live_versions;
196
const std::string DB::Properties::kCurrentSuperVersionNumber =
197
    rocksdb_prefix + current_version_number;
A
Andres Notzli 已提交
198 199
const std::string DB::Properties::kEstimateLiveDataSize =
                      rocksdb_prefix + estimate_live_data_size;
200 201
const std::string DB::Properties::kTotalSstFilesSize =
                      rocksdb_prefix + total_sst_files_size;
202
const std::string DB::Properties::kBaseLevel = rocksdb_prefix + base_level;
203 204
const std::string DB::Properties::kEstimatePendingCompactionBytes =
    rocksdb_prefix + estimate_pending_comp_bytes;
205 206 207 208
const std::string DB::Properties::kAggregatedTableProperties =
    rocksdb_prefix + aggregated_table_properties;
const std::string DB::Properties::kAggregatedTablePropertiesAtLevel =
    rocksdb_prefix + aggregated_table_properties_at_level;
209

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
const std::unordered_map<std::string,
                         DBPropertyInfo> InternalStats::ppt_name_to_info = {
    {DB::Properties::kNumFilesAtLevelPrefix,
     {false, &InternalStats::HandleNumFilesAtLevel, nullptr}},
    {DB::Properties::kLevelStats,
     {false, &InternalStats::HandleLevelStats, nullptr}},
    {DB::Properties::kStats, {false, &InternalStats::HandleStats, nullptr}},
    {DB::Properties::kCFStats, {false, &InternalStats::HandleCFStats, nullptr}},
    {DB::Properties::kDBStats, {false, &InternalStats::HandleDBStats, nullptr}},
    {DB::Properties::kSSTables,
     {false, &InternalStats::HandleSsTables, nullptr}},
    {DB::Properties::kAggregatedTableProperties,
     {false, &InternalStats::HandleAggregatedTableProperties, nullptr}},
    {DB::Properties::kAggregatedTablePropertiesAtLevel,
     {false, &InternalStats::HandleAggregatedTablePropertiesAtLevel, nullptr}},
    {DB::Properties::kNumImmutableMemTable,
     {false, nullptr, &InternalStats::HandleNumImmutableMemTable}},
    {DB::Properties::kNumImmutableMemTableFlushed,
     {false, nullptr, &InternalStats::HandleNumImmutableMemTableFlushed}},
    {DB::Properties::kMemTableFlushPending,
     {false, nullptr, &InternalStats::HandleMemTableFlushPending}},
    {DB::Properties::kCompactionPending,
     {false, nullptr, &InternalStats::HandleCompactionPending}},
    {DB::Properties::kBackgroundErrors,
     {false, nullptr, &InternalStats::HandleBackgroundErrors}},
    {DB::Properties::kCurSizeActiveMemTable,
     {false, nullptr, &InternalStats::HandleCurSizeActiveMemTable}},
    {DB::Properties::kCurSizeAllMemTables,
     {false, nullptr, &InternalStats::HandleCurSizeAllMemTables}},
    {DB::Properties::kSizeAllMemTables,
     {false, nullptr, &InternalStats::HandleSizeAllMemTables}},
    {DB::Properties::kNumEntriesActiveMemTable,
     {false, nullptr, &InternalStats::HandleNumEntriesActiveMemTable}},
    {DB::Properties::kNumEntriesImmMemTables,
     {false, nullptr, &InternalStats::HandleNumEntriesImmMemTables}},
    {DB::Properties::kNumDeletesActiveMemTable,
     {false, nullptr, &InternalStats::HandleNumDeletesActiveMemTable}},
    {DB::Properties::kNumDeletesImmMemTables,
     {false, nullptr, &InternalStats::HandleNumDeletesImmMemTables}},
    {DB::Properties::kEstimateNumKeys,
     {false, nullptr, &InternalStats::HandleEstimateNumKeys}},
    {DB::Properties::kEstimateTableReadersMem,
     {true, nullptr, &InternalStats::HandleEstimateTableReadersMem}},
    {DB::Properties::kIsFileDeletionsEnabled,
     {false, nullptr, &InternalStats::HandleIsFileDeletionsEnabled}},
    {DB::Properties::kNumSnapshots,
     {false, nullptr, &InternalStats::HandleNumSnapshots}},
    {DB::Properties::kOldestSnapshotTime,
     {false, nullptr, &InternalStats::HandleOldestSnapshotTime}},
    {DB::Properties::kNumLiveVersions,
     {false, nullptr, &InternalStats::HandleNumLiveVersions}},
261 262
    {DB::Properties::kCurrentSuperVersionNumber,
     {false, nullptr, &InternalStats::HandleCurrentSuperVersionNumber}},
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    {DB::Properties::kEstimateLiveDataSize,
     {true, nullptr, &InternalStats::HandleEstimateLiveDataSize}},
    {DB::Properties::kBaseLevel,
     {false, nullptr, &InternalStats::HandleBaseLevel}},
    {DB::Properties::kTotalSstFilesSize,
     {false, nullptr, &InternalStats::HandleTotalSstFilesSize}},
    {DB::Properties::kEstimatePendingCompactionBytes,
     {false, nullptr, &InternalStats::HandleEstimatePendingCompactionBytes}},
    {DB::Properties::kNumRunningFlushes,
     {false, nullptr, &InternalStats::HandleNumRunningFlushes}},
    {DB::Properties::kNumRunningCompactions,
     {false, nullptr, &InternalStats::HandleNumRunningCompactions}},
};

const DBPropertyInfo* GetPropertyInfo(const Slice& property) {
  std::string ppt_name = GetPropertyNameAndArg(property).first.ToString();
  auto ppt_info_iter = InternalStats::ppt_name_to_info.find(ppt_name);
  if (ppt_info_iter == InternalStats::ppt_name_to_info.end()) {
    return nullptr;
282
  }
283 284
  return &ppt_info_iter->second;
}
285

286 287 288 289 290 291 292
bool InternalStats::GetStringProperty(const DBPropertyInfo& property_info,
                                      const Slice& property,
                                      std::string* value) {
  assert(value != nullptr);
  assert(property_info.handle_string != nullptr);
  Slice arg = GetPropertyNameAndArg(property).second;
  return (this->*(property_info.handle_string))(value, arg);
293 294
}

295 296
bool InternalStats::GetIntProperty(const DBPropertyInfo& property_info,
                                   uint64_t* value, DBImpl* db) {
297
  assert(value != nullptr);
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  assert(property_info.handle_int != nullptr &&
         !property_info.need_out_of_mutex);
  db->mutex_.AssertHeld();
  return (this->*(property_info.handle_int))(value, db, nullptr /* version */);
}

bool InternalStats::GetIntPropertyOutOfMutex(
    const DBPropertyInfo& property_info, Version* version, uint64_t* value) {
  assert(value != nullptr);
  assert(property_info.handle_int != nullptr &&
         property_info.need_out_of_mutex);
  return (this->*(property_info.handle_int))(value, nullptr /* db */, version);
}

bool InternalStats::HandleNumFilesAtLevel(std::string* value, Slice suffix) {
  uint64_t level;
A
Andres Notzli 已提交
314
  const auto* vstorage = cfd_->current()->storage_info();
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  bool ok = ConsumeDecimalNumber(&suffix, &level) && suffix.empty();
  if (!ok || static_cast<int>(level) >= number_levels_) {
    return false;
  } else {
    char buf[100];
    snprintf(buf, sizeof(buf), "%d",
             vstorage->NumLevelFiles(static_cast<int>(level)));
    *value = buf;
    return true;
  }
}

bool InternalStats::HandleLevelStats(std::string* value, Slice suffix) {
  char buf[1000];
  const auto* vstorage = cfd_->current()->storage_info();
  snprintf(buf, sizeof(buf),
           "Level Files Size(MB)\n"
           "--------------------\n");
  value->append(buf);
A
Andres Notzli 已提交
334

335 336 337 338 339
  for (int level = 0; level < number_levels_; level++) {
    snprintf(buf, sizeof(buf), "%3d %8d %8.0f\n", level,
             vstorage->NumLevelFiles(level),
             vstorage->NumLevelBytes(level) / kMB);
    value->append(buf);
340
  }
341
  return true;
342
}
343

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
bool InternalStats::HandleStats(std::string* value, Slice suffix) {
  if (!HandleCFStats(value, suffix)) {
    return false;
  }
  if (!HandleDBStats(value, suffix)) {
    return false;
  }
  return true;
}

bool InternalStats::HandleCFStats(std::string* value, Slice suffix) {
  DumpCFStats(value);
  return true;
}

bool InternalStats::HandleDBStats(std::string* value, Slice suffix) {
  DumpDBStats(value);
  return true;
}

bool InternalStats::HandleSsTables(std::string* value, Slice suffix) {
S
sdong 已提交
365
  auto* current = cfd_->current();
366 367 368
  *value = current->DebugString();
  return true;
}
I
Igor Canadi 已提交
369

370 371 372 373 374 375
bool InternalStats::HandleAggregatedTableProperties(std::string* value,
                                                    Slice suffix) {
  std::shared_ptr<const TableProperties> tp;
  auto s = cfd_->current()->GetAggregatedTableProperties(&tp);
  if (!s.ok()) {
    return false;
376
  }
377 378
  *value = tp->ToString();
  return true;
379 380
}

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
bool InternalStats::HandleAggregatedTablePropertiesAtLevel(std::string* value,
                                                           Slice suffix) {
  uint64_t level;
  bool ok = ConsumeDecimalNumber(&suffix, &level) && suffix.empty();
  if (!ok || static_cast<int>(level) >= number_levels_) {
    return false;
  }
  std::shared_ptr<const TableProperties> tp;
  auto s = cfd_->current()->GetAggregatedTableProperties(
      &tp, static_cast<int>(level));
  if (!s.ok()) {
    return false;
  }
  *value = tp->ToString();
  return true;
}

bool InternalStats::HandleNumImmutableMemTable(uint64_t* value, DBImpl* db,
                                               Version* version) {
  *value = cfd_->imm()->NumNotFlushed();
  return true;
}

bool InternalStats::HandleNumImmutableMemTableFlushed(uint64_t* value,
                                                      DBImpl* db,
                                                      Version* version) {
  *value = cfd_->imm()->NumFlushed();
  return true;
}

bool InternalStats::HandleMemTableFlushPending(uint64_t* value, DBImpl* db,
                                               Version* version) {
  // Return number of mem tables that are ready to flush (made immutable)
  *value = (cfd_->imm()->IsFlushPending() ? 1 : 0);
  return true;
}

bool InternalStats::HandleNumRunningFlushes(uint64_t* value, DBImpl* db,
                                            Version* version) {
  *value = db->num_running_flushes();
  return true;
}

bool InternalStats::HandleCompactionPending(uint64_t* value, DBImpl* db,
                                            Version* version) {
  // 1 if the system already determines at least one compaction is needed.
  // 0 otherwise,
S
sdong 已提交
428
  const auto* vstorage = cfd_->current()->storage_info();
429 430 431
  *value = (cfd_->compaction_picker()->NeedsCompaction(vstorage) ? 1 : 0);
  return true;
}
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
bool InternalStats::HandleNumRunningCompactions(uint64_t* value, DBImpl* db,
                                                Version* version) {
  *value = db->num_running_compactions_;
  return true;
}

bool InternalStats::HandleBackgroundErrors(uint64_t* value, DBImpl* db,
                                           Version* version) {
  // Accumulated number of  errors in background flushes or compactions.
  *value = GetBackgroundErrorCount();
  return true;
}

bool InternalStats::HandleCurSizeActiveMemTable(uint64_t* value, DBImpl* db,
                                                Version* version) {
  // Current size of the active memtable
  *value = cfd_->mem()->ApproximateMemoryUsage();
  return true;
}

bool InternalStats::HandleCurSizeAllMemTables(uint64_t* value, DBImpl* db,
                                              Version* version) {
  // Current size of the active memtable + immutable memtables
  *value = cfd_->mem()->ApproximateMemoryUsage() +
           cfd_->imm()->ApproximateUnflushedMemTablesMemoryUsage();
  return true;
}

bool InternalStats::HandleSizeAllMemTables(uint64_t* value, DBImpl* db,
                                           Version* version) {
  *value = cfd_->mem()->ApproximateMemoryUsage() +
           cfd_->imm()->ApproximateMemoryUsage();
  return true;
}

bool InternalStats::HandleNumEntriesActiveMemTable(uint64_t* value, DBImpl* db,
                                                   Version* version) {
  // Current number of entires in the active memtable
  *value = cfd_->mem()->num_entries();
  return true;
}

bool InternalStats::HandleNumEntriesImmMemTables(uint64_t* value, DBImpl* db,
                                                 Version* version) {
  // Current number of entries in the immutable memtables
  *value = cfd_->imm()->current()->GetTotalNumEntries();
  return true;
}

bool InternalStats::HandleNumDeletesActiveMemTable(uint64_t* value, DBImpl* db,
                                                   Version* version) {
  // Current number of entires in the active memtable
  *value = cfd_->mem()->num_deletes();
  return true;
}

bool InternalStats::HandleNumDeletesImmMemTables(uint64_t* value, DBImpl* db,
                                                 Version* version) {
  // Current number of entries in the immutable memtables
  *value = cfd_->imm()->current()->GetTotalNumDeletes();
  return true;
}

bool InternalStats::HandleEstimateNumKeys(uint64_t* value, DBImpl* db,
                                          Version* version) {
  // Estimate number of entries in the column family:
  // Use estimated entries in tables + total entries in memtables.
  const auto* vstorage = cfd_->current()->storage_info();
  *value = cfd_->mem()->num_entries() +
           cfd_->imm()->current()->GetTotalNumEntries() -
           (cfd_->mem()->num_deletes() +
            cfd_->imm()->current()->GetTotalNumDeletes()) *
               2 +
           vstorage->GetEstimatedActiveKeys();
  return true;
}

bool InternalStats::HandleNumSnapshots(uint64_t* value, DBImpl* db,
                                       Version* version) {
  *value = db->snapshots().count();
  return true;
}

bool InternalStats::HandleOldestSnapshotTime(uint64_t* value, DBImpl* db,
                                             Version* version) {
  *value = static_cast<uint64_t>(db->snapshots().GetOldestSnapshotTime());
  return true;
}

bool InternalStats::HandleNumLiveVersions(uint64_t* value, DBImpl* db,
                                          Version* version) {
  *value = cfd_->GetNumLiveVersions();
  return true;
}

528 529
bool InternalStats::HandleCurrentSuperVersionNumber(uint64_t* value, DBImpl* db,
                                                    Version* version) {
530 531 532 533
  *value = cfd_->GetSuperVersionNumber();
  return true;
}

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
bool InternalStats::HandleIsFileDeletionsEnabled(uint64_t* value, DBImpl* db,
                                                 Version* version) {
  *value = db->IsFileDeletionsEnabled();
  return true;
}

bool InternalStats::HandleBaseLevel(uint64_t* value, DBImpl* db,
                                    Version* version) {
  const auto* vstorage = cfd_->current()->storage_info();
  *value = vstorage->base_level();
  return true;
}

bool InternalStats::HandleTotalSstFilesSize(uint64_t* value, DBImpl* db,
                                            Version* version) {
  *value = cfd_->GetTotalSstFilesSize();
  return true;
}

bool InternalStats::HandleEstimatePendingCompactionBytes(uint64_t* value,
                                                         DBImpl* db,
                                                         Version* version) {
  const auto* vstorage = cfd_->current()->storage_info();
  *value = vstorage->estimated_compaction_needed_bytes();
  return true;
}

bool InternalStats::HandleEstimateTableReadersMem(uint64_t* value, DBImpl* db,
                                                  Version* version) {
  *value = (version == nullptr) ? 0 : version->GetMemoryUsageByTableReaders();
  return true;
}

bool InternalStats::HandleEstimateLiveDataSize(uint64_t* value, DBImpl* db,
                                               Version* version) {
  const auto* vstorage = cfd_->current()->storage_info();
  *value = vstorage->EstimateLiveDataSize();
  return true;
I
Igor Canadi 已提交
572 573
}

574 575 576
void InternalStats::DumpDBStats(std::string* value) {
  char buf[1000];
  // DB-level stats, only available from default column family
577
  double seconds_up = (env_->NowMicros() - started_at_ + 1) / kMicrosInSec;
578 579 580 581 582 583
  double interval_seconds_up = seconds_up - db_stats_snapshot_.seconds_up;
  snprintf(buf, sizeof(buf),
           "\n** DB Stats **\nUptime(secs): %.1f total, %.1f interval\n",
           seconds_up, interval_seconds_up);
  value->append(buf);
  // Cumulative
584 585 586 587 588 589 590 591
  uint64_t user_bytes_written = GetDBStats(InternalStats::BYTES_WRITTEN);
  uint64_t num_keys_written = GetDBStats(InternalStats::NUMBER_KEYS_WRITTEN);
  uint64_t write_other = GetDBStats(InternalStats::WRITE_DONE_BY_OTHER);
  uint64_t write_self = GetDBStats(InternalStats::WRITE_DONE_BY_SELF);
  uint64_t wal_bytes = GetDBStats(InternalStats::WAL_FILE_BYTES);
  uint64_t wal_synced = GetDBStats(InternalStats::WAL_FILE_SYNCED);
  uint64_t write_with_wal = GetDBStats(InternalStats::WRITE_WITH_WAL);
  uint64_t write_stall_micros = GetDBStats(InternalStats::WRITE_STALL_MICROS);
592 593 594 595
  uint64_t compact_bytes_read = 0;
  uint64_t compact_bytes_write = 0;
  uint64_t compact_micros = 0;

596 597 598
  const int kHumanMicrosLen = 32;
  char human_micros[kHumanMicrosLen];

599
  // Data
S
sdong 已提交
600 601 602 603 604 605 606 607
  // writes: total number of write requests.
  // keys: total number of key updates issued by all the write requests
  // batches: number of group commits issued to the DB. Each group can contain
  //          one or more writes.
  // so writes/keys is the average number of put in multi-put or put
  // writes/batches is the average group commit size.
  //
  // The format is the same for interval stats.
608
  snprintf(buf, sizeof(buf),
609 610 611 612 613
           "Cumulative writes: %s writes, %s keys, %s batches, "
           "%.1f writes per batch, ingest: %.2f GB, %.2f MB/s\n",
           NumberToHumanString(write_other + write_self).c_str(),
           NumberToHumanString(num_keys_written).c_str(),
           NumberToHumanString(write_self).c_str(),
614
           (write_other + write_self) / static_cast<double>(write_self + 1),
615
           user_bytes_written / kGB, user_bytes_written / kMB / seconds_up);
616 617 618
  value->append(buf);
  // WAL
  snprintf(buf, sizeof(buf),
619 620 621 622
           "Cumulative WAL: %s writes, %s syncs, "
           "%.2f writes per sync, written: %.2f GB, %.2f MB/s\n",
           NumberToHumanString(write_with_wal).c_str(),
           NumberToHumanString(wal_synced).c_str(),
623
           write_with_wal / static_cast<double>(wal_synced + 1),
624 625
           wal_bytes / kGB, wal_bytes / kMB / seconds_up);
  value->append(buf);
626 627
  // Compact
  for (int level = 0; level < number_levels_; level++) {
628 629
    compact_bytes_read += comp_stats_[level].bytes_read_output_level +
                          comp_stats_[level].bytes_read_non_output_levels;
630 631 632 633 634 635
    compact_bytes_write += comp_stats_[level].bytes_written;
    compact_micros += comp_stats_[level].micros;
  }
  snprintf(buf, sizeof(buf),
           "Cumulative compaction: %.2f GB write, %.2f MB/s write, "
           "%.2f GB read, %.2f MB/s read, %.1f seconds\n",
636 637 638
           compact_bytes_write / kGB, compact_bytes_write / kMB / seconds_up,
           compact_bytes_read / kGB, compact_bytes_read / kMB / seconds_up,
           compact_micros / kMicrosInSec);
639
  value->append(buf);
640 641 642 643 644 645 646
  // Stall
  AppendHumanMicros(write_stall_micros, human_micros, kHumanMicrosLen, true);
  snprintf(buf, sizeof(buf),
           "Cumulative stall: %s, %.1f percent\n",
           human_micros,
           // 10000 = divide by 1M to get secs, then multiply by 100 for pct
           write_stall_micros / 10000.0 / std::max(seconds_up, 0.001));
647 648 649 650 651
  value->append(buf);

  // Interval
  uint64_t interval_write_other = write_other - db_stats_snapshot_.write_other;
  uint64_t interval_write_self = write_self - db_stats_snapshot_.write_self;
S
sdong 已提交
652 653
  uint64_t interval_num_keys_written =
      num_keys_written - db_stats_snapshot_.num_keys_written;
654
  snprintf(buf, sizeof(buf),
655 656 657 658 659 660
           "Interval writes: %s writes, %s keys, %s batches, "
           "%.1f writes per batch, ingest: %.2f MB, %.2f MB/s\n",
           NumberToHumanString(
               interval_write_other + interval_write_self).c_str(),
           NumberToHumanString(interval_num_keys_written).c_str(),
           NumberToHumanString(interval_write_self).c_str(),
661 662
           static_cast<double>(interval_write_other + interval_write_self) /
               (interval_write_self + 1),
S
sdong 已提交
663
           (user_bytes_written - db_stats_snapshot_.ingest_bytes) / kMB,
664 665
           (user_bytes_written - db_stats_snapshot_.ingest_bytes) / kMB /
               std::max(interval_seconds_up, 0.001)),
666 667 668 669 670 671 672 673
  value->append(buf);

  uint64_t interval_write_with_wal =
      write_with_wal - db_stats_snapshot_.write_with_wal;
  uint64_t interval_wal_synced = wal_synced - db_stats_snapshot_.wal_synced;
  uint64_t interval_wal_bytes = wal_bytes - db_stats_snapshot_.wal_bytes;

  snprintf(buf, sizeof(buf),
674 675 676 677
           "Interval WAL: %s writes, %s syncs, "
           "%.2f writes per sync, written: %.2f MB, %.2f MB/s\n",
           NumberToHumanString(interval_write_with_wal).c_str(),
           NumberToHumanString(interval_wal_synced).c_str(),
678 679
           interval_write_with_wal /
              static_cast<double>(interval_wal_synced + 1),
680 681 682 683
           interval_wal_bytes / kGB,
           interval_wal_bytes / kMB / std::max(interval_seconds_up, 0.001));
  value->append(buf);

684 685 686 687 688 689 690 691
  // Compaction
  uint64_t interval_compact_bytes_write =
      compact_bytes_write - db_stats_snapshot_.compact_bytes_write;
  uint64_t interval_compact_bytes_read =
      compact_bytes_read - db_stats_snapshot_.compact_bytes_read;
  uint64_t interval_compact_micros =
      compact_micros - db_stats_snapshot_.compact_micros;

692 693 694 695 696 697 698 699 700
  snprintf(
      buf, sizeof(buf),
      "Interval compaction: %.2f GB write, %.2f MB/s write, "
      "%.2f GB read, %.2f MB/s read, %.1f seconds\n",
      interval_compact_bytes_write / kGB,
      interval_compact_bytes_write / kMB / std::max(interval_seconds_up, 0.001),
      interval_compact_bytes_read / kGB,
      interval_compact_bytes_read / kMB / std::max(interval_seconds_up, 0.001),
      interval_compact_micros / kMicrosInSec);
701 702
  value->append(buf);

703 704 705 706 707 708 709 710 711 712
  // Stall
  AppendHumanMicros(
      write_stall_micros - db_stats_snapshot_.write_stall_micros,
      human_micros, kHumanMicrosLen, true);
  snprintf(buf, sizeof(buf),
           "Interval stall: %s, %.1f percent\n",
           human_micros,
           // 10000 = divide by 1M to get secs, then multiply by 100 for pct
           (write_stall_micros - db_stats_snapshot_.write_stall_micros) /
               10000.0 / std::max(interval_seconds_up, 0.001));
713 714
  value->append(buf);

715 716 717 718 719 720 721 722 723 724
  for (int level = 0; level < number_levels_; level++) {
    if (!file_read_latency_[level].Empty()) {
      char buf2[5000];
      snprintf(buf2, sizeof(buf2),
               "** Level %d read latency histogram (micros):\n%s\n", level,
               file_read_latency_[level].ToString().c_str());
      value->append(buf2);
    }
  }

725 726 727 728
  db_stats_snapshot_.seconds_up = seconds_up;
  db_stats_snapshot_.ingest_bytes = user_bytes_written;
  db_stats_snapshot_.write_other = write_other;
  db_stats_snapshot_.write_self = write_self;
S
sdong 已提交
729
  db_stats_snapshot_.num_keys_written = num_keys_written;
730 731 732
  db_stats_snapshot_.wal_bytes = wal_bytes;
  db_stats_snapshot_.wal_synced = wal_synced;
  db_stats_snapshot_.write_with_wal = write_with_wal;
S
sdong 已提交
733
  db_stats_snapshot_.write_stall_micros = write_stall_micros;
734 735 736
  db_stats_snapshot_.compact_bytes_write = compact_bytes_write;
  db_stats_snapshot_.compact_bytes_read = compact_bytes_read;
  db_stats_snapshot_.compact_micros = compact_micros;
737 738
}

739
void InternalStats::DumpCFStats(std::string* value) {
S
sdong 已提交
740
  const VersionStorageInfo* vstorage = cfd_->current()->storage_info();
741 742

  int num_levels_to_check =
743
      (cfd_->ioptions()->compaction_style != kCompactionStyleFIFO)
744
          ? vstorage->num_levels() - 1
745
          : 1;
S
sdong 已提交
746

747 748 749 750
  // Compaction scores are sorted base on its value. Restore them to the
  // level order
  std::vector<double> compaction_score(number_levels_, 0);
  for (int i = 0; i < num_levels_to_check; ++i) {
751 752
    compaction_score[vstorage->CompactionScoreLevel(i)] =
        vstorage->CompactionScore(i);
753 754 755
  }
  // Count # of files being compacted for each level
  std::vector<int> files_being_compacted(number_levels_, 0);
756
  for (int level = 0; level < number_levels_; ++level) {
757
    for (auto* f : vstorage->LevelFiles(level)) {
758 759 760 761 762 763 764 765
      if (f->being_compacted) {
        ++files_being_compacted[level];
      }
    }
  }

  char buf[1000];
  // Per-ColumnFamily stats
766
  PrintLevelStatsHeader(buf, sizeof(buf), cfd_->GetName());
767 768 769 770 771 772 773
  value->append(buf);

  CompactionStats stats_sum(0);
  int total_files = 0;
  int total_files_being_compacted = 0;
  double total_file_size = 0;
  for (int level = 0; level < number_levels_; level++) {
S
sdong 已提交
774
    int files = vstorage->NumLevelFiles(level);
775 776 777 778
    total_files += files;
    total_files_being_compacted += files_being_compacted[level];
    if (comp_stats_[level].micros > 0 || files > 0) {
      stats_sum.Add(comp_stats_[level]);
S
sdong 已提交
779
      total_file_size += vstorage->NumLevelBytes(level);
780 781 782 783
      double w_amp =
          (comp_stats_[level].bytes_read_non_output_levels == 0) ? 0.0
          : static_cast<double>(comp_stats_[level].bytes_written) /
            comp_stats_[level].bytes_read_non_output_levels;
784
      PrintLevelStats(buf, sizeof(buf), "L" + ToString(level), files,
S
sdong 已提交
785
                      files_being_compacted[level],
786 787
                      static_cast<double>(vstorage->NumLevelBytes(level)),
                      compaction_score[level],
788
                      w_amp, comp_stats_[level]);
789 790 791 792 793 794
      value->append(buf);
    }
  }
  uint64_t curr_ingest = cf_stats_value_[BYTES_FLUSHED];
  // Cumulative summary
  double w_amp = stats_sum.bytes_written / static_cast<double>(curr_ingest + 1);
795 796 797 798 799
  uint64_t total_stall_count =
      cf_stats_count_[LEVEL0_SLOWDOWN_TOTAL] +
      cf_stats_count_[LEVEL0_NUM_FILES_TOTAL] +
      cf_stats_count_[SOFT_PENDING_COMPACTION_BYTES_LIMIT] +
      cf_stats_count_[HARD_PENDING_COMPACTION_BYTES_LIMIT] +
800
      cf_stats_count_[MEMTABLE_COMPACTION] + cf_stats_count_[MEMTABLE_SLOWDOWN];
801 802
  // Stats summary across levels
  PrintLevelStats(buf, sizeof(buf), "Sum", total_files,
803 804
                  total_files_being_compacted, total_file_size, 0, w_amp,
                  stats_sum);
805 806 807 808 809 810 811
  value->append(buf);
  // Interval summary
  uint64_t interval_ingest =
      curr_ingest - cf_stats_snapshot_.ingest_bytes + 1;
  CompactionStats interval_stats(stats_sum);
  interval_stats.Subtract(cf_stats_snapshot_.comp_stats);
  w_amp = interval_stats.bytes_written / static_cast<double>(interval_ingest);
812
  PrintLevelStats(buf, sizeof(buf), "Int", 0, 0, 0, 0, w_amp, interval_stats);
813 814 815
  value->append(buf);

  snprintf(buf, sizeof(buf),
816
           "Flush(GB): cumulative %.3f, interval %.3f\n",
817 818 819
           curr_ingest / kGB, interval_ingest / kGB);
  value->append(buf);

820 821 822 823 824 825 826 827 828
  snprintf(buf, sizeof(buf), "Stalls(count): %" PRIu64
                             " level0_slowdown, "
                             "%" PRIu64
                             " level0_slowdown_with_compaction, "
                             "%" PRIu64
                             " level0_numfiles, "
                             "%" PRIu64
                             " level0_numfiles_with_compaction, "
                             "%" PRIu64
829
                             " stop for pending_compaction_bytes, "
830
                             "%" PRIu64
831
                             " slowdown for pending_compaction_bytes, "
832
                             "%" PRIu64
833
                             " memtable_compaction, "
834 835
                             "%" PRIu64
                             " memtable_slowdown, "
836
                             "interval %" PRIu64 " total count\n",
837 838 839 840
           cf_stats_count_[LEVEL0_SLOWDOWN_TOTAL],
           cf_stats_count_[LEVEL0_SLOWDOWN_WITH_COMPACTION],
           cf_stats_count_[LEVEL0_NUM_FILES_TOTAL],
           cf_stats_count_[LEVEL0_NUM_FILES_WITH_COMPACTION],
841
           cf_stats_count_[HARD_PENDING_COMPACTION_BYTES_LIMIT],
842 843
           cf_stats_count_[SOFT_PENDING_COMPACTION_BYTES_LIMIT],
           cf_stats_count_[MEMTABLE_COMPACTION],
844
           cf_stats_count_[MEMTABLE_SLOWDOWN],
845
           total_stall_count - cf_stats_snapshot_.stall_count);
846 847 848 849 850 851 852
  value->append(buf);

  cf_stats_snapshot_.ingest_bytes = curr_ingest;
  cf_stats_snapshot_.comp_stats = stats_sum;
  cf_stats_snapshot_.stall_count = total_stall_count;
}

853 854 855

#else

856
const DBPropertyInfo* GetPropertyInfo(const Slice& property) { return nullptr; }
857 858 859

#endif  // !ROCKSDB_LITE

I
Igor Canadi 已提交
860
}  // namespace rocksdb