/
stats_manager.go
4030 lines (3432 loc) · 124 KB
/
stats_manager.go
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 2014-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package indexer
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"math"
"net/http"
"path"
"path/filepath"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/couchbase/indexing/secondary/audit"
"github.com/couchbase/indexing/secondary/common"
commonjson "github.com/couchbase/indexing/secondary/common/json"
"github.com/couchbase/indexing/secondary/iowrap"
"github.com/couchbase/indexing/secondary/logging"
"github.com/couchbase/indexing/secondary/stats"
"github.com/couchbase/indexing/secondary/stubs/nitro/mm"
"github.com/couchbase/logstats/logstats"
"github.com/golang/snappy"
)
var uptime time.Time // time this package was loaded; used as indexer boot time
const APPROX_METRIC_SIZE = 100
const APPROX_METRIC_COUNT = 25
var METRICS_PREFIX = "index_"
// 0-2ms, 2ms-5ms, 5ms-10ms, 10ms-20ms, 20ms-30ms, 30ms-50ms, 50ms-100ms, 100ms-Inf
var latencyDist = []int64{0, 2, 5, 10, 20, 30, 50, 100}
// 0-2ms, 2ms-5ms, 5ms-10ms, 10ms-20ms, 20ms-30ms, 30ms-50ms, 50ms-100ms, 100ms-1000ms,
// 1000ms-5000ms, 5000ms-10000ms, 10000ms-Inf
var snapLatencyDist = []int64{0, 2, 5, 10, 20, 30, 50, 100, 1000, 5000, 10000}
// end-end scan request latency
// 0-2ms, 2ms-5ms, 5ms-10ms, 10ms-20ms, 20ms-30ms, 30ms-50ms, 50ms-100ms, 100ms-1000ms,
// 1000ms-5000ms, 5000ms-10000ms, 10000ms-50000ms, 50000ms-Inf
var scanReqLatencyDist = []int64{0, 2, 5, 10, 20, 30, 50, 100, 1000, 5000, 10000, 50000}
var isJemallocProfilingActive int64
func init() {
uptime = time.Now()
}
// KeyspaceStats tracks statistics of all indexes in a given keyspace in a stream.
// It is used internally for debugging and available in unspecified format under the
// "GET /api/v1/stats" REST API but is not used by the UI.
type KeyspaceStats struct {
keyspaceId string
// Statistics in alphabetical order
avgDcpSnapSize stats.Uint64Val
mutationQueueSize stats.Int64Val
numMutationsQueued stats.Int64Val
numNonAlignTS stats.Int64Val
numRollbacks stats.Int64Val
numRollbacksToZero stats.Int64Val
tsQueueSize stats.Int64Val
flushLatDist stats.Histogram
snapLatDist stats.Histogram
lastSnapDone stats.Int64Val
numForceInMemSnap stats.Int64Val
}
// KeyspaceStats.Init initializes a per-keyspace stats object.
func (s *KeyspaceStats) Init(keyspaceId string) {
s.keyspaceId = keyspaceId
s.numRollbacks.Init()
s.numRollbacksToZero.Init()
s.mutationQueueSize.Init()
s.numMutationsQueued.Init()
s.tsQueueSize.Init()
s.numNonAlignTS.Init()
s.avgDcpSnapSize.Init()
s.flushLatDist.InitLatency(latencyDist, func(v int64) string { return fmt.Sprintf("%vms", v/int64(time.Millisecond)) })
s.snapLatDist.InitLatency(snapLatencyDist, func(v int64) string { return fmt.Sprintf("%vms", v/int64(time.Millisecond)) })
s.lastSnapDone.Init()
s.numForceInMemSnap.Init()
}
func (s *KeyspaceStats) addKeyspaceStatsToStatsMap(statMap *StatsMap) {
statMap.AddStatValueFiltered("num_rollbacks", &s.numRollbacks)
statMap.AddStatValueFiltered("num_rollbacks_to_zero", &s.numRollbacksToZero)
statMap.AddStatValueFiltered("mutation_queue_size", &s.mutationQueueSize)
statMap.AddStatValueFiltered("num_mutations_queued", &s.numMutationsQueued)
statMap.AddStatValueFiltered("ts_queue_size", &s.tsQueueSize)
statMap.AddStatValueFiltered("num_nonalign_ts", &s.numNonAlignTS)
statMap.AddStatValueFiltered("avg_dcp_snap_size", &s.avgDcpSnapSize)
statMap.AddStatValueFiltered("flush_latency_dist", &s.flushLatDist)
statMap.AddStatValueFiltered("snapshot_latency_dist", &s.snapLatDist)
statMap.AddStatValueFiltered("last_snapshot_done", &s.lastSnapDone)
statMap.AddStatValueFiltered("num_force_inmem_snap", &s.numForceInMemSnap)
bucket := GetBucketFromKeyspaceId(s.keyspaceId)
if st := common.BucketSeqsTiming(bucket); st != nil {
statMap.AddStatValueFiltered("timings/dcp_getseqs", st)
}
}
type IndexTimingStats struct {
stCloneHandle stats.TimingStat
stNewIterator stats.TimingStat
stIteratorNext stats.TimingStat
stSnapshotCreate stats.TimingStat
stSnapshotClose stats.TimingStat
stPersistSnapshotCreate stats.TimingStat
stScanPipelineIterate stats.TimingStat
stCommit stats.TimingStat
stKVGet stats.TimingStat
stKVSet stats.TimingStat
stKVDelete stats.TimingStat
stKVInfo stats.TimingStat
stKVMetaGet stats.TimingStat
stKVMetaSet stats.TimingStat
dcpSeqs stats.TimingStat
n1qlExpr stats.TimingStat
}
func (it *IndexTimingStats) Init() {
it.stCloneHandle.Init()
it.stCommit.Init()
it.stNewIterator.Init()
it.stSnapshotCreate.Init()
it.stSnapshotClose.Init()
it.stPersistSnapshotCreate.Init()
it.stKVGet.Init()
it.stKVSet.Init()
it.stIteratorNext.Init()
it.stScanPipelineIterate.Init()
it.stKVDelete.Init()
it.stKVInfo.Init()
it.stKVMetaGet.Init()
it.stKVMetaSet.Init()
it.dcpSeqs.Init()
it.n1qlExpr.Init()
}
// IndexStats holds statistics for a single index instance. If it is non-partitioned,
// its stats will be in the IndexStats struct itself. If it is partitioned, the stats
// will instead be stored per partition in its partitions map field.
type IndexStats struct {
name, scope, collection, bucket, dispName string
indexState stats.Uint64Val
replicaId int
isArrayIndex bool
useArrItemsCount bool
partitions map[common.PartitionId]*IndexStats
scanDuration stats.Int64Val
scanReqDuration stats.Int64Val
scanReqInitDuration stats.Int64Val
scanReqAllocDuration stats.Int64Val
dcpSeqsDuration stats.Int64Val
insertBytes stats.Int64Val
numDocsPending stats.Int64Val
scanWaitDuration stats.Int64Val
numDocsIndexed stats.Int64Val
numDocsProcessed stats.Int64Val
numRequests stats.Int64Val
lastScanTime stats.Int64Val
numCompletedRequests stats.Int64Val
numRowsReturned stats.Int64Val
numRequestsRange stats.Int64Val
numCompletedRequestsRange stats.Int64Val
numRowsReturnedRange stats.Int64Val
numRowsScannedRange stats.Int64Val
scanCacheHitRange stats.Int64Val
numRequestsAggr stats.Int64Val
numCompletedRequestsAggr stats.Int64Val
numRowsReturnedAggr stats.Int64Val
numRowsScannedAggr stats.Int64Val
scanCacheHitAggr stats.Int64Val
numRowsScanned stats.Int64Val
numStrictConsReqs stats.Int64Val
diskSize stats.Int64Val
memUsed stats.Int64Val
buildProgress stats.Int64Val
completionProgress stats.Int64Val
numDocsQueued stats.Int64Val
deleteBytes stats.Int64Val
dataSize stats.Int64Val
dataSizeOnDisk stats.Int64Val
logSpaceOnDisk stats.Int64Val
rawDataSize stats.Int64Val // Sum of all data inserted into main store and back store
backstoreRawDataSize stats.Int64Val // Sum of all data inserted into back store
docidCount stats.Int64Val
scanBytesRead stats.Int64Val
getBytes stats.Int64Val
itemsCount stats.Int64Val
arrItemsCount stats.Int64Val // used only for array indexes counter maintained at GSI layer
numDiskSnapshots stats.Int64Val // # snapshots still available on disk
numCommits stats.Int64Val // # snapshots ever written to disk
numSnapshots stats.Int64Val // # snapshots ever created, including both disk and memory-only
numOpenSnapshots stats.Int64Val
numCompactions stats.Int64Val
numItemsFlushed stats.Int64Val
avgTsInterval stats.Int64Val
avgTsItemsCount stats.Int64Val
lastNumFlushQueued stats.Int64Val
lastTsTime stats.Int64Val
numDocsFlushQueued stats.Int64Val
fragPercent stats.Int64Val
sinceLastSnapshot stats.Int64Val
numSnapshotWaiters stats.Int64Val
numLastSnapshotReply stats.Int64Val
numItemsRestored stats.Int64Val
diskSnapStoreDuration stats.Int64Val
diskSnapLoadDuration stats.Int64Val
notReadyError stats.Int64Val
clientCancelError stats.Int64Val
numScanTimeouts stats.Int64Val
numScanErrors stats.Int64Val
avgScanRate stats.Int64Val
avgMutationRate stats.Int64Val
avgDrainRate stats.Int64Val
avgDiskBps stats.Int64Val
lastScanGatherTime stats.Int64Val
lastNumRowsScanned stats.Int64Val
lastMutateGatherTime stats.Int64Val
lastNumDocsIndexed stats.Int64Val
lastNumItemsFlushed stats.Int64Val
lastDiskBytes stats.Int64Val
lastRollbackTime stats.TimeVal
progressStatTime stats.TimeVal
residentPercent stats.Int64Val // resident ratio for mainstore
combinedResidentPercent stats.Int64Val // resident ratio for mainstore and backstore
cacheHitPercent stats.Int64Val
cacheHits stats.Int64Val
cacheMisses stats.Int64Val
numRecsInMem stats.Int64Val
numRecsOnDisk stats.Int64Val
numKeySize64 stats.Int64Val // 0 - 64
numKeySize256 stats.Int64Val // 65 - 256
numKeySize1K stats.Int64Val // 257 - 1K
numKeySize4K stats.Int64Val // 1025 to 4096
numKeySize100K stats.Int64Val // 4097 - 102400
numKeySizeGt100K stats.Int64Val // > 102400
numArrayKeySize64 stats.Int64Val
numArrayKeySize256 stats.Int64Val
numArrayKeySize1K stats.Int64Val
numArrayKeySize4K stats.Int64Val
numArrayKeySize100K stats.Int64Val
numArrayKeySizeGt100K stats.Int64Val
keySizeStatsSince stats.Int64Val // Since when are key size stats tracked
//stats needed for avg_scan_latency
lastScanDuration stats.Int64Val
lastNumRequests stats.Int64Val
avgScanLatency stats.Int64Val
Timings IndexTimingStats
// Placeholder stats used during GetStats call.
flushQueue stats.Int64Val
avgItemSize stats.Int64Val
waitLat stats.Int64Val
scanReqLat stats.Int64Val
scanReqInitLat stats.Int64Val
scanReqAllocLat stats.Int64Val
docidCountHolder stats.Int64Val
avgArrLenHolder stats.Int64Val
keySizeDist stats.MapVal
arrKeySizeDist stats.MapVal
scanReqInitLatDist stats.Histogram
scanReqWaitLatDist stats.Histogram
scanReqLatDist stats.Histogram
snapGenLatDist stats.Histogram
}
type IndexerStatsHolder struct {
ptr unsafe.Pointer // *IndexerStats
}
func (h *IndexerStatsHolder) Get() *IndexerStats {
return (*IndexerStats)(atomic.LoadPointer(&h.ptr))
}
func (h *IndexerStatsHolder) Set(s *IndexerStats) {
atomic.StorePointer(&h.ptr, unsafe.Pointer(s))
}
func (h *IndexerStatsHolder) GetKeyspaceStats(streamId common.StreamId, keyspaceId string) *KeyspaceStats {
return h.GetKeyspaceStatsMap()[streamId][keyspaceId]
}
func (h *IndexerStatsHolder) GetKeyspaceStatsMap() KeyspaceStatsMap {
return h.Get().GetKeyspaceStatsMap()
}
func (s *IndexerStats) GetKeyspaceStats(streamId common.StreamId, keyspaceId string) *KeyspaceStats {
return s.GetKeyspaceStatsMap()[streamId][keyspaceId]
}
func (s *IndexerStats) GetKeyspaceStatsMap() KeyspaceStatsMap {
return s.keyspaceStatsMap.Get()
}
// KeyspaceStatsMap holds a map of stream IDs to maps of keyspace IDs to per-keyspace
// stats. The outer map avoids key collisions between streams. Only INIT_STREAM
// and MAINT_STREAM have entries as other streams do not keep these stats. These two
// stream maps are always present (see NewKeyspaceStatsMap immediately below). The
// code should never try to get a map for any other stream, and nil is not checked
// for lookups of the streamId dimension.
type KeyspaceStatsMap map[common.StreamId]map[string]*KeyspaceStats
func NewKeyspaceStatsMap() KeyspaceStatsMap {
var ksm KeyspaceStatsMap = make(map[common.StreamId]map[string]*KeyspaceStats)
ksm[common.INIT_STREAM] = make(map[string]*KeyspaceStats)
ksm[common.MAINT_STREAM] = make(map[string]*KeyspaceStats)
return ksm
}
// KeyspaceStatsMapHolder holds an atomic pointer to a KeyspaceStatsMap.
type KeyspaceStatsMapHolder struct {
ptr unsafe.Pointer
}
func (h *KeyspaceStatsMapHolder) Init() {
h.Set(NewKeyspaceStatsMap())
}
func (h *KeyspaceStatsMapHolder) Get() KeyspaceStatsMap {
return *(*KeyspaceStatsMap)(atomic.LoadPointer(&h.ptr))
}
func (h *KeyspaceStatsMapHolder) Set(s KeyspaceStatsMap) {
atomic.StorePointer(&h.ptr, unsafe.Pointer(&s))
}
type LatencyMapHolder struct {
ptr *unsafe.Pointer
}
func (p *LatencyMapHolder) Init() {
p.ptr = new(unsafe.Pointer)
}
func (p *LatencyMapHolder) Set(prjLatencyMap map[string]interface{}) {
atomic.StorePointer(p.ptr, unsafe.Pointer(&prjLatencyMap))
}
func (p *LatencyMapHolder) Get() map[string]interface{} {
if ptr := atomic.LoadPointer(p.ptr); ptr != nil {
return *(*map[string]interface{})(ptr)
} else {
return make(map[string]interface{})
}
}
func (p *LatencyMapHolder) Clone() map[string]interface{} {
if ptr := atomic.LoadPointer(p.ptr); ptr != nil {
currMap := *(*map[string]interface{})(ptr)
clone := make(map[string]interface{})
for k, v := range currMap {
clone[k] = v
}
return clone
} else {
return make(map[string]interface{})
}
}
// Contains the mapping between nodeUUID to hostname of a KV node
type NodeToHostMapHolder struct {
ptr *unsafe.Pointer
}
func (n *NodeToHostMapHolder) Init() {
n.ptr = new(unsafe.Pointer)
}
func (n *NodeToHostMapHolder) Set(nodeToHostMap map[string]string) {
atomic.StorePointer(n.ptr, unsafe.Pointer(&nodeToHostMap))
}
func (n *NodeToHostMapHolder) Get() map[string]string {
if ptr := atomic.LoadPointer(n.ptr); ptr != nil {
return *(*map[string]string)(ptr)
} else {
return make(map[string]string)
}
}
type ShardTransferStatistics struct {
shardId common.ShardId
totalBytes int64
bytesWritten int64
transferRate float64
}
func (s *IndexStats) Init() {
s.indexState.Init()
s.scanDuration.Init()
s.scanReqDuration.Init()
s.scanReqInitDuration.Init()
s.scanReqAllocDuration.Init()
s.insertBytes.Init()
s.numDocsPending.Init()
s.scanWaitDuration.Init()
s.numDocsIndexed.Init()
s.numDocsProcessed.Init()
s.numRequests.Init()
s.lastScanTime.Init()
s.numCompletedRequests.Init()
s.numRowsReturned.Init()
s.numRequestsRange.Init()
s.numCompletedRequestsRange.Init()
s.numRowsReturnedRange.Init()
s.numRowsScannedRange.Init()
s.scanCacheHitRange.Init()
s.numRequestsAggr.Init()
s.numCompletedRequestsAggr.Init()
s.numRowsReturnedAggr.Init()
s.numRowsScannedAggr.Init()
s.scanCacheHitAggr.Init()
s.numRowsScanned.Init()
s.numStrictConsReqs.Init()
s.diskSize.Init()
s.memUsed.Init()
s.buildProgress.Init()
s.completionProgress.Init()
s.numDocsQueued.Init()
s.deleteBytes.Init()
s.dataSize.Init()
s.dataSizeOnDisk.Init()
s.logSpaceOnDisk.Init()
s.rawDataSize.Init()
s.backstoreRawDataSize.Init()
s.docidCount.Init()
s.fragPercent.Init()
s.scanBytesRead.Init()
s.getBytes.Init()
s.itemsCount.Init()
s.arrItemsCount.Init()
s.avgTsInterval.Init()
s.avgTsItemsCount.Init()
s.lastNumFlushQueued.Init()
s.lastTsTime.Init()
s.numDiskSnapshots.Init()
s.numCommits.Init()
s.numSnapshots.Init()
s.numOpenSnapshots.Init()
s.numCompactions.Init()
s.numItemsFlushed.Init()
s.numDocsFlushQueued.Init()
s.sinceLastSnapshot.Init()
s.numSnapshotWaiters.Init()
s.numLastSnapshotReply.Init()
s.numItemsRestored.Init()
s.diskSnapStoreDuration.Init()
s.diskSnapLoadDuration.Init()
s.notReadyError.Init()
s.clientCancelError.Init()
s.numScanTimeouts.Init()
s.numScanErrors.Init()
s.avgScanRate.Init()
s.avgMutationRate.Init()
s.avgDrainRate.Init()
s.avgDiskBps.Init()
s.lastScanGatherTime.Init()
s.lastNumRowsScanned.Init()
s.lastMutateGatherTime.Init()
s.lastNumDocsIndexed.Init()
s.lastNumItemsFlushed.Init()
s.lastDiskBytes.Init()
s.lastRollbackTime.Init()
s.progressStatTime.Init()
s.residentPercent.Init()
s.combinedResidentPercent.Init()
s.cacheHitPercent.Init()
s.cacheHits.Init()
s.cacheMisses.Init()
s.numRecsInMem.Init()
s.numRecsOnDisk.Init()
s.numKeySize64.Init()
s.numKeySize256.Init()
s.numKeySize1K.Init()
s.numKeySize4K.Init()
s.numKeySize100K.Init()
s.numKeySizeGt100K.Init()
s.numArrayKeySize64.Init()
s.numArrayKeySize256.Init()
s.numArrayKeySize1K.Init()
s.numArrayKeySize4K.Init()
s.numArrayKeySize100K.Init()
s.numArrayKeySizeGt100K.Init()
s.keySizeStatsSince.Init()
//stats needed for avg_scan_latency
s.lastScanDuration.Init()
s.lastNumRequests.Init()
s.avgScanLatency.Init()
s.Timings.Init()
s.flushQueue.Init()
s.avgItemSize.Init()
s.waitLat.Init()
s.scanReqLat.Init()
s.scanReqInitLat.Init()
s.scanReqAllocLat.Init()
s.docidCountHolder.Init()
s.avgArrLenHolder.Init()
s.keySizeDist.Init()
s.arrKeySizeDist.Init()
s.scanReqInitLatDist.InitLatency(latencyDist, func(v int64) string { return fmt.Sprintf("%vms", v/int64(time.Millisecond)) })
s.scanReqWaitLatDist.InitLatency(latencyDist, func(v int64) string { return fmt.Sprintf("%vms", v/int64(time.Millisecond)) })
s.scanReqLatDist.InitLatency(scanReqLatencyDist, func(v int64) string { return fmt.Sprintf("%vms", v/int64(time.Millisecond)) })
s.snapGenLatDist.InitLatency(snapLatencyDist, func(v int64) string { return fmt.Sprintf("%vms", v/int64(time.Millisecond)) })
s.partitions = make(map[common.PartitionId]*IndexStats)
// Set filters
// Note that the filters will be set on both: instance level stats and
// partition level stats. Instance level filter map and the partition
// level filter map is the same for each stat value.
s.SetPlannerFilters()
s.SetIndexStatusFilters()
s.SetGSIClientFilters()
s.dispName = common.FormatIndexInstDisplayName(s.name, s.replicaId)
}
func (s *IndexStats) SetPlannerFilters() {
s.itemsCount.AddFilter(stats.PlannerFilter)
s.arrItemsCount.AddFilter(stats.PlannerFilter)
s.buildProgress.AddFilter(stats.PlannerFilter)
s.residentPercent.AddFilter(stats.PlannerFilter)
s.combinedResidentPercent.AddFilter(stats.PlannerFilter)
s.dataSize.AddFilter(stats.PlannerFilter)
s.memUsed.AddFilter(stats.PlannerFilter)
s.avgDiskBps.AddFilter(stats.PlannerFilter)
s.avgDrainRate.AddFilter(stats.PlannerFilter)
s.avgMutationRate.AddFilter(stats.PlannerFilter)
s.numDocsFlushQueued.AddFilter(stats.PlannerFilter)
s.avgScanRate.AddFilter(stats.PlannerFilter)
s.numRowsReturned.AddFilter(stats.PlannerFilter)
s.numDocsPending.AddFilter(stats.PlannerFilter)
s.numDocsQueued.AddFilter(stats.PlannerFilter)
s.lastRollbackTime.AddFilter(stats.PlannerFilter)
s.progressStatTime.AddFilter(stats.PlannerFilter)
s.indexState.AddFilter(stats.PlannerFilter)
}
func (s *IndexStats) SetIndexStatusFilters() {
s.buildProgress.AddFilter(stats.IndexStatusFilter)
s.completionProgress.AddFilter(stats.IndexStatusFilter)
s.lastScanTime.AddFilter(stats.IndexStatusFilter)
}
func (s *IndexStats) SetGSIClientFilters() {
s.numDocsPending.AddFilter(stats.GSIClientFilter)
s.numDocsQueued.AddFilter(stats.GSIClientFilter)
s.lastRollbackTime.AddFilter(stats.GSIClientFilter)
s.progressStatTime.AddFilter(stats.GSIClientFilter)
s.lastScanTime.AddFilter(stats.GSIClientFilter)
s.indexState.AddFilter(stats.GSIClientFilter)
}
func (s *IndexStats) getPartitions() []common.PartitionId {
partitions := make([]common.PartitionId, 0, len(s.partitions))
for id := range s.partitions {
partitions = append(partitions, id)
}
return partitions
}
func (s *IndexStats) addPartition(id common.PartitionId) {
if _, ok := s.partitions[id]; !ok {
partnStats := &IndexStats{isArrayIndex: s.isArrayIndex, useArrItemsCount: s.useArrItemsCount}
partnStats.Init()
s.partitions[id] = partnStats
}
}
// IndexStats.Clone creates a new copy of the IndexStats object with a new
// partitions map that points to the original stats objects.
func (s *IndexStats) clone() *IndexStats {
var clone IndexStats = *s // shallow copy
clone.partitions = make(map[common.PartitionId]*IndexStats)
for k, v := range s.partitions {
clone.partitions[k] = v
}
return &clone
}
func (s *IndexStats) updateAllPartitionStats(f func(*IndexStats)) {
for _, ps := range s.partitions {
f(ps)
}
}
func (s *IndexStats) updatePartitionStats(pid common.PartitionId, f func(*IndexStats)) {
if ps, ok := s.partitions[pid]; ok {
f(ps)
}
}
func (s *IndexStats) getPartitionStats(pid common.PartitionId) *IndexStats {
return s.partitions[pid]
}
func (s *IndexStats) partnMaxInt64Stats(f func(*IndexStats) int64) int64 {
var v int64
for _, ps := range s.partitions {
pv := f(ps)
if pv > v {
v = pv
}
}
return v
}
func (s *IndexStats) partnInt64Stats(f func(*IndexStats) int64) int64 {
var v int64
for _, ps := range s.partitions {
v += f(ps)
}
if v != 0 {
return v
}
return f(s)
}
func (s *IndexStats) partnAvgInt64Stats(f func(*IndexStats) int64) int64 {
return s.int64Stats(f)
}
// int64Stats will execute the passed-in function f to extract a stat from an
// IndexStats object. If the IndexStats receiver represents a partitioned index,
// int64Stats will return the average of f over all of partitions where it is
// non-zero (different from the normal concept of average which would not exclude
// zeros). If it is zero for all partitions or the partitions map is empty, the
// index is assumed to be non-partitioned and int64Stats will return f(this).
func (s *IndexStats) int64Stats(f func(*IndexStats) int64) int64 {
var v, count int64
for _, ps := range s.partitions {
if psv := f(ps); psv != 0 {
v += psv
count++
}
}
if v != 0 {
return (v / count)
}
return f(s)
}
func (s *IndexStats) partnTimingStats(f func(*IndexStats) *stats.TimingStat) string {
var v stats.TimingStat
v.Init()
for _, ps := range s.partitions {
if x := f(ps); x != nil {
v.Count.Add(x.Count.Value())
v.Sum.Add(x.Sum.Value())
v.SumOfSq.Add(x.SumOfSq.Value())
}
}
if v.Count.Value() != 0 {
return v.Value()
}
return f(s).Value()
}
type BucketStats struct {
name string
diskUsed stats.Int64Val
}
func (s *BucketStats) Init() {
s.diskUsed.Init()
}
func (s *BucketStats) clone() *BucketStats {
var clone BucketStats = *s // shallow copy
return &clone
}
// IndexerStats contains both indexer stats at top level and individual index stats under the
// indexes map.
type IndexerStats struct {
// indexes is a map of index IDs to per-index stats. Never nil.
indexes map[common.IndexInstId]*IndexStats
// keyspaceStatsMap wraps per-keyspace stats. Never nil.
keyspaceStatsMap KeyspaceStatsMapHolder
// bucketStats
buckets map[string]*BucketStats
bslock sync.RWMutex
numConnections stats.Int64Val
memoryQuota stats.Int64Val
memoryUsed stats.Int64Val
memoryUsedStorage stats.Int64Val
memoryTotalStorage stats.Int64Val
memoryUsedQueue stats.Int64Val
memoryUsedActual stats.Int64Val //mandatory memory for plasma
needsRestart stats.BoolVal
statsResponse stats.TimingStat
notFoundError stats.Int64Val
numTenants stats.Int64Val
unitsQuota stats.Int64Val //RU/WU units quota for serverless model
unitsUsedActual stats.Int64Val //RU/WU units used for serverless model
indexerState stats.Int64Val
prjLatencyMap *LatencyMapHolder
nodeToHostMap *NodeToHostMapHolder
timestamp stats.StringVal
uptime stats.StringVal
storageMode stats.StringVal
numCPU stats.Int64Val
cpuUtilization stats.Int64Val
memoryRss stats.Uint64Val
memoryFree stats.Uint64Val
memoryTotal stats.Uint64Val
pauseTotalNs stats.Uint64Val
numIndexes stats.Int64Val
numStorageInstances stats.Int64Val
avgResidentPercent stats.Int64Val
avgMutationRate stats.Int64Val
avgDrainRate stats.Int64Val
avgDiskBps stats.Int64Val
totalDataSize stats.Int64Val
totalDiskSize stats.Int64Val
numGoroutine stats.Int64Val
numCgoCall stats.Int64Val
// indexerStateHolder holds atomic ptr to a string giving indexer state (e.g. Active, Paused)
indexerStateHolder stats.StringVal
TotalRequests stats.Int64Val
TotalRowsReturned stats.Int64Val
TotalRowsScanned stats.Int64Val
}
func (s *IndexerStats) Init() {
s.indexes = make(map[common.IndexInstId]*IndexStats)
s.keyspaceStatsMap.Init()
s.buckets = make(map[string]*BucketStats)
s.numConnections.Init()
s.memoryQuota.Init()
s.memoryUsed.Init()
s.memoryUsedStorage.Init()
s.memoryTotalStorage.Init()
s.memoryUsedQueue.Init()
s.memoryUsedActual.Init()
s.needsRestart.Init()
s.statsResponse.Init()
s.indexerState.Init()
s.notFoundError.Init()
s.prjLatencyMap = &LatencyMapHolder{}
s.prjLatencyMap.Init()
s.numTenants.Init()
s.unitsQuota.Init()
s.unitsUsedActual.Init()
s.nodeToHostMap = &NodeToHostMapHolder{}
s.nodeToHostMap.Init()
s.timestamp.Init()
s.uptime.Init()
s.storageMode.Init()
s.numCPU.Init()
s.cpuUtilization.Init()
s.memoryRss.Init()
s.memoryFree.Init()
s.memoryTotal.Init()
s.indexerStateHolder.Init()
s.pauseTotalNs.Init()
s.numIndexes.Init()
s.numStorageInstances.Init()
s.avgResidentPercent.Init()
s.avgMutationRate.Init()
s.avgDrainRate.Init()
s.avgDiskBps.Init()
s.totalDataSize.Init()
s.totalDiskSize.Init()
s.numGoroutine.Init()
s.numCgoCall.Init()
s.SetPlannerFilters()
s.SetSmartBatchingFilters()
s.SetIndexStatusFilters()
s.SetSummaryFilters()
// Set values of invariants on Init. GOMAXPROCS was already adjusted by settingsManager.
s.numCPU.Set(int64(runtime.GOMAXPROCS(0)))
s.TotalRequests.Init()
s.TotalRowsReturned.Init()
s.TotalRowsScanned.Init()
}
// SetSmartBatchingFilters marks the IndexerStats needed by Smart Batching for Rebalance.
func (s *IndexerStats) SetSmartBatchingFilters() {
s.avgResidentPercent.AddFilter(stats.SmartBatchingFilter)
s.memoryQuota.AddFilter(stats.SmartBatchingFilter)
s.memoryUsed.AddFilter(stats.SmartBatchingFilter)
s.numIndexes.AddFilter(stats.SmartBatchingFilter)
s.storageMode.AddFilter(stats.SmartBatchingFilter)
}
func (s *IndexerStats) SetIndexStatusFilters() {
s.indexerStateHolder.AddFilter(stats.IndexStatusFilter)
}
func (s *IndexerStats) SetPlannerFilters() {
s.memoryUsedStorage.AddFilter(stats.PlannerFilter)
s.memoryUsed.AddFilter(stats.PlannerFilter)
s.memoryQuota.AddFilter(stats.PlannerFilter)
s.memoryRss.AddFilter(stats.PlannerFilter)
s.memoryUsedActual.AddFilter(stats.PlannerFilter)
s.uptime.AddFilter(stats.PlannerFilter)
s.cpuUtilization.AddFilter(stats.PlannerFilter)
s.unitsQuota.AddFilter(stats.PlannerFilter)
s.unitsUsedActual.AddFilter(stats.PlannerFilter)
}
func (s *IndexerStats) SetSummaryFilters() {
s.memoryQuota.AddFilter(stats.SummaryFilter)
s.memoryUsed.AddFilter(stats.SummaryFilter)
s.memoryUsedStorage.AddFilter(stats.SummaryFilter)
s.memoryTotalStorage.AddFilter(stats.SummaryFilter)
s.memoryUsedQueue.AddFilter(stats.SummaryFilter)
s.memoryRss.AddFilter(stats.SummaryFilter)
if common.IsServerlessDeployment() {
s.memoryUsedActual.AddFilter(stats.SummaryFilter)
s.unitsQuota.AddFilter(stats.SummaryFilter)
s.unitsUsedActual.AddFilter(stats.SummaryFilter)
s.numTenants.AddFilter(stats.SummaryFilter)
}
s.numCPU.AddFilter(stats.SummaryFilter)
s.cpuUtilization.AddFilter(stats.SummaryFilter)
s.avgResidentPercent.AddFilter(stats.SummaryFilter)
s.avgMutationRate.AddFilter(stats.SummaryFilter)
s.avgDrainRate.AddFilter(stats.SummaryFilter)
s.avgDiskBps.AddFilter(stats.SummaryFilter)
s.totalDataSize.AddFilter(stats.SummaryFilter)
s.totalDiskSize.AddFilter(stats.SummaryFilter)
s.numStorageInstances.AddFilter(stats.SummaryFilter)
s.numIndexes.AddFilter(stats.SummaryFilter)
s.storageMode.AddFilter(stats.SummaryFilter)
s.indexerStateHolder.AddFilter(stats.SummaryFilter)
s.uptime.AddFilter(stats.SummaryFilter)
s.TotalRequests.AddFilter(stats.SummaryFilter)
s.TotalRowsReturned.AddFilter(stats.SummaryFilter)
s.TotalRowsScanned.AddFilter(stats.SummaryFilter)
}
// Reset recreates empty IndexStats and KeyspaceStats for each one that existed
// before. This approach avoids resetting structured data types inside the old
// objects while other routines are accessing them concurrently. This routine is
// only called by a stats REST API that few currently use.
func (s *IndexerStats) Reset() {
old := *s
*s = IndexerStats{} // overwrite old self pointer
s.Init()
// Recreate per-index objects
for instId, iStats := range old.indexes {
indexStats := s.addIndexStats(instId, iStats.bucket, iStats.scope, iStats.collection, iStats.name,
iStats.replicaId, iStats.isArrayIndex, iStats.useArrItemsCount)
// Recreate per-partition subobjects
for partnId := range iStats.partitions {
indexStats.addPartition(partnId)
}
}
// Recreate KeyspaceStats objects
for streamId, ksStats := range old.GetKeyspaceStatsMap() {
for keyspaceId := range ksStats {
s.AddKeyspaceStats(streamId, keyspaceId)
}
}
func() {
old.bslock.RLock()
defer old.bslock.RUnlock()
// Recreate BucketStats objects
for bucket, bstats := range old.buckets {
bstats := &BucketStats{name: bstats.name}
bstats.Init()
s.buckets[bucket] = bstats
}
}()
}
func (s *IndexerStats) addBucketStats(bucket string) {
s.bslock.Lock()
defer s.bslock.Unlock()
if _, ok := s.buckets[bucket]; !ok {
bstats := &BucketStats{name: bucket}
bstats.Init()
s.buckets[bucket] = bstats
}
s.setNumTenants()
}
func (s *IndexerStats) removeBucketStats(bucket string) {
s.bslock.Lock()
defer s.bslock.Unlock()
// TODO: Make this O(1)
canRemove := true
for _, stats := range s.indexes {
if stats.bucket == bucket {
canRemove = false
break
}
}
if canRemove {
delete(s.buckets, bucket)
}
s.setNumTenants()
}
func (s *IndexerStats) GetBucketStats(bucket string) *BucketStats {
s.bslock.RLock()
defer s.bslock.RUnlock()
if bstats, ok := s.buckets[bucket]; ok {
return bstats
}
return nil
}