-
Notifications
You must be signed in to change notification settings - Fork 562
Expand file tree
/
Copy pathcompaction.go
More file actions
1588 lines (1422 loc) · 48.1 KB
/
compaction.go
File metadata and controls
1588 lines (1422 loc) · 48.1 KB
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 2021 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package logs
import (
"bufio"
"bytes"
"cmp"
"fmt"
"math"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/ascii"
"github.com/cockroachdb/pebble/internal/ascii/table"
"github.com/cockroachdb/pebble/internal/manifest"
"github.com/spf13/cobra"
)
const numLevels = manifest.NumLevels
var (
compactionTable = table.Define[compactionTableRow](
table.String("kind", 7, table.AlignLeft, func(r compactionTableRow) string { return r.Kind }),
table.Div(),
table.String("from", 4, table.AlignRight, func(r compactionTableRow) string { return r.From }),
table.Div(),
table.String("to", 3, table.AlignRight, func(r compactionTableRow) string { return r.To }),
table.Div(),
table.Int("def", 3, table.AlignRight, func(r compactionTableRow) int { return r.Default }),
table.Div(),
table.Int("move", 4, table.AlignRight, func(r compactionTableRow) int { return r.Move }),
table.Div(),
table.Int("elide", 5, table.AlignRight, func(r compactionTableRow) int { return r.Elide }),
table.Div(),
table.Int("del", 3, table.AlignRight, func(r compactionTableRow) int { return r.Delete }),
table.Div(),
table.Int("blob", 4, table.AlignRight, func(r compactionTableRow) int { return r.Blob }),
table.Div(),
table.Int("virt", 4, table.AlignRight, func(r compactionTableRow) int { return r.Virtual }),
table.Div(),
table.Int("copy", 4, table.AlignRight, func(r compactionTableRow) int { return r.Copy }),
table.Div(),
table.Int("tomb", 4, table.AlignRight, func(r compactionTableRow) int { return r.Tombstone }),
table.Div(),
table.Int("rwrt", 4, table.AlignRight, func(r compactionTableRow) int { return r.Rewrite }),
table.Div(),
table.Int("cnt", 3, table.AlignRight, func(r compactionTableRow) int { return r.Count }),
table.Div(),
table.Bytes("in(B)", 5, table.AlignRight, func(r compactionTableRow) uint64 { return r.BytesIn }),
table.Div(),
table.Bytes("out(B)", 6, table.AlignRight, func(r compactionTableRow) uint64 { return r.BytesOut }),
table.Div(),
table.Bytes("mov(B)", 6, table.AlignRight, func(r compactionTableRow) uint64 { return r.BytesMoved }),
table.Div(),
table.Bytes("del(B)", 6, table.AlignRight, func(r compactionTableRow) uint64 { return r.BytesDel }),
table.Div(),
table.String("time", 4, table.AlignRight, func(r compactionTableRow) string { return r.Duration }),
)
flushIngestTable = table.Define[flushIngestTableRow](
table.String("kind", 7, table.AlignLeft, func(r flushIngestTableRow) string { return r.Kind }),
table.Div(),
table.String("from", 4, table.AlignRight, func(r flushIngestTableRow) string { return r.From }),
table.Div(),
table.String("to", 3, table.AlignRight, func(r flushIngestTableRow) string { return r.To }),
table.Div(),
table.Int("cnt", 3, table.AlignRight, func(r flushIngestTableRow) int { return r.Count }),
table.Div(),
table.Bytes("bytes", 5, table.AlignRight, func(r flushIngestTableRow) uint64 { return r.Bytes }),
table.Div(),
table.String("time", 4, table.AlignRight, func(r flushIngestTableRow) string { return r.Duration }),
)
longRunningTable = table.Define[longRunningTableRow](
table.String("kind", 7, table.AlignLeft, func(r longRunningTableRow) string { return r.Kind }),
table.Div(),
table.String("from", 4, table.AlignRight, func(r longRunningTableRow) string { return r.From }),
table.Div(),
table.String("to", 3, table.AlignRight, func(r longRunningTableRow) string { return r.To }),
table.Div(),
table.Int("job", 4, table.AlignRight, func(r longRunningTableRow) int { return r.Job }),
table.Div(),
table.String("type", 6, table.AlignRight, func(r longRunningTableRow) string { return r.Type }),
table.Div(),
table.String("start", 7, table.AlignRight, func(r longRunningTableRow) string { return r.Start }),
table.Div(),
table.String("end", 7, table.AlignRight, func(r longRunningTableRow) string { return r.End }),
table.Div(),
table.Float("dur(s)", 7, table.AlignRight, func(r longRunningTableRow) float64 { return r.DurationSeconds }),
table.Div(),
table.Bytes("bytes", 5, table.AlignRight, func(r longRunningTableRow) uint64 { return r.Bytes }),
)
)
type compactionTableRow struct {
Kind string
From string
To string
Default int
Move int
Elide int
Delete int
Blob int
Virtual int
Copy int
Tombstone int
Rewrite int
Count int
BytesIn uint64
BytesOut uint64
BytesMoved uint64
BytesDel uint64
Duration string
}
type flushIngestTableRow struct {
Kind string
From string
To string
Count int
Bytes uint64
Duration string
}
type longRunningTableRow struct {
Kind string
From string
To string
Job int
Type string
Start string
End string
DurationSeconds float64
Bytes uint64
}
var (
// Captures a common logging prefix that can be used as the context for the
// surrounding information captured by other expressions. Example:
//
// I211215 14:26:56.012382 51831533 3@vendor/github.com/cockroachdb/pebble/compaction.go:1845 ⋮ [T1,n5,pebble,s5] ...
//
logContextPattern = regexp.MustCompile(
`^.*` +
/* Timestamp */ `(?P<timestamp>\d{6} \d{2}:\d{2}:\d{2}.\d{6}).*` +
/* Node / Store */ `\[(T(\d+|\?),)?n(?P<node>\d+|\?).*,s(?P<store>\d+|\?).*?\].*`,
)
logContextPatternTimestampIdx = logContextPattern.SubexpIndex("timestamp")
logContextPatternNodeIdx = logContextPattern.SubexpIndex("node")
logContextPatternStoreIdx = logContextPattern.SubexpIndex("store")
// Matches either a compaction or a memtable flush log line.
//
// A compaction start / end line resembles:
// "[JOB X] compact(ed|ing)"
//
// A memtable flush start / end line resembles:
// "[JOB X] flush(ed|ing)"
//
// An ingested sstable flush looks like:
// "[JOB 226] flushed 6 ingested flushables"
sentinelPattern = regexp.MustCompile(`\[JOB.*(?P<prefix>compact|flush|ingest)(?P<suffix>ed|ing)[^:]`)
sentinelPatternPrefixIdx = sentinelPattern.SubexpIndex("prefix")
sentinelPatternSuffixIdx = sentinelPattern.SubexpIndex("suffix")
// Example compaction start and end log lines:
// 23.1 and older:
// I211215 14:26:56.012382 51831533 3@vendor/github.com/cockroachdb/pebble/compaction.go:1845 ⋮ [n5,pebble,s5] 1216510 [JOB 284925] compacting(default) L2 [442555] (4.2 M) + L3 [445853] (8.4 M)
// I211215 14:26:56.318543 51831533 3@vendor/github.com/cockroachdb/pebble/compaction.go:1886 ⋮ [n5,pebble,s5] 1216554 [JOB 284925] compacted(default) L2 [442555] (4.2 M) + L3 [445853] (8.4 M) -> L3 [445883 445887] (13 M), in 0.3s, output rate 42 M/s
// current:
// I211215 14:26:56.012382 51831533 3@vendor/github.com/cockroachdb/pebble/compaction.go:1845 ⋮ [n5,pebble,s5] 1216510 [JOB 284925] compacting(default) L2 [442555] (4.2MB) + L3 [445853] (8.4MB)
// I211215 14:26:56.318543 51831533 3@vendor/github.com/cockroachdb/pebble/compaction.go:1886 ⋮ [n5,pebble,s5] 1216554 [JOB 284925] compacted(default) L2 [442555] (4.2MB) + L3 [445853] (8.4MB) -> L3 [445883 445887] (13MB), in 0.3s, output rate 42MB/s
//
// NOTE: we use the log timestamp to compute the compaction duration rather
// than the Pebble log output.
compactionPattern = regexp.MustCompile(
`^.*` +
/* Job ID */ `\[JOB (?P<job>\d+)]\s` +
/* Start / end */ `compact(?P<suffix>ed|ing)` +
/* Compaction type */
`\((?P<type>.*?)\)\s` +
/* Optional annotation*/ `?(\s*\[(?P<annotations>.*?)\]\s*)?` +
/* Start / end level */
`(?P<levels>L(?P<from>\d).*?(?:.*(?:\+|->)\sL(?P<to>\d))?` +
/* Bytes */
`(?:.*?\((?P<bytes>[0-9.]+( [BKMGTPE]|[KMGTPE]?B))\))` +
/* Score */
`?(\s*(Score=\d+(\.\d+)))?)`,
)
compactionPatternJobIdx = compactionPattern.SubexpIndex("job")
compactionPatternSuffixIdx = compactionPattern.SubexpIndex("suffix")
compactionPatternTypeIdx = compactionPattern.SubexpIndex("type")
compactionPatternLevels = compactionPattern.SubexpIndex("levels")
compactionPatternFromIdx = compactionPattern.SubexpIndex("from")
compactionPatternToIdx = compactionPattern.SubexpIndex("to")
compactionPatternBytesIdx = compactionPattern.SubexpIndex("bytes")
// Example memtable flush log lines:
// 23.1 and older:
// I211213 16:23:48.903751 21136 3@vendor/github.com/cockroachdb/pebble/event.go:599 ⋮ [n9,pebble,s9] 24 [JOB 10] flushing 2 memtables to L0
// I211213 16:23:49.134464 21136 3@vendor/github.com/cockroachdb/pebble/event.go:603 ⋮ [n9,pebble,s9] 26 [JOB 10] flushed 2 memtables to L0 [1535806] (1.3 M), in 0.2s, output rate 5.8 M/s
// current:
// I211213 16:23:48.903751 21136
// 3@vendor/github.com/cockroachdb/pebble/event.go:599 ⋮ [n9,pebble,s9] 24 [JOB 10] flushing 2 memtables (1.4MB) to L0
// I211213 16:23:49.134464 21136
// 3@vendor/github.com/cockroachdb/pebble/event.go:603 ⋮ [n9,pebble,s9] 26 [JOB 10] flushed 2 memtables (1.4MB) to L0 [1535806] (1.3MB), in 0.2s, output rate 5.8MB/s
//
// NOTE: we use the log timestamp to compute the flush duration rather than
// the Pebble log output.
flushPattern = regexp.MustCompile(
`^..*` +
/* Job ID */ `\[JOB (?P<job>\d+)]\s` +
/* Compaction type */ `flush(?P<suffix>ed|ing)\s` +
/* Memtable count; size (23.2+) */ `\d+ memtables? (\([^)]+\))?` +
/* SSTable Bytes */ `(?:.*?\((?P<bytes>[0-9.]+( [BKMGTPE]|[KMGTPE]?B))\))?`,
)
flushPatternSuffixIdx = flushPattern.SubexpIndex("suffix")
flushPatternJobIdx = flushPattern.SubexpIndex("job")
flushPatternBytesIdx = flushPattern.SubexpIndex("bytes")
// Example ingested log lines:
// 23.1 and older:
// I220228 16:01:22.487906 18476248525 3@vendor/github.com/cockroachdb/pebble/ingest.go:637 ⋮ [n24,pebble,s24] 33430782 [JOB 10211226] ingested L0:21818678 (1.8 K), L0:21818683 (1.2 K), L0:21818679 (1.6 K), L0:21818680 (1.1 K), L0:21818681 (1.1 K), L0:21818682 (160 M)
// current:
// I220228 16:01:22.487906 18476248525 3@vendor/github.com/cockroachdb/pebble/ingest.go:637 ⋮ [n24,pebble,s24] 33430782 [JOB 10211226] ingested L0:21818678 (1.8KB), L0:21818683 (1.2KB), L0:21818679 (1.6KB), L0:21818680 (1.1KB), L0:21818681 (1.1KB), L0:21818682 (160MB)
//
ingestedPattern = regexp.MustCompile(
`^.*` +
/* Job ID */ `\[JOB (?P<job>\d+)]\s` +
/* ingested */ `ingested\s`)
ingestedPatternJobIdx = ingestedPattern.SubexpIndex("job")
ingestedFilePattern = regexp.MustCompile(
`L` +
/* Level */ `(?P<level>\d):` +
/* File number */ `(?P<file>\d+)\s` +
/* Bytes */ `\((?P<bytes>[0-9.]+( [BKMGTPE]|[KMGTPE]?B))\)`)
ingestedFilePatternLevelIdx = ingestedFilePattern.SubexpIndex("level")
ingestedFilePatternFileIdx = ingestedFilePattern.SubexpIndex("file")
ingestedFilePatternBytesIdx = ingestedFilePattern.SubexpIndex("bytes")
// flushable ingestions
//
// I230831 04:13:28.824280 3780 3@pebble/event.go:685 ⋮ [n10,s10,pebble] 365 [JOB 226] flushed 6 ingested flushables L0:024334 (1.5KB) + L0:024339 (1.0KB) + L0:024335 (1.9KB) + L0:024336 (1.1KB) + L0:024337 (1.1KB) + L0:024338 (12KB) in 0.0s (0.0s total), output rate 67MB/s
flushableIngestedPattern = regexp.MustCompile(
`^.*` +
/* Job ID */ `\[JOB (?P<job>\d+)]\s` +
/* match ingested flushable */ `flushed \d ingested flushable`)
flushableIngestedPatternJobIdx = flushableIngestedPattern.SubexpIndex("job")
// Example read-amp log line:
// 23.1 and older:
// total 31766 188 G - 257 G 187 G 48 K 3.6 G 744 536 G 49 K 278 G 5 2.1
// current:
// total | 1 639B 0B | - | 84B | 0 0B | 0 0B | 3 1.9KB | 1.2KB | 1 23.7
readAmpPattern = regexp.MustCompile(
/* Read amp */ `(?:^|\+)(?:\s{2}total|total \|).*?\s(?P<value>\d+)\s.{4,7}$`,
)
readAmpPatternValueIdx = readAmpPattern.SubexpIndex("value")
// Example blob file rewrite start and end log lines:
// I211215 14:26:56.318543 51831533 3@vendor/github.com/cockroachdb/pebble/compaction.go:1886 ⋮ [n5,pebble,s5] 1216554 [JOB 284925] rewrote blob file (B000006, 000006) (209B) -> (B000006, 000010) (203B), in 0.2s (0.35s total)
blobRewritePattern = regexp.MustCompile(
`^.*` +
/* Job ID */ `\[JOB (?P<job>\d+)]\s` +
/* Match rewrite end logs only */ `rewrote blob file\s` +
/* Physical file number before rewrite */
`\([^,]+,\s*(?P<physicalFileBefore>\d+)\)\s+` +
/* Size before rewrite */ `\((?P<sizeBefore>[0-9.]+(?: [BKMGTPE]|[KMGTPE]?B))\)\s*` +
`->\s*` +
/* Physical file number after rewrite */ `\([^,]+,\s*(?P<physicalFileAfter>\d+)\)\s+` +
/* Size after rewrite */ `\((?P<sizeAfter>[0-9.]+(?: [BKMGTPE]|[KMGTPE]?B))\)` +
/* Total time */ `(?:.*?in\s[0-9.]+s\s\((?P<totalTime>[0-9.]+)s\s+total\))?`,
)
blobRewritePatternJobIdx = blobRewritePattern.SubexpIndex("job")
blobRewritePatternPhysicalFileBeforeIdx = blobRewritePattern.SubexpIndex("physicalFileBefore")
blobRewritePatternPhysicalFileAfterIdx = blobRewritePattern.SubexpIndex("physicalFileAfter")
blobRewritePatternSizeBeforeIdx = blobRewritePattern.SubexpIndex("sizeBefore")
blobRewritePatternSizeAfterIdx = blobRewritePattern.SubexpIndex("sizeAfter")
blobRewritePatternTotalTimeIdx = blobRewritePattern.SubexpIndex("totalTime")
)
const (
// timeFmt matches the Cockroach log timestamp format.
// See: https://github.com/cockroachdb/cockroach/blob/master/pkg/util/log/format_crdb_v2.go
timeFmt = "060102 15:04:05.000000"
// timeFmtSlim is similar to timeFmt, except that it strips components with a
// lower granularity than a minute.
timeFmtSlim = "060102 15:04"
// timeFmtHrMinSec prints only the hour, minute and second of the time.
timeFmtHrMinSec = "15:04:05"
)
// compactionType is the type of compaction. It tracks the types in
// compaction.go. We copy the values here to avoid exporting the types in
// compaction.go.
type compactionType uint8
const (
compactionTypeDefault compactionType = iota
compactionTypeFlush
compactionTypeMove
compactionTypeCopy
compactionTypeDeleteOnly
compactionTypeElisionOnly
compactionTypeRead
compactionTypeTombstoneDensity
compactionTypeRewrite
compactionTypeBlobRewrite
compactionTypeVirtualRewrite
)
// String implements fmt.Stringer.
func (c compactionType) String() string {
switch c {
case compactionTypeDefault:
return "default"
case compactionTypeMove:
return "move"
case compactionTypeCopy:
return "copy"
case compactionTypeDeleteOnly:
return "delete-only"
case compactionTypeElisionOnly:
return "elision-only"
case compactionTypeRead:
return "read"
case compactionTypeTombstoneDensity:
return "tombstone-density"
case compactionTypeRewrite:
return "rewrite"
case compactionTypeBlobRewrite:
return "blob-rewrite"
case compactionTypeVirtualRewrite:
return "virtual-sst-rewrite"
default:
panic(errors.Newf("unknown compaction type: %s", c))
}
}
// parseCompactionType parses the given compaction type string and returns a
// compactionType.
func parseCompactionType(s string) (t compactionType, err error) {
switch s {
case "default":
t = compactionTypeDefault
case "move":
t = compactionTypeMove
case "copy":
t = compactionTypeCopy
case "delete-only":
t = compactionTypeDeleteOnly
case "elision-only":
t = compactionTypeElisionOnly
case "read":
t = compactionTypeRead
case "tombstone-density":
t = compactionTypeTombstoneDensity
case "rewrite":
t = compactionTypeRewrite
case "blob-rewrite":
t = compactionTypeBlobRewrite
case "virtual-sst-rewrite":
t = compactionTypeVirtualRewrite
default:
err = errors.Newf("unknown compaction type: %s", s)
}
return
}
// compactionStart is a compaction start event.
type compactionStart struct {
ctx logContext
jobID int
cType compactionType
fromLevel int
toLevel int
inputBytes uint64
// Blob-specific fields (only used when cType == compactionTypeBlobRewrite).
physicalFileIDBefore int
}
// parseCompactionStart converts the given regular expression sub-matches for a
// compaction start log line into a compactionStart event.
func parseCompactionStart(matches []string) (compactionStart, error) {
var start compactionStart
// Parse job ID.
jobID, err := strconv.Atoi(matches[compactionPatternJobIdx])
if err != nil {
return start, errors.Newf("could not parse jobID: %s", err)
}
// Parse compaction type.
cType, err := parseCompactionType(matches[compactionPatternTypeIdx])
if err != nil {
return start, err
}
// Parse input bytes.
inputBytes, err := sumInputBytes(matches[compactionPatternLevels])
if err != nil {
return start, errors.Newf("could not sum input bytes: %s", err)
}
// Parse from-level.
from, err := strconv.Atoi(matches[compactionPatternFromIdx])
if err != nil {
return start, errors.Newf("could not parse from-level: %s", err)
}
// Parse to-level. For deletion and elision compactions, set the same level.
to := from
if cType != compactionTypeElisionOnly && cType != compactionTypeDeleteOnly {
to, err = strconv.Atoi(matches[compactionPatternToIdx])
if err != nil {
return start, errors.Newf("could not parse to-level: %s", err)
}
}
start = compactionStart{
jobID: jobID,
cType: cType,
fromLevel: from,
toLevel: to,
inputBytes: inputBytes,
}
return start, nil
}
// compactionEnd is a compaction end event.
type compactionEnd struct {
jobID int
writtenBytes uint64
// TODO(jackson): Parse and include the aggregate size of input
// sstables. It may be instructive, because compactions that drop
// keys write less data than they remove from the input level.
// Blob-specific fields (only used when cType == compactionTypeBlobRewrite).
physicalFileIDAfter int
duration time.Duration
}
// parseCompactionEnd converts the given regular expression sub-matches for a
// compaction end log line into a compactionEnd event.
func parseCompactionEnd(matches []string) (compactionEnd, error) {
var end compactionEnd
// Parse job ID.
jobID, err := strconv.Atoi(matches[compactionPatternJobIdx])
if err != nil {
return end, errors.Newf("could not parse jobID: %s", err)
}
end = compactionEnd{jobID: jobID}
// Optionally, if we have compacted bytes.
if matches[compactionPatternBytesIdx] != "" {
end.writtenBytes = unHumanize(matches[compactionPatternBytesIdx])
}
return end, nil
}
// parseFlushStart converts the given regular expression sub-matches for a
// memtable flush start log line into a compactionStart event.
func parseFlushStart(matches []string) (compactionStart, error) {
var start compactionStart
// Parse job ID.
jobID, err := strconv.Atoi(matches[flushPatternJobIdx])
if err != nil {
return start, errors.Newf("could not parse jobID: %s", err)
}
c := compactionStart{
jobID: jobID,
cType: compactionTypeFlush,
fromLevel: -1,
toLevel: 0,
}
return c, nil
}
// parseFlushEnd converts the given regular expression sub-matches for a
// memtable flush end log line into a compactionEnd event.
func parseFlushEnd(matches []string) (compactionEnd, error) {
var end compactionEnd
// Parse job ID.
jobID, err := strconv.Atoi(matches[flushPatternJobIdx])
if err != nil {
return end, errors.Newf("could not parse jobID: %s", err)
}
end = compactionEnd{jobID: jobID}
// Optionally, if we have flushed bytes.
if matches[flushPatternBytesIdx] != "" {
end.writtenBytes = unHumanize(matches[flushPatternBytesIdx])
}
return end, nil
}
// event describes an aggregated event (eg, start and end events
// combined if necessary).
type event struct {
nodeID int
storeID int
jobID int
timeStart time.Time
timeEnd time.Time
compaction *compaction
ingest *ingest
}
// compaction represents an aggregated compaction event (i.e. the combination of
// a start and end event).
type compaction struct {
cType compactionType
fromLevel int
toLevel int
inputBytes uint64
outputBytes uint64
// Blob-specific fields (only used when cType == compactionTypeBlobRewrite).
physicalFileIDBefore int
physicalFileIDAfter int
duration time.Duration
}
// ingest describes the completion of an ingest.
type ingest struct {
files []ingestedFile
}
type ingestedFile struct {
level int
fileNum int
sizeBytes uint64
}
// readAmp represents a read-amp event.
type readAmp struct {
ctx logContext
readAmp int
}
type nodeStoreJob struct {
node, store, job int
}
func (n nodeStoreJob) String() string {
return fmt.Sprintf("(node=%d,store=%d,job=%d)", n.node, n.store, n.job)
}
type errorEvent struct {
path string
line string
err error
}
// logEventCollector keeps track of open compaction events and read-amp events
// over the course of parsing log line events. Completed compaction events are
// added to the collector once a matching start and end pair are encountered.
// Read-amp events are added as they are encountered (the have no start / end
// concept).
type logEventCollector struct {
ctx logContext
m map[nodeStoreJob]compactionStart
events []event
readAmps []readAmp
errors []errorEvent
}
// newEventCollector instantiates a new logEventCollector.
func newEventCollector() *logEventCollector {
return &logEventCollector{
m: make(map[nodeStoreJob]compactionStart),
}
}
// addError records an error encountered during log parsing.
func (c *logEventCollector) addError(path, line string, err error) {
c.errors = append(c.errors, errorEvent{path: path, line: line, err: err})
}
// addCompactionStart adds a new compactionStart to the collector. The event is
// tracked by its job ID.
func (c *logEventCollector) addCompactionStart(start compactionStart) error {
key := nodeStoreJob{c.ctx.node, c.ctx.store, start.jobID}
if _, ok := c.m[key]; ok {
return errors.Newf("start event already seen for %s", key)
}
start.ctx = c.ctx
c.m[key] = start
return nil
}
// addCompactionEnd completes the compaction event for the given compactionEnd.
func (c *logEventCollector) addCompactionEnd(end compactionEnd) {
key := nodeStoreJob{c.ctx.node, c.ctx.store, end.jobID}
start, ok := c.m[key]
if !ok {
_, _ = fmt.Fprintf(
os.Stderr,
"compaction end event missing start event for %s; skipping\n", key,
)
return
}
// Remove the job from the collector once it has been matched.
delete(c.m, key)
comp := &compaction{
cType: start.cType,
fromLevel: start.fromLevel,
toLevel: start.toLevel,
inputBytes: start.inputBytes,
outputBytes: end.writtenBytes,
}
// Add blob-specific fields if this is a blob rewrite.
if start.cType == compactionTypeBlobRewrite {
comp.physicalFileIDBefore = start.physicalFileIDBefore
comp.physicalFileIDAfter = end.physicalFileIDAfter
comp.duration = end.duration
}
c.events = append(c.events, event{
nodeID: start.ctx.node,
storeID: start.ctx.store,
jobID: start.jobID,
timeStart: start.ctx.timestamp,
timeEnd: c.ctx.timestamp,
compaction: comp,
})
}
// addReadAmp adds the readAmp event to the collector.
func (c *logEventCollector) addReadAmp(ra readAmp) {
ra.ctx = c.ctx
c.readAmps = append(c.readAmps, ra)
}
// logContext captures the metadata of log lines.
type logContext struct {
timestamp time.Time
node, store int
}
// saveContext saves the given logContext in the collector.
func (c *logEventCollector) saveContext(ctx logContext) {
c.ctx = ctx
}
// level is a level in the LSM. The WAL is level -1.
type level int
// String implements fmt.Stringer.
func (l level) String() string {
if l == -1 {
return "WAL"
}
if l == -2 {
return "BLOB"
}
return "L" + strconv.Itoa(int(l))
}
// fromTo is a map key for (from, to) level tuples.
type fromTo struct {
from, to level
}
// compactionTypeCount is a mapping from compaction type to count.
type compactionTypeCount map[compactionType]int
// windowSummary summarizes events in a window of time between a start and end
// time. The window tracks:
// - for each compaction type: counts, total bytes compacted, and total duration.
// - total ingested bytes for each level
// - read amp magnitudes
type windowSummary struct {
nodeID, storeID int
tStart, tEnd time.Time
eventCount int
flushedCount int
flushedBytes uint64
flushedTime time.Duration
compactionCounts map[fromTo]compactionTypeCount
compactionBytesIn map[fromTo]uint64
compactionBytesOut map[fromTo]uint64
compactionBytesMoved map[fromTo]uint64
compactionBytesDel map[fromTo]uint64
compactionTime map[fromTo]time.Duration
ingestedCount [numLevels]int
ingestedBytes [numLevels]uint64
readAmps []readAmp
longRunning []event
}
// String implements fmt.Stringer, returning a formatted window summary.
func (s windowSummary) String() string {
type fromToCount struct {
ft fromTo
counts compactionTypeCount
bytesIn uint64
bytesOut uint64
bytesMoved uint64
bytesDel uint64
duration time.Duration
}
var pairs []fromToCount
for k, v := range s.compactionCounts {
pairs = append(pairs, fromToCount{
ft: k,
counts: v,
bytesIn: s.compactionBytesIn[k],
bytesOut: s.compactionBytesOut[k],
bytesMoved: s.compactionBytesMoved[k],
bytesDel: s.compactionBytesDel[k],
duration: s.compactionTime[k],
})
}
slices.SortFunc(pairs, func(l, r fromToCount) int {
if v := cmp.Compare(l.ft.from, r.ft.from); v != 0 {
return v
}
return cmp.Compare(l.ft.to, r.ft.to)
})
nodeID, storeID := "?", "?"
if s.nodeID != -1 {
nodeID = strconv.Itoa(s.nodeID)
}
if s.storeID != -1 {
storeID = strconv.Itoa(s.storeID)
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("node: %s, store: %s\n", nodeID, storeID))
sb.WriteString(fmt.Sprintf(" from: %s\n", s.tStart.Format(timeFmtSlim)))
sb.WriteString(fmt.Sprintf(" to: %s\n", s.tEnd.Format(timeFmtSlim)))
var count, sum int
for _, ra := range s.readAmps {
count++
sum += ra.readAmp
}
sb.WriteString(fmt.Sprintf(" r-amp: %.1f\n", float64(sum)/float64(count)))
sb.WriteString("\n")
// Print flush+ingest statistics.
{
var flushIngestRows []flushIngestTableRow
var totalCount, totalBytes int
var totalTime time.Duration
if s.flushedCount > 0 {
flushIngestRows = append(flushIngestRows, flushIngestTableRow{
Kind: "flush",
From: "",
To: "L0",
Count: s.flushedCount,
Bytes: s.flushedBytes,
Duration: s.flushedTime.Truncate(time.Second).String(),
})
totalCount += s.flushedCount
totalBytes += int(s.flushedBytes)
totalTime += s.flushedTime
}
for l := 0; l < len(s.ingestedBytes); l++ {
if s.ingestedCount[l] == 0 {
continue
}
flushIngestRows = append(flushIngestRows, flushIngestTableRow{
Kind: "ingest",
From: "",
To: fmt.Sprintf("L%d", l),
Count: s.ingestedCount[l],
Bytes: s.ingestedBytes[l],
Duration: "",
})
totalCount += s.ingestedCount[l]
totalBytes += int(s.ingestedBytes[l])
}
if len(flushIngestRows) > 0 {
flushIngestRows = append(flushIngestRows, flushIngestTableRow{
Kind: "total",
From: "",
To: "",
Count: totalCount,
Bytes: uint64(totalBytes),
Duration: totalTime.Truncate(time.Second).String(),
})
board := ascii.Make(20, 1)
flushIngestTable.Render(board.At(0, 0), table.RenderOptions{}, flushIngestRows...)
sb.WriteString(board.String())
sb.WriteString("\n\n")
}
}
// Print compactions statistics.
if len(s.compactionCounts) > 0 {
var compactionRows []compactionTableRow
var totalDef, totalMove, totalElision, totalDel, totalBlob, totalVirtual, totalCopy, totalTombstone, totalRewrite int
var totalBytesIn, totalBytesOut, totalBytesMoved, totalBytesDel uint64
var totalTime time.Duration
for _, p := range pairs {
def := p.counts[compactionTypeDefault]
move := p.counts[compactionTypeMove]
elision := p.counts[compactionTypeElisionOnly]
del := p.counts[compactionTypeDeleteOnly]
blob := p.counts[compactionTypeBlobRewrite]
virtual := p.counts[compactionTypeVirtualRewrite]
copy := p.counts[compactionTypeCopy]
tombstone := p.counts[compactionTypeTombstoneDensity]
rewrite := p.counts[compactionTypeRewrite]
total := def + move + elision + del + blob + virtual + copy + tombstone + rewrite
compactionRows = append(compactionRows, compactionTableRow{
Kind: "compact",
From: p.ft.from.String(),
To: p.ft.to.String(),
Default: def,
Move: move,
Elide: elision,
Delete: del,
Blob: blob,
Virtual: virtual,
Copy: copy,
Tombstone: tombstone,
Rewrite: rewrite,
Count: total,
BytesIn: p.bytesIn,
BytesOut: p.bytesOut,
BytesMoved: p.bytesMoved,
BytesDel: p.bytesDel,
Duration: p.duration.Truncate(time.Second).String(),
})
totalDef += def
totalMove += move
totalElision += elision
totalDel += del
totalBlob += blob
totalVirtual += virtual
totalCopy += copy
totalTombstone += tombstone
totalRewrite += rewrite
totalBytesIn += p.bytesIn
totalBytesOut += p.bytesOut
totalBytesMoved += p.bytesMoved
totalBytesDel += p.bytesDel
totalTime += p.duration
}
compactionRows = append(compactionRows, compactionTableRow{
Kind: "total",
From: "",
To: "",
Default: totalDef,
Move: totalMove,
Elide: totalElision,
Delete: totalDel,
Blob: totalBlob,
Virtual: totalVirtual,
Copy: totalCopy,
Tombstone: totalTombstone,
Rewrite: totalRewrite,
Count: s.eventCount,
BytesIn: totalBytesIn,
BytesOut: totalBytesOut,
BytesMoved: totalBytesMoved,
BytesDel: totalBytesDel,
Duration: totalTime.Truncate(time.Second).String(),
})
board := ascii.Make(20, 1)
compactionTable.Render(board.At(0, 0), table.RenderOptions{}, compactionRows...)
sb.WriteString(board.String())
sb.WriteString("\n\n")
}
// (Optional) Long running events.
if len(s.longRunning) > 0 {
sb.WriteString("long-running events (descending runtime):\n")
var longRunningRows []longRunningTableRow
for _, e := range s.longRunning {
if e.compaction != nil {
c := e.compaction
kind := "compact"
if c.fromLevel == -1 {
kind = "flush"
} else if c.fromLevel == -2 {
kind = "blob"
} else if c.cType == compactionTypeVirtualRewrite {
kind = "virtual"
}
longRunningRows = append(longRunningRows, longRunningTableRow{
Kind: kind,
From: level(c.fromLevel).String(),
To: level(c.toLevel).String(),
Job: e.jobID,
Type: c.cType.String(),
Start: e.timeStart.Format(timeFmtHrMinSec),
End: e.timeEnd.Format(timeFmtHrMinSec),
DurationSeconds: e.timeEnd.Sub(e.timeStart).Seconds(),
Bytes: c.outputBytes,
})
}
}
board := ascii.Make(20, 1)
longRunningTable.Render(board.At(0, 0), table.RenderOptions{}, longRunningRows...)
sb.WriteString(board.String())
sb.WriteString("\n\n")
}
return sb.String()
}
// windowSummarySlice is a slice of windowSummary that sorts in order of start
// time, node, then store.
type windowsSummarySlice []windowSummary
func (s windowsSummarySlice) Len() int {
return len(s)
}
func (s windowsSummarySlice) Less(i, j int) bool {
if !s[i].tStart.Equal(s[j].tStart) {
return s[i].tStart.Before(s[j].tStart)
}
if s[i].nodeID != s[j].nodeID {
return s[i].nodeID < s[j].nodeID
}
return s[i].storeID < s[j].storeID
}
func (s windowsSummarySlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// eventSlice is a slice of events that sorts in order of node, store,
// then event start time.
type eventSlice []event
func (s eventSlice) Len() int {
return len(s)
}
func (s eventSlice) Less(i, j int) bool {
if s[i].nodeID != s[j].nodeID {
return s[i].nodeID < s[j].nodeID
}
if s[i].storeID != s[j].storeID {
return s[i].storeID < s[j].storeID
}
return s[i].timeStart.Before(s[j].timeStart)
}
func (s eventSlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// readAmpSlice is a slice of readAmp events that sorts in order of node, store,
// then read amp event start time.
type readAmpSlice []readAmp
func (r readAmpSlice) Len() int {
return len(r)
}
func (r readAmpSlice) Less(i, j int) bool {
// Sort by node, store, then read-amp.
if r[i].ctx.node != r[j].ctx.node {
return r[i].ctx.node < r[j].ctx.node
}
if r[i].ctx.store != r[j].ctx.store {
return r[i].ctx.store < r[j].ctx.store
}
return r[i].ctx.timestamp.Before(r[j].ctx.timestamp)
}