internal_stats.cc 67.7 KB
Newer Older
S
Siying Dong 已提交
1 2 3
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
I
Igor Canadi 已提交
4
//
5 6
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
//
I
Igor Canadi 已提交
7 8 9 10 11
// 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 已提交
12

13
#include <algorithm>
14
#include <cinttypes>
15
#include <cstddef>
Y
Yi Wu 已提交
16
#include <limits>
17
#include <sstream>
Y
Yi Wu 已提交
18
#include <string>
19
#include <utility>
I
Igor Canadi 已提交
20
#include <vector>
21

22 23
#include "cache/cache_entry_roles.h"
#include "cache/cache_entry_stats.h"
Y
Yi Wu 已提交
24
#include "db/column_family.h"
25
#include "db/db_impl/db_impl.h"
26
#include "rocksdb/system_clock.h"
27
#include "rocksdb/table.h"
28
#include "table/block_based/cachable_entry.h"
29
#include "util/string_util.h"
I
Igor Canadi 已提交
30

31
namespace ROCKSDB_NAMESPACE {
I
Igor Canadi 已提交
32

33
#ifndef ROCKSDB_LITE
34 35 36 37 38 39

const std::map<LevelStatType, LevelStat> InternalStats::compaction_level_stats =
    {
        {LevelStatType::NUM_FILES, LevelStat{"NumFiles", "Files"}},
        {LevelStatType::COMPACTED_FILES,
         LevelStat{"CompactedFiles", "CompactedFiles"}},
40
        {LevelStatType::SIZE_BYTES, LevelStat{"SizeBytes", "Size"}},
41
        {LevelStatType::SCORE, LevelStat{"Score", "Score"}},
42 43 44 45 46 47
        {LevelStatType::READ_GB, LevelStat{"ReadGB", "Read(GB)"}},
        {LevelStatType::RN_GB, LevelStat{"RnGB", "Rn(GB)"}},
        {LevelStatType::RNP1_GB, LevelStat{"Rnp1GB", "Rnp1(GB)"}},
        {LevelStatType::WRITE_GB, LevelStat{"WriteGB", "Write(GB)"}},
        {LevelStatType::W_NEW_GB, LevelStat{"WnewGB", "Wnew(GB)"}},
        {LevelStatType::MOVED_GB, LevelStat{"MovedGB", "Moved(GB)"}},
48
        {LevelStatType::WRITE_AMP, LevelStat{"WriteAmp", "W-Amp"}},
49 50 51
        {LevelStatType::READ_MBPS, LevelStat{"ReadMBps", "Rd(MB/s)"}},
        {LevelStatType::WRITE_MBPS, LevelStat{"WriteMBps", "Wr(MB/s)"}},
        {LevelStatType::COMP_SEC, LevelStat{"CompSec", "Comp(sec)"}},
52 53
        {LevelStatType::COMP_CPU_SEC,
         LevelStat{"CompMergeCPU", "CompMergeCPU(sec)"}},
54 55
        {LevelStatType::COMP_COUNT, LevelStat{"CompCount", "Comp(cnt)"}},
        {LevelStatType::AVG_SEC, LevelStat{"AvgSec", "Avg(sec)"}},
56 57
        {LevelStatType::KEY_IN, LevelStat{"KeyIn", "KeyIn"}},
        {LevelStatType::KEY_DROP, LevelStat{"KeyDrop", "KeyDrop"}},
58
        {LevelStatType::R_BLOB_GB, LevelStat{"RblobGB", "Rblob(GB)"}},
59
        {LevelStatType::W_BLOB_GB, LevelStat{"WblobGB", "Wblob(GB)"}},
60 61
};

L
Lei Jin 已提交
62 63 64
namespace {
const double kMB = 1048576.0;
const double kGB = kMB * 1024;
65
const double kMicrosInSec = 1000000.0;
L
Lei Jin 已提交
66

67 68
void PrintLevelStatsHeader(char* buf, size_t len, const std::string& cf_name,
                           const std::string& group_by) {
69 70
  int written_size =
      snprintf(buf, len, "\n** Compaction Stats [%s] **\n", cf_name.c_str());
71
  written_size = std::min(written_size, static_cast<int>(len));
72 73 74 75 76
  auto hdr = [](LevelStatType t) {
    return InternalStats::compaction_level_stats.at(t).header_name.c_str();
  };
  int line_size = snprintf(
      buf + written_size, len - written_size,
77 78
      "%s    %s   %s     %s %s  %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s "
      "%s\n",
79
      // Note that we skip COMPACTED_FILES and merge it with Files column
80 81 82 83 84 85 86 87 88
      group_by.c_str(), hdr(LevelStatType::NUM_FILES),
      hdr(LevelStatType::SIZE_BYTES), hdr(LevelStatType::SCORE),
      hdr(LevelStatType::READ_GB), hdr(LevelStatType::RN_GB),
      hdr(LevelStatType::RNP1_GB), hdr(LevelStatType::WRITE_GB),
      hdr(LevelStatType::W_NEW_GB), hdr(LevelStatType::MOVED_GB),
      hdr(LevelStatType::WRITE_AMP), hdr(LevelStatType::READ_MBPS),
      hdr(LevelStatType::WRITE_MBPS), hdr(LevelStatType::COMP_SEC),
      hdr(LevelStatType::COMP_CPU_SEC), hdr(LevelStatType::COMP_COUNT),
      hdr(LevelStatType::AVG_SEC), hdr(LevelStatType::KEY_IN),
89 90
      hdr(LevelStatType::KEY_DROP), hdr(LevelStatType::R_BLOB_GB),
      hdr(LevelStatType::W_BLOB_GB));
91 92

  written_size += line_size;
93
  written_size = std::min(written_size, static_cast<int>(len));
94 95
  snprintf(buf + written_size, len - written_size, "%s\n",
           std::string(line_size, '-').c_str());
L
Lei Jin 已提交
96 97
}

98 99 100 101
void PrepareLevelStats(std::map<LevelStatType, double>* level_stats,
                       int num_files, int being_compacted,
                       double total_file_size, double score, double w_amp,
                       const InternalStats::CompactionStats& stats) {
102 103 104
  const uint64_t bytes_read = stats.bytes_read_non_output_levels +
                              stats.bytes_read_output_level +
                              stats.bytes_read_blob;
105 106 107
  const uint64_t bytes_written = stats.bytes_written + stats.bytes_written_blob;
  const int64_t bytes_new = stats.bytes_written - stats.bytes_read_output_level;
  const double elapsed = (stats.micros + 1) / kMicrosInSec;
L
Lei Jin 已提交
108

109 110
  (*level_stats)[LevelStatType::NUM_FILES] = num_files;
  (*level_stats)[LevelStatType::COMPACTED_FILES] = being_compacted;
111
  (*level_stats)[LevelStatType::SIZE_BYTES] = total_file_size;
112 113 114 115 116 117 118 119 120 121
  (*level_stats)[LevelStatType::SCORE] = score;
  (*level_stats)[LevelStatType::READ_GB] = bytes_read / kGB;
  (*level_stats)[LevelStatType::RN_GB] =
      stats.bytes_read_non_output_levels / kGB;
  (*level_stats)[LevelStatType::RNP1_GB] = stats.bytes_read_output_level / kGB;
  (*level_stats)[LevelStatType::WRITE_GB] = stats.bytes_written / kGB;
  (*level_stats)[LevelStatType::W_NEW_GB] = bytes_new / kGB;
  (*level_stats)[LevelStatType::MOVED_GB] = stats.bytes_moved / kGB;
  (*level_stats)[LevelStatType::WRITE_AMP] = w_amp;
  (*level_stats)[LevelStatType::READ_MBPS] = bytes_read / kMB / elapsed;
122
  (*level_stats)[LevelStatType::WRITE_MBPS] = bytes_written / kMB / elapsed;
123
  (*level_stats)[LevelStatType::COMP_SEC] = stats.micros / kMicrosInSec;
124
  (*level_stats)[LevelStatType::COMP_CPU_SEC] = stats.cpu_micros / kMicrosInSec;
125 126 127 128 129 130 131
  (*level_stats)[LevelStatType::COMP_COUNT] = stats.count;
  (*level_stats)[LevelStatType::AVG_SEC] =
      stats.count == 0 ? 0 : stats.micros / kMicrosInSec / stats.count;
  (*level_stats)[LevelStatType::KEY_IN] =
      static_cast<double>(stats.num_input_records);
  (*level_stats)[LevelStatType::KEY_DROP] =
      static_cast<double>(stats.num_dropped_records);
132
  (*level_stats)[LevelStatType::R_BLOB_GB] = stats.bytes_read_blob / kGB;
133
  (*level_stats)[LevelStatType::W_BLOB_GB] = stats.bytes_written_blob / kGB;
134 135 136 137
}

void PrintLevelStats(char* buf, size_t len, const std::string& name,
                     const std::map<LevelStatType, double>& stat_value) {
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  snprintf(
      buf, len,
      "%4s "      /*  Level */
      "%6d/%-3d " /*  Files */
      "%8s "      /*  Size */
      "%5.1f "    /*  Score */
      "%8.1f "    /*  Read(GB) */
      "%7.1f "    /*  Rn(GB) */
      "%8.1f "    /*  Rnp1(GB) */
      "%9.1f "    /*  Write(GB) */
      "%8.1f "    /*  Wnew(GB) */
      "%9.1f "    /*  Moved(GB) */
      "%5.1f "    /*  W-Amp */
      "%8.1f "    /*  Rd(MB/s) */
      "%8.1f "    /*  Wr(MB/s) */
153 154
      "%9.2f "    /*  Comp(sec) */
      "%17.2f "   /*  CompMergeCPU(sec) */
155 156 157
      "%9d "      /*  Comp(cnt) */
      "%8.3f "    /*  Avg(sec) */
      "%7s "      /*  KeyIn */
158
      "%6s "      /*  KeyDrop */
159
      "%9.1f "    /*  Rblob(GB) */
160
      "%9.1f\n",  /*  Wblob(GB) */
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      name.c_str(), static_cast<int>(stat_value.at(LevelStatType::NUM_FILES)),
      static_cast<int>(stat_value.at(LevelStatType::COMPACTED_FILES)),
      BytesToHumanString(
          static_cast<uint64_t>(stat_value.at(LevelStatType::SIZE_BYTES)))
          .c_str(),
      stat_value.at(LevelStatType::SCORE),
      stat_value.at(LevelStatType::READ_GB),
      stat_value.at(LevelStatType::RN_GB),
      stat_value.at(LevelStatType::RNP1_GB),
      stat_value.at(LevelStatType::WRITE_GB),
      stat_value.at(LevelStatType::W_NEW_GB),
      stat_value.at(LevelStatType::MOVED_GB),
      stat_value.at(LevelStatType::WRITE_AMP),
      stat_value.at(LevelStatType::READ_MBPS),
      stat_value.at(LevelStatType::WRITE_MBPS),
      stat_value.at(LevelStatType::COMP_SEC),
177
      stat_value.at(LevelStatType::COMP_CPU_SEC),
178 179 180 181 182 183 184
      static_cast<int>(stat_value.at(LevelStatType::COMP_COUNT)),
      stat_value.at(LevelStatType::AVG_SEC),
      NumberToHumanString(
          static_cast<std::int64_t>(stat_value.at(LevelStatType::KEY_IN)))
          .c_str(),
      NumberToHumanString(
          static_cast<std::int64_t>(stat_value.at(LevelStatType::KEY_DROP)))
185
          .c_str(),
186
      stat_value.at(LevelStatType::R_BLOB_GB),
187
      stat_value.at(LevelStatType::W_BLOB_GB));
188 189 190 191 192 193 194 195 196 197
}

void PrintLevelStats(char* buf, size_t len, const std::string& name,
                     int num_files, int being_compacted, double total_file_size,
                     double score, double w_amp,
                     const InternalStats::CompactionStats& stats) {
  std::map<LevelStatType, double> level_stats;
  PrepareLevelStats(&level_stats, num_files, being_compacted, total_file_size,
                    score, w_amp, stats);
  PrintLevelStats(buf, len, name, level_stats);
L
Lei Jin 已提交
198
}
199 200 201 202 203 204 205 206 207 208 209 210 211

// 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 已提交
212
}
213
}  // anonymous namespace
L
Lei Jin 已提交
214

215 216 217
static const std::string rocksdb_prefix = "rocksdb.";

static const std::string num_files_at_level_prefix = "num-files-at-level";
218 219
static const std::string compression_ratio_at_level_prefix =
    "compression-ratio-at-level";
220
static const std::string allstats = "stats";
221 222
static const std::string sstables = "sstables";
static const std::string cfstats = "cfstats";
223 224 225
static const std::string cfstats_no_file_histogram =
    "cfstats-no-file-histogram";
static const std::string cf_file_histogram = "cf-file-histogram";
226 227
static const std::string dbstats = "dbstats";
static const std::string levelstats = "levelstats";
228
static const std::string block_cache_entry_stats = "block-cache-entry-stats";
229
static const std::string num_immutable_mem_table = "num-immutable-mem-table";
230 231
static const std::string num_immutable_mem_table_flushed =
    "num-immutable-mem-table-flushed";
232 233 234 235
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 =
236
    "cur-size-active-mem-table";
237 238
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";
239
static const std::string num_entries_active_mem_table =
240
    "num-entries-active-mem-table";
241
static const std::string num_entries_imm_mem_tables =
242
    "num-entries-imm-mem-tables";
243
static const std::string num_deletes_active_mem_table =
244
    "num-deletes-active-mem-table";
245
static const std::string num_deletes_imm_mem_tables =
246
    "num-deletes-imm-mem-tables";
247 248
static const std::string estimate_num_keys = "estimate-num-keys";
static const std::string estimate_table_readers_mem =
249
    "estimate-table-readers-mem";
250
static const std::string is_file_deletions_enabled =
251
    "is-file-deletions-enabled";
252 253
static const std::string num_snapshots = "num-snapshots";
static const std::string oldest_snapshot_time = "oldest-snapshot-time";
254
static const std::string oldest_snapshot_sequence = "oldest-snapshot-sequence";
255
static const std::string num_live_versions = "num-live-versions";
256 257
static const std::string current_version_number =
    "current-super-version-number";
A
Andres Notzli 已提交
258
static const std::string estimate_live_data_size = "estimate-live-data-size";
259
static const std::string min_log_number_to_keep_str = "min-log-number-to-keep";
260 261
static const std::string min_obsolete_sst_number_to_keep_str =
    "min-obsolete-sst-number-to-keep";
262
static const std::string base_level_str = "base-level";
263
static const std::string total_sst_files_size = "total-sst-files-size";
264
static const std::string live_sst_files_size = "live-sst-files-size";
265 266
static const std::string estimate_pending_comp_bytes =
    "estimate-pending-compaction-bytes";
267 268 269 270
static const std::string aggregated_table_properties =
    "aggregated-table-properties";
static const std::string aggregated_table_properties_at_level =
    aggregated_table_properties + "-at-level";
271 272
static const std::string num_running_compactions = "num-running-compactions";
static const std::string num_running_flushes = "num-running-flushes";
273 274 275
static const std::string actual_delayed_write_rate =
    "actual-delayed-write-rate";
static const std::string is_write_stopped = "is-write-stopped";
Y
Yi Wu 已提交
276
static const std::string estimate_oldest_key_time = "estimate-oldest-key-time";
Y
Yi Wu 已提交
277 278 279
static const std::string block_cache_capacity = "block-cache-capacity";
static const std::string block_cache_usage = "block-cache-usage";
static const std::string block_cache_pinned_usage = "block-cache-pinned-usage";
280
static const std::string options_statistics = "options-statistics";
281 282

const std::string DB::Properties::kNumFilesAtLevelPrefix =
283
    rocksdb_prefix + num_files_at_level_prefix;
284
const std::string DB::Properties::kCompressionRatioAtLevelPrefix =
285
    rocksdb_prefix + compression_ratio_at_level_prefix;
286
const std::string DB::Properties::kStats = rocksdb_prefix + allstats;
287 288
const std::string DB::Properties::kSSTables = rocksdb_prefix + sstables;
const std::string DB::Properties::kCFStats = rocksdb_prefix + cfstats;
289 290 291 292
const std::string DB::Properties::kCFStatsNoFileHistogram =
    rocksdb_prefix + cfstats_no_file_histogram;
const std::string DB::Properties::kCFFileHistogram =
    rocksdb_prefix + cf_file_histogram;
293
const std::string DB::Properties::kDBStats = rocksdb_prefix + dbstats;
294
const std::string DB::Properties::kLevelStats = rocksdb_prefix + levelstats;
295 296
const std::string DB::Properties::kBlockCacheEntryStats =
    rocksdb_prefix + block_cache_entry_stats;
297
const std::string DB::Properties::kNumImmutableMemTable =
298
    rocksdb_prefix + num_immutable_mem_table;
299
const std::string DB::Properties::kNumImmutableMemTableFlushed =
300
    rocksdb_prefix + num_immutable_mem_table_flushed;
301
const std::string DB::Properties::kMemTableFlushPending =
302
    rocksdb_prefix + mem_table_flush_pending;
303
const std::string DB::Properties::kCompactionPending =
304
    rocksdb_prefix + compaction_pending;
305 306 307 308
const std::string DB::Properties::kNumRunningCompactions =
    rocksdb_prefix + num_running_compactions;
const std::string DB::Properties::kNumRunningFlushes =
    rocksdb_prefix + num_running_flushes;
309
const std::string DB::Properties::kBackgroundErrors =
310
    rocksdb_prefix + background_errors;
311
const std::string DB::Properties::kCurSizeActiveMemTable =
312
    rocksdb_prefix + cur_size_active_mem_table;
313
const std::string DB::Properties::kCurSizeAllMemTables =
314
    rocksdb_prefix + cur_size_all_mem_tables;
315 316
const std::string DB::Properties::kSizeAllMemTables =
    rocksdb_prefix + size_all_mem_tables;
317
const std::string DB::Properties::kNumEntriesActiveMemTable =
318
    rocksdb_prefix + num_entries_active_mem_table;
319
const std::string DB::Properties::kNumEntriesImmMemTables =
320
    rocksdb_prefix + num_entries_imm_mem_tables;
321
const std::string DB::Properties::kNumDeletesActiveMemTable =
322
    rocksdb_prefix + num_deletes_active_mem_table;
323
const std::string DB::Properties::kNumDeletesImmMemTables =
324
    rocksdb_prefix + num_deletes_imm_mem_tables;
325
const std::string DB::Properties::kEstimateNumKeys =
326
    rocksdb_prefix + estimate_num_keys;
327
const std::string DB::Properties::kEstimateTableReadersMem =
328
    rocksdb_prefix + estimate_table_readers_mem;
329
const std::string DB::Properties::kIsFileDeletionsEnabled =
330
    rocksdb_prefix + is_file_deletions_enabled;
331
const std::string DB::Properties::kNumSnapshots =
332
    rocksdb_prefix + num_snapshots;
333
const std::string DB::Properties::kOldestSnapshotTime =
334
    rocksdb_prefix + oldest_snapshot_time;
335 336
const std::string DB::Properties::kOldestSnapshotSequence =
    rocksdb_prefix + oldest_snapshot_sequence;
337
const std::string DB::Properties::kNumLiveVersions =
338
    rocksdb_prefix + num_live_versions;
339
const std::string DB::Properties::kCurrentSuperVersionNumber =
340
    rocksdb_prefix + current_version_number;
A
Andres Notzli 已提交
341
const std::string DB::Properties::kEstimateLiveDataSize =
342
    rocksdb_prefix + estimate_live_data_size;
343
const std::string DB::Properties::kMinLogNumberToKeep =
344
    rocksdb_prefix + min_log_number_to_keep_str;
345 346
const std::string DB::Properties::kMinObsoleteSstNumberToKeep =
    rocksdb_prefix + min_obsolete_sst_number_to_keep_str;
347
const std::string DB::Properties::kTotalSstFilesSize =
348
    rocksdb_prefix + total_sst_files_size;
349 350
const std::string DB::Properties::kLiveSstFilesSize =
    rocksdb_prefix + live_sst_files_size;
351
const std::string DB::Properties::kBaseLevel = rocksdb_prefix + base_level_str;
352 353
const std::string DB::Properties::kEstimatePendingCompactionBytes =
    rocksdb_prefix + estimate_pending_comp_bytes;
354 355 356 357
const std::string DB::Properties::kAggregatedTableProperties =
    rocksdb_prefix + aggregated_table_properties;
const std::string DB::Properties::kAggregatedTablePropertiesAtLevel =
    rocksdb_prefix + aggregated_table_properties_at_level;
358 359 360 361
const std::string DB::Properties::kActualDelayedWriteRate =
    rocksdb_prefix + actual_delayed_write_rate;
const std::string DB::Properties::kIsWriteStopped =
    rocksdb_prefix + is_write_stopped;
Y
Yi Wu 已提交
362 363
const std::string DB::Properties::kEstimateOldestKeyTime =
    rocksdb_prefix + estimate_oldest_key_time;
Y
Yi Wu 已提交
364 365 366 367 368 369
const std::string DB::Properties::kBlockCacheCapacity =
    rocksdb_prefix + block_cache_capacity;
const std::string DB::Properties::kBlockCacheUsage =
    rocksdb_prefix + block_cache_usage;
const std::string DB::Properties::kBlockCachePinnedUsage =
    rocksdb_prefix + block_cache_pinned_usage;
370 371
const std::string DB::Properties::kOptionsStatistics =
    rocksdb_prefix + options_statistics;
372

373 374 375
const std::unordered_map<std::string, DBPropertyInfo>
    InternalStats::ppt_name_to_info = {
        {DB::Properties::kNumFilesAtLevelPrefix,
376 377
         {false, &InternalStats::HandleNumFilesAtLevel, nullptr, nullptr,
          nullptr}},
378 379
        {DB::Properties::kCompressionRatioAtLevelPrefix,
         {false, &InternalStats::HandleCompressionRatioAtLevelPrefix, nullptr,
380
          nullptr, nullptr}},
381
        {DB::Properties::kLevelStats,
382
         {false, &InternalStats::HandleLevelStats, nullptr, nullptr, nullptr}},
383
        {DB::Properties::kStats,
384
         {false, &InternalStats::HandleStats, nullptr, nullptr, nullptr}},
385 386
        {DB::Properties::kCFStats,
         {false, &InternalStats::HandleCFStats, nullptr,
387
          &InternalStats::HandleCFMapStats, nullptr}},
388
        {DB::Properties::kCFStatsNoFileHistogram,
389
         {false, &InternalStats::HandleCFStatsNoFileHistogram, nullptr, nullptr,
390 391
          nullptr}},
        {DB::Properties::kCFFileHistogram,
392 393
         {false, &InternalStats::HandleCFFileHistogram, nullptr, nullptr,
          nullptr}},
394
        {DB::Properties::kDBStats,
395
         {false, &InternalStats::HandleDBStats, nullptr, nullptr, nullptr}},
396 397 398
        {DB::Properties::kBlockCacheEntryStats,
         {false, &InternalStats::HandleBlockCacheEntryStats, nullptr,
          &InternalStats::HandleBlockCacheEntryStatsMap, nullptr}},
399
        {DB::Properties::kSSTables,
400
         {false, &InternalStats::HandleSsTables, nullptr, nullptr, nullptr}},
401 402
        {DB::Properties::kAggregatedTableProperties,
         {false, &InternalStats::HandleAggregatedTableProperties, nullptr,
403
          &InternalStats::HandleAggregatedTablePropertiesMap, nullptr}},
404 405
        {DB::Properties::kAggregatedTablePropertiesAtLevel,
         {false, &InternalStats::HandleAggregatedTablePropertiesAtLevel,
406 407
          nullptr, &InternalStats::HandleAggregatedTablePropertiesAtLevelMap,
          nullptr}},
408
        {DB::Properties::kNumImmutableMemTable,
409 410
         {false, nullptr, &InternalStats::HandleNumImmutableMemTable, nullptr,
          nullptr}},
411 412
        {DB::Properties::kNumImmutableMemTableFlushed,
         {false, nullptr, &InternalStats::HandleNumImmutableMemTableFlushed,
413
          nullptr, nullptr}},
414
        {DB::Properties::kMemTableFlushPending,
415 416
         {false, nullptr, &InternalStats::HandleMemTableFlushPending, nullptr,
          nullptr}},
417
        {DB::Properties::kCompactionPending,
418 419
         {false, nullptr, &InternalStats::HandleCompactionPending, nullptr,
          nullptr}},
420
        {DB::Properties::kBackgroundErrors,
421 422
         {false, nullptr, &InternalStats::HandleBackgroundErrors, nullptr,
          nullptr}},
423
        {DB::Properties::kCurSizeActiveMemTable,
424
         {false, nullptr, &InternalStats::HandleCurSizeActiveMemTable, nullptr,
425 426
          nullptr}},
        {DB::Properties::kCurSizeAllMemTables,
427 428
         {false, nullptr, &InternalStats::HandleCurSizeAllMemTables, nullptr,
          nullptr}},
429
        {DB::Properties::kSizeAllMemTables,
430 431
         {false, nullptr, &InternalStats::HandleSizeAllMemTables, nullptr,
          nullptr}},
432 433
        {DB::Properties::kNumEntriesActiveMemTable,
         {false, nullptr, &InternalStats::HandleNumEntriesActiveMemTable,
434
          nullptr, nullptr}},
435
        {DB::Properties::kNumEntriesImmMemTables,
436
         {false, nullptr, &InternalStats::HandleNumEntriesImmMemTables, nullptr,
437 438 439
          nullptr}},
        {DB::Properties::kNumDeletesActiveMemTable,
         {false, nullptr, &InternalStats::HandleNumDeletesActiveMemTable,
440
          nullptr, nullptr}},
441
        {DB::Properties::kNumDeletesImmMemTables,
442
         {false, nullptr, &InternalStats::HandleNumDeletesImmMemTables, nullptr,
443 444
          nullptr}},
        {DB::Properties::kEstimateNumKeys,
445 446
         {false, nullptr, &InternalStats::HandleEstimateNumKeys, nullptr,
          nullptr}},
447
        {DB::Properties::kEstimateTableReadersMem,
448
         {true, nullptr, &InternalStats::HandleEstimateTableReadersMem, nullptr,
449 450
          nullptr}},
        {DB::Properties::kIsFileDeletionsEnabled,
451
         {false, nullptr, &InternalStats::HandleIsFileDeletionsEnabled, nullptr,
452 453
          nullptr}},
        {DB::Properties::kNumSnapshots,
454 455
         {false, nullptr, &InternalStats::HandleNumSnapshots, nullptr,
          nullptr}},
456
        {DB::Properties::kOldestSnapshotTime,
457 458
         {false, nullptr, &InternalStats::HandleOldestSnapshotTime, nullptr,
          nullptr}},
459 460 461
        {DB::Properties::kOldestSnapshotSequence,
         {false, nullptr, &InternalStats::HandleOldestSnapshotSequence, nullptr,
          nullptr}},
462
        {DB::Properties::kNumLiveVersions,
463 464
         {false, nullptr, &InternalStats::HandleNumLiveVersions, nullptr,
          nullptr}},
465 466
        {DB::Properties::kCurrentSuperVersionNumber,
         {false, nullptr, &InternalStats::HandleCurrentSuperVersionNumber,
467
          nullptr, nullptr}},
468
        {DB::Properties::kEstimateLiveDataSize,
469 470
         {true, nullptr, &InternalStats::HandleEstimateLiveDataSize, nullptr,
          nullptr}},
471
        {DB::Properties::kMinLogNumberToKeep,
472 473
         {false, nullptr, &InternalStats::HandleMinLogNumberToKeep, nullptr,
          nullptr}},
474 475 476
        {DB::Properties::kMinObsoleteSstNumberToKeep,
         {false, nullptr, &InternalStats::HandleMinObsoleteSstNumberToKeep,
          nullptr, nullptr}},
477
        {DB::Properties::kBaseLevel,
478
         {false, nullptr, &InternalStats::HandleBaseLevel, nullptr, nullptr}},
479
        {DB::Properties::kTotalSstFilesSize,
480 481
         {false, nullptr, &InternalStats::HandleTotalSstFilesSize, nullptr,
          nullptr}},
482
        {DB::Properties::kLiveSstFilesSize,
483 484
         {false, nullptr, &InternalStats::HandleLiveSstFilesSize, nullptr,
          nullptr}},
485 486
        {DB::Properties::kEstimatePendingCompactionBytes,
         {false, nullptr, &InternalStats::HandleEstimatePendingCompactionBytes,
487
          nullptr, nullptr}},
488
        {DB::Properties::kNumRunningFlushes,
489 490
         {false, nullptr, &InternalStats::HandleNumRunningFlushes, nullptr,
          nullptr}},
491
        {DB::Properties::kNumRunningCompactions,
492
         {false, nullptr, &InternalStats::HandleNumRunningCompactions, nullptr,
493
          nullptr}},
494
        {DB::Properties::kActualDelayedWriteRate,
495
         {false, nullptr, &InternalStats::HandleActualDelayedWriteRate, nullptr,
496 497
          nullptr}},
        {DB::Properties::kIsWriteStopped,
498 499
         {false, nullptr, &InternalStats::HandleIsWriteStopped, nullptr,
          nullptr}},
Y
Yi Wu 已提交
500
        {DB::Properties::kEstimateOldestKeyTime,
501
         {false, nullptr, &InternalStats::HandleEstimateOldestKeyTime, nullptr,
Y
Yi Wu 已提交
502
          nullptr}},
Y
Yi Wu 已提交
503
        {DB::Properties::kBlockCacheCapacity,
504 505
         {false, nullptr, &InternalStats::HandleBlockCacheCapacity, nullptr,
          nullptr}},
Y
Yi Wu 已提交
506
        {DB::Properties::kBlockCacheUsage,
507 508
         {false, nullptr, &InternalStats::HandleBlockCacheUsage, nullptr,
          nullptr}},
Y
Yi Wu 已提交
509
        {DB::Properties::kBlockCachePinnedUsage,
510
         {false, nullptr, &InternalStats::HandleBlockCachePinnedUsage, nullptr,
Y
Yi Wu 已提交
511
          nullptr}},
512 513 514
        {DB::Properties::kOptionsStatistics,
         {false, nullptr, nullptr, nullptr,
          &DBImpl::GetPropertyHandleOptionsStatistics}},
515 516
};

517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
InternalStats::InternalStats(int num_levels, SystemClock* clock,
                             ColumnFamilyData* cfd)
    : db_stats_{},
      cf_stats_value_{},
      cf_stats_count_{},
      comp_stats_(num_levels),
      comp_stats_by_pri_(Env::Priority::TOTAL),
      file_read_latency_(num_levels),
      bg_error_count_(0),
      number_levels_(num_levels),
      clock_(clock),
      cfd_(cfd),
      started_at_(clock->NowMicros()) {}

Status InternalStats::CollectCacheEntryStats() {
  using Collector = CacheEntryStatsCollector<CacheEntryRoleStats>;
  Cache* block_cache;
  bool ok = HandleBlockCacheStat(&block_cache);
  if (ok) {
    // Extract or create stats collector.
    std::shared_ptr<Collector> collector;
    Status s = Collector::GetShared(block_cache, clock_, &collector);
    if (s.ok()) {
540 541
      // TODO: use a max age like stats_dump_period_sec / 2, but it's
      // difficult to access that setting from here with just cfd_
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 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
      collector->GetStats(&cache_entry_stats);
    } else {
      // Block cache likely under pressure. Scanning could make it worse,
      // so skip.
    }
    return s;
  } else {
    return Status::NotFound("block cache not configured");
  }
}

std::function<void(const Slice&, void*, size_t, Cache::DeleterFn)>
InternalStats::CacheEntryRoleStats::GetEntryCallback() {
  return [&](const Slice& /*key*/, void* /*value*/, size_t charge,
             Cache::DeleterFn deleter) {
    auto e = role_map_.find(deleter);
    size_t role_idx;
    if (e == role_map_.end()) {
      role_idx = static_cast<size_t>(CacheEntryRole::kMisc);
    } else {
      role_idx = static_cast<size_t>(e->second);
    }
    entry_counts[role_idx]++;
    total_charges[role_idx] += charge;
  };
}

void InternalStats::CacheEntryRoleStats::BeginCollection(
    Cache* cache, SystemClock*, uint64_t start_time_micros) {
  Clear();
  last_start_time_micros_ = start_time_micros;
  ++collection_count;
  role_map_ = CopyCacheDeleterRoleMap();
  std::ostringstream str;
  str << cache->Name() << "@" << static_cast<void*>(cache);
  cache_id = str.str();
  cache_capacity = cache->GetCapacity();
}

void InternalStats::CacheEntryRoleStats::EndCollection(
    Cache*, SystemClock*, uint64_t end_time_micros) {
  last_end_time_micros_ = end_time_micros;
}

void InternalStats::CacheEntryRoleStats::SkippedCollection() {
  ++copies_of_last_collection;
}

uint64_t InternalStats::CacheEntryRoleStats::GetLastDurationMicros() const {
  if (last_end_time_micros_ > last_start_time_micros_) {
    return last_end_time_micros_ - last_start_time_micros_;
  } else {
    return 0U;
  }
}

std::string InternalStats::CacheEntryRoleStats::ToString(
    SystemClock* clock) const {
  std::ostringstream str;
  str << "Block cache " << cache_id
      << " capacity: " << BytesToHumanString(cache_capacity)
      << " collections: " << collection_count
      << " last_copies: " << copies_of_last_collection
      << " last_secs: " << (GetLastDurationMicros() / 1000000.0)
      << " secs_since: "
      << ((clock->NowMicros() - last_end_time_micros_) / 1000000U) << "\n";
  str << "Block cache entry stats(count,size,portion):";
  for (size_t i = 0; i < kNumCacheEntryRoles; ++i) {
    if (entry_counts[i] > 0) {
      str << " " << kCacheEntryRoleToCamelString[i] << "(" << entry_counts[i]
          << "," << BytesToHumanString(total_charges[i]) << ","
          << (100.0 * total_charges[i] / cache_capacity) << "%)";
    }
  }
  str << "\n";
  return str.str();
}

void InternalStats::CacheEntryRoleStats::ToMap(
    std::map<std::string, std::string>* values, SystemClock* clock) const {
  values->clear();
  auto& v = *values;
  v["id"] = cache_id;
  v["capacity"] = ROCKSDB_NAMESPACE::ToString(cache_capacity);
  v["secs_for_last_collection"] =
      ROCKSDB_NAMESPACE::ToString(GetLastDurationMicros() / 1000000.0);
  v["secs_since_last_collection"] = ROCKSDB_NAMESPACE::ToString(
      (clock->NowMicros() - last_end_time_micros_) / 1000000U);
  for (size_t i = 0; i < kNumCacheEntryRoles; ++i) {
    std::string role = kCacheEntryRoleToHyphenString[i];
    v["count." + role] = ROCKSDB_NAMESPACE::ToString(entry_counts[i]);
    v["bytes." + role] = ROCKSDB_NAMESPACE::ToString(total_charges[i]);
    v["percent." + role] =
        ROCKSDB_NAMESPACE::ToString(100.0 * total_charges[i] / cache_capacity);
  }
}

bool InternalStats::HandleBlockCacheEntryStats(std::string* value,
                                               Slice /*suffix*/) {
  Status s = CollectCacheEntryStats();
  if (!s.ok()) {
    return false;
  }
  *value = cache_entry_stats.ToString(clock_);
  return true;
}

bool InternalStats::HandleBlockCacheEntryStatsMap(
    std::map<std::string, std::string>* values, Slice /*suffix*/) {
  Status s = CollectCacheEntryStats();
  if (!s.ok()) {
    return false;
  }
  cache_entry_stats.ToMap(values, clock_);
  return true;
}

659 660 661 662 663
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;
664
  }
665 666
  return &ppt_info_iter->second;
}
667

668 669 670 671 672 673 674
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);
675 676
}

677
bool InternalStats::GetMapProperty(const DBPropertyInfo& property_info,
678
                                   const Slice& property,
679
                                   std::map<std::string, std::string>* value) {
680 681
  assert(value != nullptr);
  assert(property_info.handle_map != nullptr);
682 683
  Slice arg = GetPropertyNameAndArg(property).second;
  return (this->*(property_info.handle_map))(value, arg);
684 685
}

686 687
bool InternalStats::GetIntProperty(const DBPropertyInfo& property_info,
                                   uint64_t* value, DBImpl* db) {
688
  assert(value != nullptr);
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
  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 已提交
705
  const auto* vstorage = cfd_->current()->storage_info();
706 707 708 709 710 711 712 713 714 715 716 717
  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;
  }
}

718 719 720 721 722 723 724 725 726 727 728 729 730
bool InternalStats::HandleCompressionRatioAtLevelPrefix(std::string* value,
                                                        Slice suffix) {
  uint64_t level;
  const auto* vstorage = cfd_->current()->storage_info();
  bool ok = ConsumeDecimalNumber(&suffix, &level) && suffix.empty();
  if (!ok || level >= static_cast<uint64_t>(number_levels_)) {
    return false;
  }
  *value = ToString(
      vstorage->GetEstimatedCompressionRatioAtLevel(static_cast<int>(level)));
  return true;
}

A
Andrew Kryczka 已提交
731
bool InternalStats::HandleLevelStats(std::string* value, Slice /*suffix*/) {
732 733 734 735 736 737
  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 已提交
738

739 740 741 742 743
  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);
744
  }
745
  return true;
746
}
747

748 749 750 751 752 753 754 755 756 757
bool InternalStats::HandleStats(std::string* value, Slice suffix) {
  if (!HandleCFStats(value, suffix)) {
    return false;
  }
  if (!HandleDBStats(value, suffix)) {
    return false;
  }
  return true;
}

758
bool InternalStats::HandleCFMapStats(
759
    std::map<std::string, std::string>* cf_stats, Slice /*suffix*/) {
760 761 762 763
  DumpCFMapStats(cf_stats);
  return true;
}

A
Andrew Kryczka 已提交
764
bool InternalStats::HandleCFStats(std::string* value, Slice /*suffix*/) {
765 766 767 768
  DumpCFStats(value);
  return true;
}

769
bool InternalStats::HandleCFStatsNoFileHistogram(std::string* value,
A
Andrew Kryczka 已提交
770
                                                 Slice /*suffix*/) {
771 772 773 774
  DumpCFStatsNoFileHistogram(value);
  return true;
}

A
Andrew Kryczka 已提交
775 776
bool InternalStats::HandleCFFileHistogram(std::string* value,
                                          Slice /*suffix*/) {
777 778 779 780
  DumpCFFileHistogram(value);
  return true;
}

A
Andrew Kryczka 已提交
781
bool InternalStats::HandleDBStats(std::string* value, Slice /*suffix*/) {
782 783 784 785
  DumpDBStats(value);
  return true;
}

A
Andrew Kryczka 已提交
786
bool InternalStats::HandleSsTables(std::string* value, Slice /*suffix*/) {
S
sdong 已提交
787
  auto* current = cfd_->current();
788
  *value = current->DebugString(true, true);
789 790
  return true;
}
I
Igor Canadi 已提交
791

792
bool InternalStats::HandleAggregatedTableProperties(std::string* value,
A
Andrew Kryczka 已提交
793
                                                    Slice /*suffix*/) {
794 795 796 797
  std::shared_ptr<const TableProperties> tp;
  auto s = cfd_->current()->GetAggregatedTableProperties(&tp);
  if (!s.ok()) {
    return false;
798
  }
799 800
  *value = tp->ToString();
  return true;
801 802
}

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
static std::map<std::string, std::string> MapUint64ValuesToString(
    const std::map<std::string, uint64_t>& from) {
  std::map<std::string, std::string> to;
  for (const auto& e : from) {
    to[e.first] = ToString(e.second);
  }
  return to;
}

bool InternalStats::HandleAggregatedTablePropertiesMap(
    std::map<std::string, std::string>* values, Slice /*suffix*/) {
  std::shared_ptr<const TableProperties> tp;
  auto s = cfd_->current()->GetAggregatedTableProperties(&tp);
  if (!s.ok()) {
    return false;
  }
  *values = MapUint64ValuesToString(tp->GetAggregatablePropertiesAsMap());
  return true;
}

bool InternalStats::HandleAggregatedTablePropertiesAtLevel(std::string* values,
824 825 826 827 828 829 830 831 832 833 834 835
                                                           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;
  }
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
  *values = tp->ToString();
  return true;
}

bool InternalStats::HandleAggregatedTablePropertiesAtLevelMap(
    std::map<std::string, std::string>* values, 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;
  }
  *values = MapUint64ValuesToString(tp->GetAggregatablePropertiesAsMap());
854 855 856
  return true;
}

A
Andrew Kryczka 已提交
857 858
bool InternalStats::HandleNumImmutableMemTable(uint64_t* value, DBImpl* /*db*/,
                                               Version* /*version*/) {
859 860 861 862 863
  *value = cfd_->imm()->NumNotFlushed();
  return true;
}

bool InternalStats::HandleNumImmutableMemTableFlushed(uint64_t* value,
A
Andrew Kryczka 已提交
864 865
                                                      DBImpl* /*db*/,
                                                      Version* /*version*/) {
866 867 868 869
  *value = cfd_->imm()->NumFlushed();
  return true;
}

A
Andrew Kryczka 已提交
870 871
bool InternalStats::HandleMemTableFlushPending(uint64_t* value, DBImpl* /*db*/,
                                               Version* /*version*/) {
872 873 874 875 876
  *value = (cfd_->imm()->IsFlushPending() ? 1 : 0);
  return true;
}

bool InternalStats::HandleNumRunningFlushes(uint64_t* value, DBImpl* db,
A
Andrew Kryczka 已提交
877
                                            Version* /*version*/) {
878 879 880 881
  *value = db->num_running_flushes();
  return true;
}

A
Andrew Kryczka 已提交
882 883
bool InternalStats::HandleCompactionPending(uint64_t* value, DBImpl* /*db*/,
                                            Version* /*version*/) {
884 885
  // 1 if the system already determines at least one compaction is needed.
  // 0 otherwise,
S
sdong 已提交
886
  const auto* vstorage = cfd_->current()->storage_info();
887 888 889
  *value = (cfd_->compaction_picker()->NeedsCompaction(vstorage) ? 1 : 0);
  return true;
}
890

891
bool InternalStats::HandleNumRunningCompactions(uint64_t* value, DBImpl* db,
A
Andrew Kryczka 已提交
892
                                                Version* /*version*/) {
893 894 895 896
  *value = db->num_running_compactions_;
  return true;
}

A
Andrew Kryczka 已提交
897 898
bool InternalStats::HandleBackgroundErrors(uint64_t* value, DBImpl* /*db*/,
                                           Version* /*version*/) {
899 900 901 902 903
  // Accumulated number of  errors in background flushes or compactions.
  *value = GetBackgroundErrorCount();
  return true;
}

A
Andrew Kryczka 已提交
904 905
bool InternalStats::HandleCurSizeActiveMemTable(uint64_t* value, DBImpl* /*db*/,
                                                Version* /*version*/) {
906
  // Current size of the active memtable
907 908
  // Using ApproximateMemoryUsageFast to avoid the need for synchronization
  *value = cfd_->mem()->ApproximateMemoryUsageFast();
909 910 911
  return true;
}

A
Andrew Kryczka 已提交
912 913
bool InternalStats::HandleCurSizeAllMemTables(uint64_t* value, DBImpl* /*db*/,
                                              Version* /*version*/) {
914
  // Current size of the active memtable + immutable memtables
915 916
  // Using ApproximateMemoryUsageFast to avoid the need for synchronization
  *value = cfd_->mem()->ApproximateMemoryUsageFast() +
917 918 919 920
           cfd_->imm()->ApproximateUnflushedMemTablesMemoryUsage();
  return true;
}

A
Andrew Kryczka 已提交
921 922
bool InternalStats::HandleSizeAllMemTables(uint64_t* value, DBImpl* /*db*/,
                                           Version* /*version*/) {
923 924
  // Using ApproximateMemoryUsageFast to avoid the need for synchronization
  *value = cfd_->mem()->ApproximateMemoryUsageFast() +
925 926 927 928
           cfd_->imm()->ApproximateMemoryUsage();
  return true;
}

A
Andrew Kryczka 已提交
929 930 931
bool InternalStats::HandleNumEntriesActiveMemTable(uint64_t* value,
                                                   DBImpl* /*db*/,
                                                   Version* /*version*/) {
932 933 934 935 936
  // Current number of entires in the active memtable
  *value = cfd_->mem()->num_entries();
  return true;
}

A
Andrew Kryczka 已提交
937 938 939
bool InternalStats::HandleNumEntriesImmMemTables(uint64_t* value,
                                                 DBImpl* /*db*/,
                                                 Version* /*version*/) {
940 941 942 943 944
  // Current number of entries in the immutable memtables
  *value = cfd_->imm()->current()->GetTotalNumEntries();
  return true;
}

A
Andrew Kryczka 已提交
945 946 947
bool InternalStats::HandleNumDeletesActiveMemTable(uint64_t* value,
                                                   DBImpl* /*db*/,
                                                   Version* /*version*/) {
948 949 950 951 952
  // Current number of entires in the active memtable
  *value = cfd_->mem()->num_deletes();
  return true;
}

A
Andrew Kryczka 已提交
953 954 955
bool InternalStats::HandleNumDeletesImmMemTables(uint64_t* value,
                                                 DBImpl* /*db*/,
                                                 Version* /*version*/) {
956 957 958 959 960
  // Current number of entries in the immutable memtables
  *value = cfd_->imm()->current()->GetTotalNumDeletes();
  return true;
}

A
Andrew Kryczka 已提交
961 962
bool InternalStats::HandleEstimateNumKeys(uint64_t* value, DBImpl* /*db*/,
                                          Version* /*version*/) {
963 964 965
  // Estimate number of entries in the column family:
  // Use estimated entries in tables + total entries in memtables.
  const auto* vstorage = cfd_->current()->storage_info();
966 967 968 969 970 971 972 973
  uint64_t estimate_keys = cfd_->mem()->num_entries() +
                           cfd_->imm()->current()->GetTotalNumEntries() +
                           vstorage->GetEstimatedActiveKeys();
  uint64_t estimate_deletes =
      cfd_->mem()->num_deletes() + cfd_->imm()->current()->GetTotalNumDeletes();
  *value = estimate_keys > estimate_deletes * 2
               ? estimate_keys - (estimate_deletes * 2)
               : 0;
974 975 976 977
  return true;
}

bool InternalStats::HandleNumSnapshots(uint64_t* value, DBImpl* db,
A
Andrew Kryczka 已提交
978
                                       Version* /*version*/) {
979 980 981 982 983
  *value = db->snapshots().count();
  return true;
}

bool InternalStats::HandleOldestSnapshotTime(uint64_t* value, DBImpl* db,
A
Andrew Kryczka 已提交
984
                                             Version* /*version*/) {
985 986 987 988
  *value = static_cast<uint64_t>(db->snapshots().GetOldestSnapshotTime());
  return true;
}

989 990 991 992 993 994
bool InternalStats::HandleOldestSnapshotSequence(uint64_t* value, DBImpl* db,
                                                 Version* /*version*/) {
  *value = static_cast<uint64_t>(db->snapshots().GetOldestSnapshotSequence());
  return true;
}

A
Andrew Kryczka 已提交
995 996
bool InternalStats::HandleNumLiveVersions(uint64_t* value, DBImpl* /*db*/,
                                          Version* /*version*/) {
997 998 999 1000
  *value = cfd_->GetNumLiveVersions();
  return true;
}

A
Andrew Kryczka 已提交
1001 1002 1003
bool InternalStats::HandleCurrentSuperVersionNumber(uint64_t* value,
                                                    DBImpl* /*db*/,
                                                    Version* /*version*/) {
1004 1005 1006 1007
  *value = cfd_->GetSuperVersionNumber();
  return true;
}

1008
bool InternalStats::HandleIsFileDeletionsEnabled(uint64_t* value, DBImpl* db,
A
Andrew Kryczka 已提交
1009
                                                 Version* /*version*/) {
1010
  *value = db->IsFileDeletionsEnabled() ? 1 : 0;
1011 1012 1013
  return true;
}

A
Andrew Kryczka 已提交
1014 1015
bool InternalStats::HandleBaseLevel(uint64_t* value, DBImpl* /*db*/,
                                    Version* /*version*/) {
1016 1017 1018 1019 1020
  const auto* vstorage = cfd_->current()->storage_info();
  *value = vstorage->base_level();
  return true;
}

1021 1022
bool InternalStats::HandleTotalSstFilesSize(uint64_t* value, DBImpl* /*db*/,
                                            Version* /*version*/) {
1023 1024 1025 1026
  *value = cfd_->GetTotalSstFilesSize();
  return true;
}

1027 1028 1029 1030 1031 1032
bool InternalStats::HandleLiveSstFilesSize(uint64_t* value, DBImpl* /*db*/,
                                           Version* /*version*/) {
  *value = cfd_->GetLiveSstFilesSize();
  return true;
}

1033
bool InternalStats::HandleEstimatePendingCompactionBytes(uint64_t* value,
A
Andrew Kryczka 已提交
1034 1035
                                                         DBImpl* /*db*/,
                                                         Version* /*version*/) {
1036 1037 1038 1039 1040
  const auto* vstorage = cfd_->current()->storage_info();
  *value = vstorage->estimated_compaction_needed_bytes();
  return true;
}

A
Andrew Kryczka 已提交
1041 1042
bool InternalStats::HandleEstimateTableReadersMem(uint64_t* value,
                                                  DBImpl* /*db*/,
1043 1044 1045 1046 1047
                                                  Version* version) {
  *value = (version == nullptr) ? 0 : version->GetMemoryUsageByTableReaders();
  return true;
}

A
Andrew Kryczka 已提交
1048
bool InternalStats::HandleEstimateLiveDataSize(uint64_t* value, DBImpl* /*db*/,
1049 1050
                                               Version* version) {
  const auto* vstorage = version->storage_info();
1051 1052
  *value = vstorage->EstimateLiveDataSize();
  return true;
I
Igor Canadi 已提交
1053 1054
}

1055
bool InternalStats::HandleMinLogNumberToKeep(uint64_t* value, DBImpl* db,
A
Andrew Kryczka 已提交
1056
                                             Version* /*version*/) {
1057 1058 1059 1060
  *value = db->MinLogNumberToKeep();
  return true;
}

1061 1062 1063 1064 1065 1066 1067
bool InternalStats::HandleMinObsoleteSstNumberToKeep(uint64_t* value,
                                                     DBImpl* db,
                                                     Version* /*version*/) {
  *value = db->MinObsoleteSstNumberToKeep();
  return true;
}

1068
bool InternalStats::HandleActualDelayedWriteRate(uint64_t* value, DBImpl* db,
A
Andrew Kryczka 已提交
1069
                                                 Version* /*version*/) {
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
  const WriteController& wc = db->write_controller();
  if (!wc.NeedsDelay()) {
    *value = 0;
  } else {
    *value = wc.delayed_write_rate();
  }
  return true;
}

bool InternalStats::HandleIsWriteStopped(uint64_t* value, DBImpl* db,
A
Andrew Kryczka 已提交
1080
                                         Version* /*version*/) {
1081 1082 1083 1084
  *value = db->write_controller().IsStopped() ? 1 : 0;
  return true;
}

Y
Yi Wu 已提交
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
bool InternalStats::HandleEstimateOldestKeyTime(uint64_t* value, DBImpl* /*db*/,
                                                Version* /*version*/) {
  // TODO(yiwu): The property is currently available for fifo compaction
  // with allow_compaction = false. This is because we don't propagate
  // oldest_key_time on compaction.
  if (cfd_->ioptions()->compaction_style != kCompactionStyleFIFO ||
      cfd_->GetCurrentMutableCFOptions()
          ->compaction_options_fifo.allow_compaction) {
    return false;
  }

  TablePropertiesCollection collection;
  auto s = cfd_->current()->GetPropertiesOfAllTables(&collection);
  if (!s.ok()) {
    return false;
  }
  *value = std::numeric_limits<uint64_t>::max();
  for (auto& p : collection) {
    *value = std::min(*value, p.second->oldest_key_time);
1104 1105 1106
    if (*value == 0) {
      break;
    }
Y
Yi Wu 已提交
1107
  }
1108 1109 1110 1111 1112
  if (*value > 0) {
    *value = std::min({cfd_->mem()->ApproximateOldestKeyTime(),
                       cfd_->imm()->ApproximateOldestKeyTime(), *value});
  }
  return *value > 0 && *value < std::numeric_limits<uint64_t>::max();
Y
Yi Wu 已提交
1113 1114
}

Y
Yi Wu 已提交
1115 1116
bool InternalStats::HandleBlockCacheStat(Cache** block_cache) {
  assert(block_cache != nullptr);
1117
  auto* table_factory = cfd_->ioptions()->table_factory.get();
Y
Yi Wu 已提交
1118
  assert(table_factory != nullptr);
1119 1120 1121
  *block_cache =
      table_factory->GetOptions<Cache>(TableFactory::kBlockCacheOpts());
  return *block_cache != nullptr;
Y
Yi Wu 已提交
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
}

bool InternalStats::HandleBlockCacheCapacity(uint64_t* value, DBImpl* /*db*/,
                                             Version* /*version*/) {
  Cache* block_cache;
  bool ok = HandleBlockCacheStat(&block_cache);
  if (!ok) {
    return false;
  }
  *value = static_cast<uint64_t>(block_cache->GetCapacity());
  return true;
}

bool InternalStats::HandleBlockCacheUsage(uint64_t* value, DBImpl* /*db*/,
                                          Version* /*version*/) {
  Cache* block_cache;
  bool ok = HandleBlockCacheStat(&block_cache);
  if (!ok) {
    return false;
  }
  *value = static_cast<uint64_t>(block_cache->GetUsage());
  return true;
}

bool InternalStats::HandleBlockCachePinnedUsage(uint64_t* value, DBImpl* /*db*/,
                                                Version* /*version*/) {
  Cache* block_cache;
  bool ok = HandleBlockCacheStat(&block_cache);
  if (!ok) {
    return false;
  }
  *value = static_cast<uint64_t>(block_cache->GetPinnedUsage());
  return true;
}

1157 1158 1159
void InternalStats::DumpDBStats(std::string* value) {
  char buf[1000];
  // DB-level stats, only available from default column family
1160
  double seconds_up = (clock_->NowMicros() - started_at_ + 1) / kMicrosInSec;
1161 1162 1163 1164 1165 1166
  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
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
  uint64_t user_bytes_written =
      GetDBStats(InternalStats::kIntStatsBytesWritten);
  uint64_t num_keys_written =
      GetDBStats(InternalStats::kIntStatsNumKeysWritten);
  uint64_t write_other = GetDBStats(InternalStats::kIntStatsWriteDoneByOther);
  uint64_t write_self = GetDBStats(InternalStats::kIntStatsWriteDoneBySelf);
  uint64_t wal_bytes = GetDBStats(InternalStats::kIntStatsWalFileBytes);
  uint64_t wal_synced = GetDBStats(InternalStats::kIntStatsWalFileSynced);
  uint64_t write_with_wal = GetDBStats(InternalStats::kIntStatsWriteWithWal);
  uint64_t write_stall_micros =
      GetDBStats(InternalStats::kIntStatsWriteStallMicros);
1178

1179 1180 1181
  const int kHumanMicrosLen = 32;
  char human_micros[kHumanMicrosLen];

1182
  // Data
S
sdong 已提交
1183 1184
  // writes: total number of write requests.
  // keys: total number of key updates issued by all the write requests
1185 1186
  // commit groups: number of group commits issued to the DB. Each group can
  //                contain one or more writes.
S
sdong 已提交
1187
  // so writes/keys is the average number of put in multi-put or put
1188
  // writes/groups is the average group commit size.
S
sdong 已提交
1189 1190
  //
  // The format is the same for interval stats.
1191
  snprintf(buf, sizeof(buf),
1192 1193
           "Cumulative writes: %s writes, %s keys, %s commit groups, "
           "%.1f writes per commit group, ingest: %.2f GB, %.2f MB/s\n",
1194 1195 1196
           NumberToHumanString(write_other + write_self).c_str(),
           NumberToHumanString(num_keys_written).c_str(),
           NumberToHumanString(write_self).c_str(),
1197
           (write_other + write_self) / static_cast<double>(write_self + 1),
1198
           user_bytes_written / kGB, user_bytes_written / kMB / seconds_up);
1199 1200 1201
  value->append(buf);
  // WAL
  snprintf(buf, sizeof(buf),
1202 1203 1204 1205
           "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(),
1206
           write_with_wal / static_cast<double>(wal_synced + 1),
1207 1208 1209 1210
           wal_bytes / kGB, wal_bytes / kMB / seconds_up);
  value->append(buf);
  // Stall
  AppendHumanMicros(write_stall_micros, human_micros, kHumanMicrosLen, true);
1211
  snprintf(buf, sizeof(buf), "Cumulative stall: %s, %.1f percent\n",
1212 1213 1214
           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));
1215 1216 1217 1218 1219
  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 已提交
1220 1221
  uint64_t interval_num_keys_written =
      num_keys_written - db_stats_snapshot_.num_keys_written;
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
  snprintf(
      buf, sizeof(buf),
      "Interval writes: %s writes, %s keys, %s commit groups, "
      "%.1f writes per commit group, 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(),
      static_cast<double>(interval_write_other + interval_write_self) /
          (interval_write_self + 1),
      (user_bytes_written - db_stats_snapshot_.ingest_bytes) / kMB,
      (user_bytes_written - db_stats_snapshot_.ingest_bytes) / kMB /
          std::max(interval_seconds_up, 0.001)),
      value->append(buf);
1235 1236 1237 1238 1239 1240

  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;

1241 1242 1243
  snprintf(
      buf, sizeof(buf),
      "Interval WAL: %s writes, %s syncs, "
1244
      "%.2f writes per sync, written: %.2f GB, %.2f MB/s\n",
1245 1246 1247 1248 1249
      NumberToHumanString(interval_write_with_wal).c_str(),
      NumberToHumanString(interval_wal_synced).c_str(),
      interval_write_with_wal / static_cast<double>(interval_wal_synced + 1),
      interval_wal_bytes / kGB,
      interval_wal_bytes / kMB / std::max(interval_seconds_up, 0.001));
1250 1251 1252
  value->append(buf);

  // Stall
1253 1254 1255
  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,
1256 1257 1258
           // 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));
1259 1260 1261 1262 1263 1264
  value->append(buf);

  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 已提交
1265
  db_stats_snapshot_.num_keys_written = num_keys_written;
1266 1267 1268
  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 已提交
1269
  db_stats_snapshot_.write_stall_micros = write_stall_micros;
1270 1271
}

1272
/**
1273 1274 1275 1276 1277 1278
 * Dump Compaction Level stats to a map of stat name with "compaction." prefix
 * to value in double as string. The level in stat name is represented with
 * a prefix "Lx" where "x" is the level number. A special level "Sum"
 * represents the sum of a stat for all levels.
 * The result also contains IO stall counters which keys start with "io_stalls."
 * and values represent uint64 encoded as strings.
1279
 */
1280
void InternalStats::DumpCFMapStats(
1281
    std::map<std::string, std::string>* cf_stats) {
1282
  const VersionStorageInfo* vstorage = cfd_->current()->storage_info();
1283
  CompactionStats compaction_stats_sum;
1284
  std::map<int, std::map<LevelStatType, double>> levels_stats;
1285
  DumpCFMapStats(vstorage, &levels_stats, &compaction_stats_sum);
1286 1287 1288 1289 1290 1291
  for (auto const& level_ent : levels_stats) {
    auto level_str =
        level_ent.first == -1 ? "Sum" : "L" + ToString(level_ent.first);
    for (auto const& stat_ent : level_ent.second) {
      auto stat_type = stat_ent.first;
      auto key_str =
1292
          "compaction." + level_str + "." +
1293
          InternalStats::compaction_level_stats.at(stat_type).property_name;
1294
      (*cf_stats)[key_str] = std::to_string(stat_ent.second);
1295 1296
    }
  }
1297 1298

  DumpCFMapStatsIOStalls(cf_stats);
1299 1300
}

1301
void InternalStats::DumpCFMapStats(
1302
    const VersionStorageInfo* vstorage,
1303 1304
    std::map<int, std::map<LevelStatType, double>>* levels_stats,
    CompactionStats* compaction_stats_sum) {
1305
  assert(vstorage);
1306 1307

  int num_levels_to_check =
1308
      (cfd_->ioptions()->compaction_style != kCompactionStyleFIFO)
1309
          ? vstorage->num_levels() - 1
1310
          : 1;
S
sdong 已提交
1311

1312
  // Compaction scores are sorted based on its value. Restore them to the
1313 1314 1315
  // level order
  std::vector<double> compaction_score(number_levels_, 0);
  for (int i = 0; i < num_levels_to_check; ++i) {
1316 1317
    compaction_score[vstorage->CompactionScoreLevel(i)] =
        vstorage->CompactionScore(i);
1318 1319 1320
  }
  // Count # of files being compacted for each level
  std::vector<int> files_being_compacted(number_levels_, 0);
1321
  for (int level = 0; level < number_levels_; ++level) {
1322
    for (auto* f : vstorage->LevelFiles(level)) {
1323 1324 1325 1326 1327 1328 1329 1330 1331
      if (f->being_compacted) {
        ++files_being_compacted[level];
      }
    }
  }

  int total_files = 0;
  int total_files_being_compacted = 0;
  double total_file_size = 0;
1332 1333 1334
  uint64_t flush_ingest = cf_stats_value_[BYTES_FLUSHED];
  uint64_t add_file_ingest = cf_stats_value_[BYTES_INGESTED_ADD_FILE];
  uint64_t curr_ingest = flush_ingest + add_file_ingest;
1335
  for (int level = 0; level < number_levels_; level++) {
S
sdong 已提交
1336
    int files = vstorage->NumLevelFiles(level);
1337 1338 1339
    total_files += files;
    total_files_being_compacted += files_being_compacted[level];
    if (comp_stats_[level].micros > 0 || files > 0) {
1340
      compaction_stats_sum->Add(comp_stats_[level]);
S
sdong 已提交
1341
      total_file_size += vstorage->NumLevelBytes(level);
1342 1343 1344 1345
      uint64_t input_bytes;
      if (level == 0) {
        input_bytes = curr_ingest;
      } else {
1346 1347
        input_bytes = comp_stats_[level].bytes_read_non_output_levels +
                      comp_stats_[level].bytes_read_blob;
1348
      }
1349
      double w_amp =
1350
          (input_bytes == 0)
1351
              ? 0.0
1352 1353
              : static_cast<double>(comp_stats_[level].bytes_written +
                                    comp_stats_[level].bytes_written_blob) /
1354
                    input_bytes;
1355 1356 1357 1358 1359
      std::map<LevelStatType, double> level_stats;
      PrepareLevelStats(&level_stats, files, files_being_compacted[level],
                        static_cast<double>(vstorage->NumLevelBytes(level)),
                        compaction_score[level], w_amp, comp_stats_[level]);
      (*levels_stats)[level] = level_stats;
1360 1361
    }
  }
1362
  // Cumulative summary
1363 1364
  double w_amp = (compaction_stats_sum->bytes_written +
                  compaction_stats_sum->bytes_written_blob) /
1365 1366 1367 1368 1369 1370 1371 1372
                 static_cast<double>(curr_ingest + 1);
  // Stats summary across levels
  std::map<LevelStatType, double> sum_stats;
  PrepareLevelStats(&sum_stats, total_files, total_files_being_compacted,
                    total_file_size, 0, w_amp, *compaction_stats_sum);
  (*levels_stats)[-1] = sum_stats;  //  -1 is for the Sum level
}

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
void InternalStats::DumpCFMapStatsByPriority(
    std::map<int, std::map<LevelStatType, double>>* priorities_stats) {
  for (size_t priority = 0; priority < comp_stats_by_pri_.size(); priority++) {
    if (comp_stats_by_pri_[priority].micros > 0) {
      std::map<LevelStatType, double> priority_stats;
      PrepareLevelStats(&priority_stats, 0 /* num_files */,
                        0 /* being_compacted */, 0 /* total_file_size */,
                        0 /* compaction_score */, 0 /* w_amp */,
                        comp_stats_by_pri_[priority]);
      (*priorities_stats)[static_cast<int>(priority)] = priority_stats;
    }
  }
}

1387 1388 1389
void InternalStats::DumpCFMapStatsIOStalls(
    std::map<std::string, std::string>* cf_stats) {
  (*cf_stats)["io_stalls.level0_slowdown"] =
1390
      std::to_string(cf_stats_count_[L0_FILE_COUNT_LIMIT_SLOWDOWNS]);
1391
  (*cf_stats)["io_stalls.level0_slowdown_with_compaction"] =
1392
      std::to_string(cf_stats_count_[LOCKED_L0_FILE_COUNT_LIMIT_SLOWDOWNS]);
1393
  (*cf_stats)["io_stalls.level0_numfiles"] =
1394
      std::to_string(cf_stats_count_[L0_FILE_COUNT_LIMIT_STOPS]);
1395
  (*cf_stats)["io_stalls.level0_numfiles_with_compaction"] =
1396
      std::to_string(cf_stats_count_[LOCKED_L0_FILE_COUNT_LIMIT_STOPS]);
1397
  (*cf_stats)["io_stalls.stop_for_pending_compaction_bytes"] =
1398
      std::to_string(cf_stats_count_[PENDING_COMPACTION_BYTES_LIMIT_STOPS]);
1399
  (*cf_stats)["io_stalls.slowdown_for_pending_compaction_bytes"] =
1400
      std::to_string(cf_stats_count_[PENDING_COMPACTION_BYTES_LIMIT_SLOWDOWNS]);
1401
  (*cf_stats)["io_stalls.memtable_compaction"] =
1402
      std::to_string(cf_stats_count_[MEMTABLE_LIMIT_STOPS]);
1403
  (*cf_stats)["io_stalls.memtable_slowdown"] =
1404
      std::to_string(cf_stats_count_[MEMTABLE_LIMIT_SLOWDOWNS]);
1405

1406 1407 1408
  uint64_t total_stop = cf_stats_count_[L0_FILE_COUNT_LIMIT_STOPS] +
                        cf_stats_count_[PENDING_COMPACTION_BYTES_LIMIT_STOPS] +
                        cf_stats_count_[MEMTABLE_LIMIT_STOPS];
1409 1410

  uint64_t total_slowdown =
1411 1412 1413
      cf_stats_count_[L0_FILE_COUNT_LIMIT_SLOWDOWNS] +
      cf_stats_count_[PENDING_COMPACTION_BYTES_LIMIT_SLOWDOWNS] +
      cf_stats_count_[MEMTABLE_LIMIT_SLOWDOWNS];
1414 1415 1416 1417 1418

  (*cf_stats)["io_stalls.total_stop"] = std::to_string(total_stop);
  (*cf_stats)["io_stalls.total_slowdown"] = std::to_string(total_slowdown);
}

1419
void InternalStats::DumpCFStats(std::string* value) {
1420 1421 1422 1423 1424
  DumpCFStatsNoFileHistogram(value);
  DumpCFFileHistogram(value);
}

void InternalStats::DumpCFStatsNoFileHistogram(std::string* value) {
J
Jonathan Lee 已提交
1425
  char buf[2000];
1426
  // Per-ColumnFamily stats
1427
  PrintLevelStatsHeader(buf, sizeof(buf), cfd_->GetName(), "Level");
1428 1429 1430
  value->append(buf);

  // Print stats for each level
1431
  const VersionStorageInfo* vstorage = cfd_->current()->storage_info();
1432
  std::map<int, std::map<LevelStatType, double>> levels_stats;
1433
  CompactionStats compaction_stats_sum;
1434
  DumpCFMapStats(vstorage, &levels_stats, &compaction_stats_sum);
1435
  for (int l = 0; l < number_levels_; ++l) {
1436 1437 1438 1439 1440
    if (levels_stats.find(l) != levels_stats.end()) {
      PrintLevelStats(buf, sizeof(buf), "L" + ToString(l), levels_stats[l]);
      value->append(buf);
    }
  }
1441

1442 1443 1444 1445 1446 1447
  // Print sum of level stats
  PrintLevelStats(buf, sizeof(buf), "Sum", levels_stats[-1]);
  value->append(buf);

  uint64_t flush_ingest = cf_stats_value_[BYTES_FLUSHED];
  uint64_t add_file_ingest = cf_stats_value_[BYTES_INGESTED_ADD_FILE];
1448 1449 1450 1451
  uint64_t ingest_files_addfile = cf_stats_value_[INGESTED_NUM_FILES_TOTAL];
  uint64_t ingest_l0_files_addfile =
      cf_stats_value_[INGESTED_LEVEL0_NUM_FILES_TOTAL];
  uint64_t ingest_keys_addfile = cf_stats_value_[INGESTED_NUM_KEYS_TOTAL];
1452
  // Cumulative summary
1453
  uint64_t total_stall_count =
1454 1455 1456 1457 1458 1459
      cf_stats_count_[L0_FILE_COUNT_LIMIT_SLOWDOWNS] +
      cf_stats_count_[L0_FILE_COUNT_LIMIT_STOPS] +
      cf_stats_count_[PENDING_COMPACTION_BYTES_LIMIT_SLOWDOWNS] +
      cf_stats_count_[PENDING_COMPACTION_BYTES_LIMIT_STOPS] +
      cf_stats_count_[MEMTABLE_LIMIT_STOPS] +
      cf_stats_count_[MEMTABLE_LIMIT_SLOWDOWNS];
1460
  // Interval summary
1461 1462 1463
  uint64_t interval_flush_ingest =
      flush_ingest - cf_stats_snapshot_.ingest_bytes_flush;
  uint64_t interval_add_file_inget =
1464
      add_file_ingest - cf_stats_snapshot_.ingest_bytes_addfile;
1465
  uint64_t interval_ingest =
1466
      interval_flush_ingest + interval_add_file_inget + 1;
1467
  CompactionStats interval_stats(compaction_stats_sum);
1468
  interval_stats.Subtract(cf_stats_snapshot_.comp_stats);
1469
  double w_amp =
1470 1471
      (interval_stats.bytes_written + interval_stats.bytes_written_blob) /
      static_cast<double>(interval_ingest);
1472
  PrintLevelStats(buf, sizeof(buf), "Int", 0, 0, 0, 0, w_amp, interval_stats);
1473 1474
  value->append(buf);

1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
  PrintLevelStatsHeader(buf, sizeof(buf), cfd_->GetName(), "Priority");
  value->append(buf);
  std::map<int, std::map<LevelStatType, double>> priorities_stats;
  DumpCFMapStatsByPriority(&priorities_stats);
  for (size_t priority = 0; priority < comp_stats_by_pri_.size(); ++priority) {
    if (priorities_stats.find(static_cast<int>(priority)) !=
        priorities_stats.end()) {
      PrintLevelStats(
          buf, sizeof(buf),
          Env::PriorityToString(static_cast<Env::Priority>(priority)),
          priorities_stats[static_cast<int>(priority)]);
      value->append(buf);
    }
  }

1490 1491 1492 1493 1494 1495
  snprintf(buf, sizeof(buf),
           "\nBlob file count: %" ROCKSDB_PRIszt ", total size: %.1f GB\n\n",
           vstorage->GetBlobFiles().size(),
           vstorage->GetTotalBlobFileSize() / kGB);
  value->append(buf);

1496
  double seconds_up = (clock_->NowMicros() - started_at_ + 1) / kMicrosInSec;
1497 1498 1499 1500
  double interval_seconds_up = seconds_up - cf_stats_snapshot_.seconds_up;
  snprintf(buf, sizeof(buf), "Uptime(secs): %.1f total, %.1f interval\n",
           seconds_up, interval_seconds_up);
  value->append(buf);
1501 1502
  snprintf(buf, sizeof(buf), "Flush(GB): cumulative %.3f, interval %.3f\n",
           flush_ingest / kGB, interval_flush_ingest / kGB);
1503
  value->append(buf);
1504 1505
  snprintf(buf, sizeof(buf), "AddFile(GB): cumulative %.3f, interval %.3f\n",
           add_file_ingest / kGB, interval_add_file_inget / kGB);
1506 1507
  value->append(buf);

1508 1509
  uint64_t interval_ingest_files_addfile =
      ingest_files_addfile - cf_stats_snapshot_.ingest_files_addfile;
1510 1511 1512
  snprintf(buf, sizeof(buf),
           "AddFile(Total Files): cumulative %" PRIu64 ", interval %" PRIu64
           "\n",
1513 1514 1515 1516 1517 1518
           ingest_files_addfile, interval_ingest_files_addfile);
  value->append(buf);

  uint64_t interval_ingest_l0_files_addfile =
      ingest_l0_files_addfile - cf_stats_snapshot_.ingest_l0_files_addfile;
  snprintf(buf, sizeof(buf),
I
Islam AbdelRahman 已提交
1519
           "AddFile(L0 Files): cumulative %" PRIu64 ", interval %" PRIu64 "\n",
1520 1521 1522 1523 1524
           ingest_l0_files_addfile, interval_ingest_l0_files_addfile);
  value->append(buf);

  uint64_t interval_ingest_keys_addfile =
      ingest_keys_addfile - cf_stats_snapshot_.ingest_keys_addfile;
I
Islam AbdelRahman 已提交
1525 1526
  snprintf(buf, sizeof(buf),
           "AddFile(Keys): cumulative %" PRIu64 ", interval %" PRIu64 "\n",
1527 1528 1529
           ingest_keys_addfile, interval_ingest_keys_addfile);
  value->append(buf);

1530 1531 1532 1533 1534 1535
  // Compact
  uint64_t compact_bytes_read = 0;
  uint64_t compact_bytes_write = 0;
  uint64_t compact_micros = 0;
  for (int level = 0; level < number_levels_; level++) {
    compact_bytes_read += comp_stats_[level].bytes_read_output_level +
1536 1537
                          comp_stats_[level].bytes_read_non_output_levels +
                          comp_stats_[level].bytes_read_blob;
1538 1539
    compact_bytes_write += comp_stats_[level].bytes_written +
                           comp_stats_[level].bytes_written_blob;
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
    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",
           compact_bytes_write / kGB, compact_bytes_write / kMB / seconds_up,
           compact_bytes_read / kGB, compact_bytes_read / kMB / seconds_up,
           compact_micros / kMicrosInSec);
  value->append(buf);

  // Compaction interval
  uint64_t interval_compact_bytes_write =
      compact_bytes_write - cf_stats_snapshot_.compact_bytes_write;
  uint64_t interval_compact_bytes_read =
      compact_bytes_read - cf_stats_snapshot_.compact_bytes_read;
  uint64_t interval_compact_micros =
      compact_micros - cf_stats_snapshot_.compact_micros;

  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);
  value->append(buf);
  cf_stats_snapshot_.compact_bytes_write = compact_bytes_write;
  cf_stats_snapshot_.compact_bytes_read = compact_bytes_read;
  cf_stats_snapshot_.compact_micros = compact_micros;

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
  snprintf(buf, sizeof(buf),
           "Stalls(count): %" PRIu64
           " level0_slowdown, "
           "%" PRIu64
           " level0_slowdown_with_compaction, "
           "%" PRIu64
           " level0_numfiles, "
           "%" PRIu64
           " level0_numfiles_with_compaction, "
           "%" PRIu64
           " stop for pending_compaction_bytes, "
           "%" PRIu64
           " slowdown for pending_compaction_bytes, "
           "%" PRIu64
           " memtable_compaction, "
           "%" PRIu64
           " memtable_slowdown, "
           "interval %" PRIu64 " total count\n",
           cf_stats_count_[L0_FILE_COUNT_LIMIT_SLOWDOWNS],
           cf_stats_count_[LOCKED_L0_FILE_COUNT_LIMIT_SLOWDOWNS],
           cf_stats_count_[L0_FILE_COUNT_LIMIT_STOPS],
           cf_stats_count_[LOCKED_L0_FILE_COUNT_LIMIT_STOPS],
           cf_stats_count_[PENDING_COMPACTION_BYTES_LIMIT_STOPS],
           cf_stats_count_[PENDING_COMPACTION_BYTES_LIMIT_SLOWDOWNS],
           cf_stats_count_[MEMTABLE_LIMIT_STOPS],
           cf_stats_count_[MEMTABLE_LIMIT_SLOWDOWNS],
1599
           total_stall_count - cf_stats_snapshot_.stall_count);
1600 1601
  value->append(buf);

1602
  cf_stats_snapshot_.seconds_up = seconds_up;
1603
  cf_stats_snapshot_.ingest_bytes_flush = flush_ingest;
1604 1605 1606 1607
  cf_stats_snapshot_.ingest_bytes_addfile = add_file_ingest;
  cf_stats_snapshot_.ingest_files_addfile = ingest_files_addfile;
  cf_stats_snapshot_.ingest_l0_files_addfile = ingest_l0_files_addfile;
  cf_stats_snapshot_.ingest_keys_addfile = ingest_keys_addfile;
1608
  cf_stats_snapshot_.comp_stats = compaction_stats_sum;
1609
  cf_stats_snapshot_.stall_count = total_stall_count;
1610 1611 1612 1613 1614 1615 1616 1617 1618

  Status s = CollectCacheEntryStats();
  if (s.ok()) {
    value->append(cache_entry_stats.ToString(clock_));
  } else {
    value->append("Block cache: ");
    value->append(s.ToString());
    value->append("\n");
  }
1619 1620
}

1621
void InternalStats::DumpCFFileHistogram(std::string* value) {
1622 1623 1624 1625 1626 1627
  assert(value);
  assert(cfd_);

  std::ostringstream oss;
  oss << "\n** File Read Latency Histogram By Level [" << cfd_->GetName()
      << "] **\n";
1628 1629 1630

  for (int level = 0; level < number_levels_; level++) {
    if (!file_read_latency_[level].Empty()) {
1631 1632
      oss << "** Level " << level << " read latency histogram (micros):\n"
          << file_read_latency_[level].ToString() << '\n';
1633 1634
    }
  }
1635 1636 1637 1638 1639 1640

  if (!blob_file_read_latency_.Empty()) {
    oss << "** Blob file read latency histogram (micros):\n"
        << blob_file_read_latency_.ToString() << '\n';
  }

1641
  value->append(oss.str());
1642
}
1643 1644 1645

#else

1646 1647 1648
const DBPropertyInfo* GetPropertyInfo(const Slice& /*property*/) {
  return nullptr;
}
1649 1650 1651

#endif  // !ROCKSDB_LITE

1652
}  // namespace ROCKSDB_NAMESPACE