forked from facebook/rocksdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block_cache_trace_analyzer.cc
2307 lines (2227 loc) · 92.9 KB
/
block_cache_trace_analyzer.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
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
428
429
430
431
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
528
529
530
531
532
533
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
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// 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).
#ifndef ROCKSDB_LITE
#ifdef GFLAGS
#include "tools/block_cache_analyzer/block_cache_trace_analyzer.h"
#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <random>
#include <sstream>
#include "monitoring/histogram.h"
#include "util/gflags_compat.h"
#include "util/string_util.h"
using GFLAGS_NAMESPACE::ParseCommandLineFlags;
DEFINE_string(block_cache_trace_path, "", "The trace file path.");
DEFINE_bool(is_block_cache_human_readable_trace, false,
"Is the trace file provided for analysis generated by running "
"block_cache_trace_analyzer with "
"FLAGS_human_readable_trace_file_path is specified.");
DEFINE_string(
block_cache_sim_config_path, "",
"The config file path. One cache configuration per line. The format of a "
"cache configuration is "
"cache_name,num_shard_bits,ghost_capacity,cache_capacity_1,...,cache_"
"capacity_N. Supported cache names are lru, lru_priority, lru_hybrid, and "
"lru_hybrid_no_insert_on_row_miss. User may also add a prefix 'ghost_' to "
"a cache_name to add a ghost cache in front of the real cache. "
"ghost_capacity and cache_capacity can be xK, xM or xG where x is a "
"positive number.");
DEFINE_int32(block_cache_trace_downsample_ratio, 1,
"The trace collected accesses on one in every "
"block_cache_trace_downsample_ratio blocks. We scale "
"down the simulated cache size by this ratio.");
DEFINE_bool(print_block_size_stats, false,
"Print block size distribution and the distribution break down by "
"block type and column family.");
DEFINE_bool(print_access_count_stats, false,
"Print access count distribution and the distribution break down "
"by block type and column family.");
DEFINE_bool(print_data_block_access_count_stats, false,
"Print data block accesses by user Get and Multi-Get.");
DEFINE_int32(cache_sim_warmup_seconds, 0,
"The number of seconds to warmup simulated caches. The hit/miss "
"counters are reset after the warmup completes.");
DEFINE_int32(analyze_bottom_k_access_count_blocks, 0,
"Print out detailed access information for blocks with their "
"number of accesses are the bottom k among all blocks.");
DEFINE_int32(analyze_top_k_access_count_blocks, 0,
"Print out detailed access information for blocks with their "
"number of accesses are the top k among all blocks.");
DEFINE_string(block_cache_analysis_result_dir, "",
"The directory that saves block cache analysis results.");
DEFINE_string(
timeline_labels, "",
"Group the number of accesses per block per second using these labels. "
"Possible labels are a combination of the following: cf (column family), "
"sst, level, bt (block type), caller, block. For example, label \"cf_bt\" "
"means the number of access per second is grouped by unique pairs of "
"\"cf_bt\". A label \"all\" contains the aggregated number of accesses per "
"second across all possible labels.");
DEFINE_string(reuse_distance_labels, "",
"Group the reuse distance of a block using these labels. Reuse "
"distance is defined as the cumulated size of unique blocks read "
"between two consecutive accesses on the same block.");
DEFINE_string(
reuse_distance_buckets, "",
"Group blocks by their reuse distances given these buckets. For "
"example, if 'reuse_distance_buckets' is '1K,1M,1G', we will "
"create four buckets. The first three buckets contain the number of "
"blocks with reuse distance less than 1KB, between 1K and 1M, between 1M "
"and 1G, respectively. The last bucket contains the number of blocks with "
"reuse distance larger than 1G. ");
DEFINE_string(
reuse_interval_labels, "",
"Group the reuse interval of a block using these labels. Reuse "
"interval is defined as the time between two consecutive accesses "
"on the same block.");
DEFINE_string(
reuse_interval_buckets, "",
"Group blocks by their reuse interval given these buckets. For "
"example, if 'reuse_distance_buckets' is '1,10,100', we will "
"create four buckets. The first three buckets contain the number of "
"blocks with reuse interval less than 1 second, between 1 second and 10 "
"seconds, between 10 seconds and 100 seconds, respectively. The last "
"bucket contains the number of blocks with reuse interval longer than 100 "
"seconds.");
DEFINE_string(
reuse_lifetime_labels, "",
"Group the reuse lifetime of a block using these labels. Reuse "
"lifetime is defined as the time interval between the first access on a "
"block and the last access on the same block. For blocks that are only "
"accessed once, its lifetime is set to kMaxUint64.");
DEFINE_string(
reuse_lifetime_buckets, "",
"Group blocks by their reuse lifetime given these buckets. For "
"example, if 'reuse_lifetime_buckets' is '1,10,100', we will "
"create four buckets. The first three buckets contain the number of "
"blocks with reuse lifetime less than 1 second, between 1 second and 10 "
"seconds, between 10 seconds and 100 seconds, respectively. The last "
"bucket contains the number of blocks with reuse lifetime longer than 100 "
"seconds.");
DEFINE_string(
analyze_callers, "",
"The list of callers to perform a detailed analysis on. If speicfied, the "
"analyzer will output a detailed percentage of accesses for each caller "
"break down by column family, level, and block type. A list of available "
"callers are: Get, MultiGet, Iterator, ApproximateSize, VerifyChecksum, "
"SSTDumpTool, ExternalSSTIngestion, Repair, Prefetch, Compaction, "
"CompactionRefill, Flush, SSTFileReader, Uncategorized.");
DEFINE_string(access_count_buckets, "",
"Group number of blocks by their access count given these "
"buckets. If specified, the analyzer will output a detailed "
"analysis on the number of blocks grouped by their access count "
"break down by block type and column family.");
DEFINE_int32(analyze_blocks_reuse_k_reuse_window, 0,
"Analyze the percentage of blocks that are accessed in the "
"[k, 2*k] seconds are accessed again in the next [2*k, 3*k], "
"[3*k, 4*k],...,[k*(n-1), k*n] seconds. ");
DEFINE_string(analyze_get_spatial_locality_labels, "",
"Group data blocks using these labels.");
DEFINE_string(analyze_get_spatial_locality_buckets, "",
"Group data blocks by their statistics using these buckets.");
DEFINE_string(skew_labels, "",
"Group the access count of a block using these labels.");
DEFINE_string(skew_buckets, "", "Group the skew labels using these buckets.");
DEFINE_bool(mrc_only, false,
"Evaluate alternative cache policies only. When this flag is true, "
"the analyzer does NOT maintain states of each block in memory for "
"analysis. It only feeds the accesses into the cache simulators.");
DEFINE_string(
analyze_correlation_coefficients_labels, "",
"Analyze the correlation coefficients of features such as number of past "
"accesses with regard to the number of accesses till the next access.");
DEFINE_int32(analyze_correlation_coefficients_max_number_of_values, 1000000,
"The maximum number of values for a feature. If the number of "
"values for a feature is larger than this max, it randomly "
"selects 'max' number of values.");
DEFINE_string(human_readable_trace_file_path, "",
"The filt path that saves human readable access records.");
namespace ROCKSDB_NAMESPACE {
namespace {
const std::string kMissRatioCurveFileName = "mrc";
const std::string kGroupbyBlock = "block";
const std::string kGroupbyTable = "table";
const std::string kGroupbyColumnFamily = "cf";
const std::string kGroupbySSTFile = "sst";
const std::string kGroupbyBlockType = "bt";
const std::string kGroupbyCaller = "caller";
const std::string kGroupbyLevel = "level";
const std::string kGroupbyAll = "all";
const std::set<std::string> kGroupbyLabels{
kGroupbyBlock, kGroupbyColumnFamily, kGroupbySSTFile, kGroupbyLevel,
kGroupbyBlockType, kGroupbyCaller, kGroupbyAll};
const std::string kSupportedCacheNames =
" lru ghost_lru lru_priority ghost_lru_priority lru_hybrid "
"ghost_lru_hybrid lru_hybrid_no_insert_on_row_miss "
"ghost_lru_hybrid_no_insert_on_row_miss ";
// The suffix for the generated csv files.
const std::string kFileNameSuffixMissRatioTimeline = "miss_ratio_timeline";
const std::string kFileNameSuffixMissTimeline = "miss_timeline";
const std::string kFileNameSuffixSkew = "skewness";
const std::string kFileNameSuffixAccessTimeline = "access_timeline";
const std::string kFileNameSuffixCorrelation = "correlation_input";
const std::string kFileNameSuffixAvgReuseIntervalNaccesses =
"avg_reuse_interval_naccesses";
const std::string kFileNameSuffixAvgReuseInterval = "avg_reuse_interval";
const std::string kFileNameSuffixReuseInterval = "access_reuse_interval";
const std::string kFileNameSuffixReuseLifetime = "reuse_lifetime";
const std::string kFileNameSuffixAccessReuseBlocksTimeline =
"reuse_blocks_timeline";
const std::string kFileNameSuffixPercentOfAccessSummary =
"percentage_of_accesses_summary";
const std::string kFileNameSuffixPercentRefKeys = "percent_ref_keys";
const std::string kFileNameSuffixPercentDataSizeOnRefKeys =
"percent_data_size_on_ref_keys";
const std::string kFileNameSuffixPercentAccessesOnRefKeys =
"percent_accesses_on_ref_keys";
const std::string kFileNameSuffixAccessCountSummary = "access_count_summary";
std::string block_type_to_string(TraceType type) {
switch (type) {
case kBlockTraceFilterBlock:
return "Filter";
case kBlockTraceDataBlock:
return "Data";
case kBlockTraceIndexBlock:
return "Index";
case kBlockTraceRangeDeletionBlock:
return "RangeDeletion";
case kBlockTraceUncompressionDictBlock:
return "UncompressionDict";
default:
break;
}
// This cannot happen.
return "InvalidType";
}
std::string caller_to_string(TableReaderCaller caller) {
switch (caller) {
case kUserGet:
return "Get";
case kUserMultiGet:
return "MultiGet";
case kUserIterator:
return "Iterator";
case kUserApproximateSize:
return "ApproximateSize";
case kUserVerifyChecksum:
return "VerifyChecksum";
case kSSTDumpTool:
return "SSTDumpTool";
case kExternalSSTIngestion:
return "ExternalSSTIngestion";
case kRepair:
return "Repair";
case kPrefetch:
return "Prefetch";
case kCompaction:
return "Compaction";
case kCompactionRefill:
return "CompactionRefill";
case kFlush:
return "Flush";
case kSSTFileReader:
return "SSTFileReader";
case kUncategorized:
return "Uncategorized";
default:
break;
}
// This cannot happen.
return "InvalidCaller";
}
TableReaderCaller string_to_caller(std::string caller_str) {
if (caller_str == "Get") {
return kUserGet;
} else if (caller_str == "MultiGet") {
return kUserMultiGet;
} else if (caller_str == "Iterator") {
return kUserIterator;
} else if (caller_str == "ApproximateSize") {
return kUserApproximateSize;
} else if (caller_str == "VerifyChecksum") {
return kUserVerifyChecksum;
} else if (caller_str == "SSTDumpTool") {
return kSSTDumpTool;
} else if (caller_str == "ExternalSSTIngestion") {
return kExternalSSTIngestion;
} else if (caller_str == "Repair") {
return kRepair;
} else if (caller_str == "Prefetch") {
return kPrefetch;
} else if (caller_str == "Compaction") {
return kCompaction;
} else if (caller_str == "CompactionRefill") {
return kCompactionRefill;
} else if (caller_str == "Flush") {
return kFlush;
} else if (caller_str == "SSTFileReader") {
return kSSTFileReader;
} else if (caller_str == "Uncategorized") {
return kUncategorized;
}
return TableReaderCaller::kMaxBlockCacheLookupCaller;
}
bool is_user_access(TableReaderCaller caller) {
switch (caller) {
case kUserGet:
case kUserMultiGet:
case kUserIterator:
case kUserApproximateSize:
case kUserVerifyChecksum:
return true;
default:
break;
}
return false;
}
const char kBreakLine[] =
"***************************************************************\n";
void print_break_lines(uint32_t num_break_lines) {
for (uint32_t i = 0; i < num_break_lines; i++) {
fprintf(stdout, kBreakLine);
}
}
double percent(uint64_t numerator, uint64_t denomenator) {
if (denomenator == 0) {
return -1;
}
return static_cast<double>(numerator * 100.0 / denomenator);
}
std::map<uint64_t, uint64_t> adjust_time_unit(
const std::map<uint64_t, uint64_t>& time_stats, uint64_t time_unit) {
if (time_unit == 1) {
return time_stats;
}
std::map<uint64_t, uint64_t> adjusted_time_stats;
for (auto const& time : time_stats) {
adjusted_time_stats[static_cast<uint64_t>(time.first / time_unit)] +=
time.second;
}
return adjusted_time_stats;
}
} // namespace
void BlockCacheTraceAnalyzer::WriteMissRatioCurves() const {
if (!cache_simulator_) {
return;
}
if (output_dir_.empty()) {
return;
}
uint64_t trace_duration =
trace_end_timestamp_in_seconds_ - trace_start_timestamp_in_seconds_;
uint64_t total_accesses = access_sequence_number_;
const std::string output_miss_ratio_curve_path =
output_dir_ + "/" + std::to_string(trace_duration) + "_" +
std::to_string(total_accesses) + "_" + kMissRatioCurveFileName;
std::ofstream out(output_miss_ratio_curve_path);
if (!out.is_open()) {
return;
}
// Write header.
const std::string header =
"cache_name,num_shard_bits,ghost_capacity,capacity,miss_ratio,total_"
"accesses";
out << header << std::endl;
for (auto const& config_caches : cache_simulator_->sim_caches()) {
const CacheConfiguration& config = config_caches.first;
for (uint32_t i = 0; i < config.cache_capacities.size(); i++) {
double miss_ratio =
config_caches.second[i]->miss_ratio_stats().miss_ratio();
// Write the body.
out << config.cache_name;
out << ",";
out << config.num_shard_bits;
out << ",";
out << config.ghost_cache_capacity;
out << ",";
out << config.cache_capacities[i];
out << ",";
out << std::fixed << std::setprecision(4) << miss_ratio;
out << ",";
out << config_caches.second[i]->miss_ratio_stats().total_accesses();
out << std::endl;
}
}
out.close();
}
void BlockCacheTraceAnalyzer::UpdateFeatureVectors(
const std::vector<uint64_t>& access_sequence_number_timeline,
const std::vector<uint64_t>& access_timeline, const std::string& label,
std::map<std::string, Features>* label_features,
std::map<std::string, Predictions>* label_predictions) const {
if (access_sequence_number_timeline.empty() || access_timeline.empty()) {
return;
}
assert(access_timeline.size() == access_sequence_number_timeline.size());
uint64_t prev_access_sequence_number = access_sequence_number_timeline[0];
uint64_t prev_access_timestamp = access_timeline[0];
for (uint32_t i = 0; i < access_sequence_number_timeline.size(); i++) {
uint64_t num_accesses_since_last_access =
access_sequence_number_timeline[i] - prev_access_sequence_number;
uint64_t elapsed_time_since_last_access =
access_timeline[i] - prev_access_timestamp;
prev_access_sequence_number = access_sequence_number_timeline[i];
prev_access_timestamp = access_timeline[i];
if (i < access_sequence_number_timeline.size() - 1) {
(*label_features)[label].num_accesses_since_last_access.push_back(
num_accesses_since_last_access);
(*label_features)[label].num_past_accesses.push_back(i);
(*label_features)[label].elapsed_time_since_last_access.push_back(
elapsed_time_since_last_access);
}
if (i >= 1) {
(*label_predictions)[label].num_accesses_till_next_access.push_back(
num_accesses_since_last_access);
(*label_predictions)[label].elapsed_time_till_next_access.push_back(
elapsed_time_since_last_access);
}
}
}
void BlockCacheTraceAnalyzer::WriteMissRatioTimeline(uint64_t time_unit) const {
if (!cache_simulator_ || output_dir_.empty()) {
return;
}
std::map<uint64_t, std::map<std::string, std::map<uint64_t, double>>>
cs_name_timeline;
uint64_t start_time = port::kMaxUint64;
uint64_t end_time = 0;
const std::map<uint64_t, uint64_t>& trace_num_misses =
adjust_time_unit(miss_ratio_stats_.num_misses_timeline(), time_unit);
const std::map<uint64_t, uint64_t>& trace_num_accesses =
adjust_time_unit(miss_ratio_stats_.num_accesses_timeline(), time_unit);
assert(trace_num_misses.size() == trace_num_accesses.size());
for (auto const& num_miss : trace_num_misses) {
uint64_t time = num_miss.first;
start_time = std::min(start_time, time);
end_time = std::max(end_time, time);
uint64_t miss = num_miss.second;
auto it = trace_num_accesses.find(time);
assert(it != trace_num_accesses.end());
uint64_t access = it->second;
cs_name_timeline[port::kMaxUint64]["trace"][time] = percent(miss, access);
}
for (auto const& config_caches : cache_simulator_->sim_caches()) {
const CacheConfiguration& config = config_caches.first;
std::string cache_label = config.cache_name + "-" +
std::to_string(config.num_shard_bits) + "-" +
std::to_string(config.ghost_cache_capacity);
for (uint32_t i = 0; i < config.cache_capacities.size(); i++) {
const std::map<uint64_t, uint64_t>& num_misses = adjust_time_unit(
config_caches.second[i]->miss_ratio_stats().num_misses_timeline(),
time_unit);
const std::map<uint64_t, uint64_t>& num_accesses = adjust_time_unit(
config_caches.second[i]->miss_ratio_stats().num_accesses_timeline(),
time_unit);
assert(num_misses.size() == num_accesses.size());
for (auto const& num_miss : num_misses) {
uint64_t time = num_miss.first;
start_time = std::min(start_time, time);
end_time = std::max(end_time, time);
uint64_t miss = num_miss.second;
auto it = num_accesses.find(time);
assert(it != num_accesses.end());
uint64_t access = it->second;
cs_name_timeline[config.cache_capacities[i]][cache_label][time] =
percent(miss, access);
}
}
}
for (auto const& it : cs_name_timeline) {
const std::string output_miss_ratio_timeline_path =
output_dir_ + "/" + std::to_string(it.first) + "_" +
std::to_string(time_unit) + "_" + kFileNameSuffixMissRatioTimeline;
std::ofstream out(output_miss_ratio_timeline_path);
if (!out.is_open()) {
return;
}
std::string header("time");
for (uint64_t now = start_time; now <= end_time; now++) {
header += ",";
header += std::to_string(now);
}
out << header << std::endl;
for (auto const& label : it.second) {
std::string row(label.first);
for (uint64_t now = start_time; now <= end_time; now++) {
auto misses = label.second.find(now);
row += ",";
if (misses != label.second.end()) {
row += std::to_string(misses->second);
} else {
row += "0";
}
}
out << row << std::endl;
}
out.close();
}
}
void BlockCacheTraceAnalyzer::WriteMissTimeline(uint64_t time_unit) const {
if (!cache_simulator_ || output_dir_.empty()) {
return;
}
std::map<uint64_t, std::map<std::string, std::map<uint64_t, uint64_t>>>
cs_name_timeline;
uint64_t start_time = port::kMaxUint64;
uint64_t end_time = 0;
const std::map<uint64_t, uint64_t>& trace_num_misses =
adjust_time_unit(miss_ratio_stats_.num_misses_timeline(), time_unit);
for (auto const& num_miss : trace_num_misses) {
uint64_t time = num_miss.first;
start_time = std::min(start_time, time);
end_time = std::max(end_time, time);
uint64_t miss = num_miss.second;
cs_name_timeline[port::kMaxUint64]["trace"][time] = miss;
}
for (auto const& config_caches : cache_simulator_->sim_caches()) {
const CacheConfiguration& config = config_caches.first;
std::string cache_label = config.cache_name + "-" +
std::to_string(config.num_shard_bits) + "-" +
std::to_string(config.ghost_cache_capacity);
for (uint32_t i = 0; i < config.cache_capacities.size(); i++) {
const std::map<uint64_t, uint64_t>& num_misses = adjust_time_unit(
config_caches.second[i]->miss_ratio_stats().num_misses_timeline(),
time_unit);
for (auto const& num_miss : num_misses) {
uint64_t time = num_miss.first;
start_time = std::min(start_time, time);
end_time = std::max(end_time, time);
uint64_t miss = num_miss.second;
cs_name_timeline[config.cache_capacities[i]][cache_label][time] = miss;
}
}
}
for (auto const& it : cs_name_timeline) {
const std::string output_miss_ratio_timeline_path =
output_dir_ + "/" + std::to_string(it.first) + "_" +
std::to_string(time_unit) + "_" + kFileNameSuffixMissTimeline;
std::ofstream out(output_miss_ratio_timeline_path);
if (!out.is_open()) {
return;
}
std::string header("time");
for (uint64_t now = start_time; now <= end_time; now++) {
header += ",";
header += std::to_string(now);
}
out << header << std::endl;
for (auto const& label : it.second) {
std::string row(label.first);
for (uint64_t now = start_time; now <= end_time; now++) {
auto misses = label.second.find(now);
row += ",";
if (misses != label.second.end()) {
row += std::to_string(misses->second);
} else {
row += "0";
}
}
out << row << std::endl;
}
out.close();
}
}
void BlockCacheTraceAnalyzer::WriteSkewness(
const std::string& label_str, const std::vector<uint64_t>& percent_buckets,
TraceType target_block_type) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, uint64_t> label_naccesses;
uint64_t total_naccesses = 0;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType type,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
if (target_block_type != TraceType::kTraceMax &&
target_block_type != type) {
return;
}
const std::string label = BuildLabel(
labels, cf_name, fd, level, type,
TableReaderCaller::kMaxBlockCacheLookupCaller, block_id, block);
label_naccesses[label] += block.num_accesses;
total_naccesses += block.num_accesses;
};
TraverseBlocks(block_callback, &labels);
std::map<std::string, std::map<uint64_t, uint64_t>> label_bucket_naccesses;
std::vector<std::pair<std::string, uint64_t>> pairs;
for (auto const& itr : label_naccesses) {
pairs.push_back(itr);
}
// Sort in descending order.
sort(pairs.begin(), pairs.end(),
[](const std::pair<std::string, uint64_t>& a,
const std::pair<std::string, uint64_t>& b) {
return b.second < a.second;
});
size_t prev_start_index = 0;
for (auto const& percent : percent_buckets) {
label_bucket_naccesses[label_str][percent] = 0;
size_t end_index = 0;
if (percent == port::kMaxUint64) {
end_index = label_naccesses.size();
} else {
end_index = percent * label_naccesses.size() / 100;
}
for (size_t i = prev_start_index; i < end_index; i++) {
label_bucket_naccesses[label_str][percent] += pairs[i].second;
}
prev_start_index = end_index;
}
std::string filename_suffix;
if (target_block_type != TraceType::kTraceMax) {
filename_suffix = block_type_to_string(target_block_type);
filename_suffix += "_";
}
filename_suffix += kFileNameSuffixSkew;
WriteStatsToFile(label_str, percent_buckets, filename_suffix,
label_bucket_naccesses, total_naccesses);
}
void BlockCacheTraceAnalyzer::WriteCorrelationFeatures(
const std::string& label_str, uint32_t max_number_of_values) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, Features> label_features;
std::map<std::string, Predictions> label_predictions;
auto block_callback =
[&](const std::string& cf_name, uint64_t fd, uint32_t level,
TraceType block_type, const std::string& /*block_key*/,
uint64_t /*block_key_id*/, const BlockAccessInfo& block) {
if (block.table_id == 0 && labels.find(kGroupbyTable) != labels.end()) {
// We only know table id information for get requests.
return;
}
if (labels.find(kGroupbyCaller) != labels.end()) {
// Group by caller.
for (auto const& caller_map : block.caller_access_timeline) {
const std::string label =
BuildLabel(labels, cf_name, fd, level, block_type,
caller_map.first, /*block_id=*/0, block);
auto it = block.caller_access_sequence__number_timeline.find(
caller_map.first);
assert(it != block.caller_access_sequence__number_timeline.end());
UpdateFeatureVectors(it->second, caller_map.second, label,
&label_features, &label_predictions);
}
return;
}
const std::string label =
BuildLabel(labels, cf_name, fd, level, block_type,
TableReaderCaller::kMaxBlockCacheLookupCaller,
/*block_id=*/0, block);
UpdateFeatureVectors(block.access_sequence_number_timeline,
block.access_timeline, label, &label_features,
&label_predictions);
};
TraverseBlocks(block_callback, &labels);
WriteCorrelationFeaturesToFile(label_str, label_features, label_predictions,
max_number_of_values);
}
void BlockCacheTraceAnalyzer::WriteCorrelationFeaturesToFile(
const std::string& label,
const std::map<std::string, Features>& label_features,
const std::map<std::string, Predictions>& label_predictions,
uint32_t max_number_of_values) const {
for (auto const& label_feature_vectors : label_features) {
const Features& past = label_feature_vectors.second;
auto it = label_predictions.find(label_feature_vectors.first);
assert(it != label_predictions.end());
const Predictions& future = it->second;
const std::string output_path = output_dir_ + "/" + label + "_" +
label_feature_vectors.first + "_" +
kFileNameSuffixCorrelation;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header(
"num_accesses_since_last_access,elapsed_time_since_last_access,num_"
"past_accesses,num_accesses_till_next_access,elapsed_time_till_next_"
"access");
out << header << std::endl;
std::vector<uint32_t> indexes;
for (uint32_t i = 0; i < past.num_accesses_since_last_access.size(); i++) {
indexes.push_back(i);
}
RandomShuffle(indexes.begin(), indexes.end());
for (uint32_t i = 0; i < max_number_of_values && i < indexes.size(); i++) {
uint32_t rand_index = indexes[i];
out << std::to_string(past.num_accesses_since_last_access[rand_index])
<< ",";
out << std::to_string(past.elapsed_time_since_last_access[rand_index])
<< ",";
out << std::to_string(past.num_past_accesses[rand_index]) << ",";
out << std::to_string(future.num_accesses_till_next_access[rand_index])
<< ",";
out << std::to_string(future.elapsed_time_till_next_access[rand_index])
<< std::endl;
}
out.close();
}
}
void BlockCacheTraceAnalyzer::WriteCorrelationFeaturesForGet(
uint32_t max_number_of_values) const {
std::string label = "GetKeyInfo";
std::map<std::string, Features> label_features;
std::map<std::string, Predictions> label_predictions;
for (auto const& get_info : get_key_info_map_) {
const GetKeyInfo& info = get_info.second;
UpdateFeatureVectors(info.access_sequence_number_timeline,
info.access_timeline, label, &label_features,
&label_predictions);
}
WriteCorrelationFeaturesToFile(label, label_features, label_predictions,
max_number_of_values);
}
std::set<std::string> BlockCacheTraceAnalyzer::ParseLabelStr(
const std::string& label_str) const {
std::stringstream ss(label_str);
std::set<std::string> labels;
// label_str is in the form of "label1_label2_label3", e.g., cf_bt.
while (ss.good()) {
std::string label_name;
getline(ss, label_name, '_');
if (kGroupbyLabels.find(label_name) == kGroupbyLabels.end()) {
// Unknown label name.
fprintf(stderr, "Unknown label name %s, label string %s\n",
label_name.c_str(), label_str.c_str());
return {};
}
labels.insert(label_name);
}
return labels;
}
std::string BlockCacheTraceAnalyzer::BuildLabel(
const std::set<std::string>& labels, const std::string& cf_name,
uint64_t fd, uint32_t level, TraceType type, TableReaderCaller caller,
uint64_t block_key, const BlockAccessInfo& block) const {
std::map<std::string, std::string> label_value_map;
label_value_map[kGroupbyAll] = kGroupbyAll;
label_value_map[kGroupbyLevel] = std::to_string(level);
label_value_map[kGroupbyCaller] = caller_to_string(caller);
label_value_map[kGroupbySSTFile] = std::to_string(fd);
label_value_map[kGroupbyBlockType] = block_type_to_string(type);
label_value_map[kGroupbyColumnFamily] = cf_name;
label_value_map[kGroupbyBlock] = std::to_string(block_key);
label_value_map[kGroupbyTable] = std::to_string(block.table_id);
// Concatenate the label values.
std::string label;
for (auto const& l : labels) {
label += label_value_map[l];
label += "-";
}
if (!label.empty()) {
label.pop_back();
}
return label;
}
void BlockCacheTraceAnalyzer::TraverseBlocks(
std::function<void(const std::string& /*cf_name*/, uint64_t /*fd*/,
uint32_t /*level*/, TraceType /*block_type*/,
const std::string& /*block_key*/,
uint64_t /*block_key_id*/,
const BlockAccessInfo& /*block_access_info*/)>
block_callback,
std::set<std::string>* labels) const {
for (auto const& cf_aggregates : cf_aggregates_map_) {
// Stats per column family.
const std::string& cf_name = cf_aggregates.first;
for (auto const& file_aggregates : cf_aggregates.second.fd_aggregates_map) {
// Stats per SST file.
const uint64_t fd = file_aggregates.first;
const uint32_t level = file_aggregates.second.level;
for (auto const& block_type_aggregates :
file_aggregates.second.block_type_aggregates_map) {
// Stats per block type.
const TraceType type = block_type_aggregates.first;
for (auto const& block_access_info :
block_type_aggregates.second.block_access_info_map) {
// Stats per block.
if (labels && block_access_info.second.table_id == 0 &&
labels->find(kGroupbyTable) != labels->end()) {
// We only know table id information for get requests.
return;
}
block_callback(cf_name, fd, level, type, block_access_info.first,
block_access_info.second.block_id,
block_access_info.second);
}
}
}
}
}
void BlockCacheTraceAnalyzer::WriteGetSpatialLocality(
const std::string& label_str,
const std::vector<uint64_t>& percent_buckets) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, std::map<uint64_t, uint64_t>> label_pnrefkeys_nblocks;
std::map<std::string, std::map<uint64_t, uint64_t>> label_pnrefs_nblocks;
std::map<std::string, std::map<uint64_t, uint64_t>> label_pndatasize_nblocks;
uint64_t nblocks = 0;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType /*block_type*/,
const std::string& /*block_key*/,
uint64_t /*block_key_id*/,
const BlockAccessInfo& block) {
if (block.num_keys == 0) {
return;
}
uint64_t naccesses = 0;
for (auto const& key_access : block.key_num_access_map) {
for (auto const& caller_access : key_access.second) {
if (caller_access.first == TableReaderCaller::kUserGet) {
naccesses += caller_access.second;
}
}
}
const std::string label =
BuildLabel(labels, cf_name, fd, level, TraceType::kBlockTraceDataBlock,
TableReaderCaller::kUserGet, /*block_id=*/0, block);
const uint64_t percent_referenced_for_existing_keys =
static_cast<uint64_t>(std::max(
percent(block.key_num_access_map.size(), block.num_keys), 0.0));
const uint64_t percent_accesses_for_existing_keys =
static_cast<uint64_t>(std::max(
percent(block.num_referenced_key_exist_in_block, naccesses), 0.0));
const uint64_t percent_referenced_data_size = static_cast<uint64_t>(
std::max(percent(block.referenced_data_size, block.block_size), 0.0));
if (label_pnrefkeys_nblocks.find(label) == label_pnrefkeys_nblocks.end()) {
for (auto const& percent_bucket : percent_buckets) {
label_pnrefkeys_nblocks[label][percent_bucket] = 0;
label_pnrefs_nblocks[label][percent_bucket] = 0;
label_pndatasize_nblocks[label][percent_bucket] = 0;
}
}
label_pnrefkeys_nblocks[label]
.upper_bound(percent_referenced_for_existing_keys)
->second += 1;
label_pnrefs_nblocks[label]
.upper_bound(percent_accesses_for_existing_keys)
->second += 1;
label_pndatasize_nblocks[label]
.upper_bound(percent_referenced_data_size)
->second += 1;
nblocks += 1;
};
TraverseBlocks(block_callback, &labels);
WriteStatsToFile(label_str, percent_buckets, kFileNameSuffixPercentRefKeys,
label_pnrefkeys_nblocks, nblocks);
WriteStatsToFile(label_str, percent_buckets,
kFileNameSuffixPercentAccessesOnRefKeys,
label_pnrefs_nblocks, nblocks);
WriteStatsToFile(label_str, percent_buckets,
kFileNameSuffixPercentDataSizeOnRefKeys,
label_pndatasize_nblocks, nblocks);
}
void BlockCacheTraceAnalyzer::WriteAccessTimeline(const std::string& label_str,
uint64_t time_unit,
bool user_access_only) const {
std::set<std::string> labels = ParseLabelStr(label_str);
uint64_t start_time = port::kMaxUint64;
uint64_t end_time = 0;
std::map<std::string, std::map<uint64_t, uint64_t>> label_access_timeline;
std::map<uint64_t, std::vector<std::string>> access_count_block_id_map;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType type,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
uint64_t naccesses = 0;
for (auto const& timeline : block.caller_num_accesses_timeline) {
const TableReaderCaller caller = timeline.first;
if (user_access_only && !is_user_access(caller)) {
continue;
}
const std::string label =
BuildLabel(labels, cf_name, fd, level, type, caller, block_id, block);
for (auto const& naccess : timeline.second) {
const uint64_t timestamp = naccess.first / time_unit;
const uint64_t num = naccess.second;
label_access_timeline[label][timestamp] += num;
start_time = std::min(start_time, timestamp);
end_time = std::max(end_time, timestamp);
naccesses += num;
}
}
if (naccesses > 0) {
access_count_block_id_map[naccesses].push_back(std::to_string(block_id));
}
};
TraverseBlocks(block_callback, &labels);
// We have label_access_timeline now. Write them into a file.
const std::string user_access_prefix =
user_access_only ? "user_access_only_" : "all_access_";
const std::string output_path = output_dir_ + "/" + user_access_prefix +
label_str + "_" + std::to_string(time_unit) +
"_" + kFileNameSuffixAccessTimeline;
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("time");
if (labels.find("block") != labels.end()) {
for (uint64_t now = start_time; now <= end_time; now++) {
header += ",";
header += std::to_string(now);
}
out << header << std::endl;
// Write the most frequently accessed blocks first.
for (auto naccess_it = access_count_block_id_map.rbegin();
naccess_it != access_count_block_id_map.rend(); naccess_it++) {
for (auto& block_id_it : naccess_it->second) {
std::string row(block_id_it);
for (uint64_t now = start_time; now <= end_time; now++) {
auto it = label_access_timeline[block_id_it].find(now);
row += ",";
if (it != label_access_timeline[block_id_it].end()) {
row += std::to_string(it->second);
} else {
row += "0";
}
}
out << row << std::endl;
}
}
out.close();
return;
}
for (uint64_t now = start_time; now <= end_time; now++) {
header += ",";
header += std::to_string(now);
}
out << header << std::endl;
for (auto const& label : label_access_timeline) {
std::string row(label.first);
for (uint64_t now = start_time; now <= end_time; now++) {
auto it = label.second.find(now);
row += ",";
if (it != label.second.end()) {
row += std::to_string(it->second);
} else {
row += "0";
}
}
out << row << std::endl;
}
out.close();
}
void BlockCacheTraceAnalyzer::WriteReuseDistance(
const std::string& label_str,
const std::vector<uint64_t>& distance_buckets) const {
std::set<std::string> labels = ParseLabelStr(label_str);
std::map<std::string, std::map<uint64_t, uint64_t>> label_distance_num_reuses;
uint64_t total_num_reuses = 0;
auto block_callback = [&](const std::string& cf_name, uint64_t fd,
uint32_t level, TraceType type,
const std::string& /*block_key*/, uint64_t block_id,
const BlockAccessInfo& block) {
const std::string label = BuildLabel(
labels, cf_name, fd, level, type,
TableReaderCaller::kMaxBlockCacheLookupCaller, block_id, block);
if (label_distance_num_reuses.find(label) ==
label_distance_num_reuses.end()) {
// The first time we encounter this label.
for (auto const& distance_bucket : distance_buckets) {
label_distance_num_reuses[label][distance_bucket] = 0;
}
}
for (auto const& reuse_distance : block.reuse_distance_count) {
label_distance_num_reuses[label]
.upper_bound(reuse_distance.first)
->second += reuse_distance.second;
total_num_reuses += reuse_distance.second;
}
};
TraverseBlocks(block_callback, &labels);
// We have label_naccesses and label_distance_num_reuses now. Write them into
// a file.
const std::string output_path =
output_dir_ + "/" + label_str + "_reuse_distance";
std::ofstream out(output_path);
if (!out.is_open()) {
return;
}
std::string header("bucket");
for (auto const& label_it : label_distance_num_reuses) {
header += ",";
header += label_it.first;
}
out << header << std::endl;
for (auto const& bucket : distance_buckets) {
std::string row(std::to_string(bucket));
for (auto const& label_it : label_distance_num_reuses) {
auto const& it = label_it.second.find(bucket);
assert(it != label_it.second.end());
row += ",";
row += std::to_string(percent(it->second, total_num_reuses));
}
out << row << std::endl;
}
out.close();