-
Notifications
You must be signed in to change notification settings - Fork 28
/
ns_server.go
executable file
·1714 lines (1459 loc) · 51.1 KB
/
ns_server.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 cbft
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"unsafe"
"github.com/couchbase/cbgt"
"github.com/couchbase/cbgt/rest"
log "github.com/couchbase/clog"
gojson "github.com/couchbase/go_json"
)
// Dump stats to log once every 5min. This stat is configurable
// through the ENV_OPTION: logStatsEvery
var LogEveryNStats = 300
var SourcePartitionSeqsSleepDefault = 10 * time.Second
var SourcePartitionSeqsCacheTimeoutDefault = 60 * time.Second
// Atomic counters to keep track of the number of active
// http and https limit listeners.
var TotHTTPLimitListenersOpened uint64
var TotHTTPLimitListenersClosed uint64
var TotHTTPSLimitListenersOpened uint64
var TotHTTPSLimitListenersClosed uint64
// Atomic counters to keep track of the number of active
// grpc and grpc-ssl listeners.
var TotGRPCListenersOpened uint64
var TotGRPCListenersClosed uint64
var TotGRPCSListenersOpened uint64
var TotGRPCSListenersClosed uint64
// App-herder pertinent atomic stats.
var TotHerderWaitingIn uint64
var TotHerderWaitingOut uint64
var TotHerderOnBatchExecuteStartBeg uint64
var TotHerderOnBatchExecuteStartEnd uint64
var TotHerderQueriesRejected uint64
var TotMergesSkipped uint64
// Query Throttler stats.
var TotKNNQueriesRejectedByThrottler uint64
// Atomic stat that tracks current memory acquired, not including
// HeapIdle (memory reclaimed); updated every second;
// Used by the app_herder to track memory consumption by process.
var currentMemoryUsed uint64
// Optional callback when current memory used has dropped since the
// last sampling.
var OnMemoryUsedDropped func(curMemoryUsed, prevMemoryUsed uint64)
// PartitionSeqsProvider represents source object that can provide
// partition seqs, such as some pindex or dest implementations.
type PartitionSeqsProvider interface {
// Returned map is keyed by partition id.
PartitionSeqs() (map[string]cbgt.UUIDSeq, error)
}
var statsNamePrefix = []byte("\"")
var statsNameSuffix = []byte("\":")
// NsStatsHandler is a REST handler that provides stats/metrics for
// consumption by ns_server
type NsStatsHandler struct {
statsCount int64
mgr *cbgt.Manager
}
func NewNsStatsHandler(mgr *cbgt.Manager) *NsStatsHandler {
return &NsStatsHandler{mgr: mgr}
}
func (h *NsStatsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
currentStatsCount := atomic.AddInt64(&h.statsCount, 1)
initNsServerCaching(h.mgr)
rd := getRecentInfo()
if rd.err != nil {
rest.ShowError(w, req, fmt.Sprintf("could not retrieve defs: %v", rd.err),
http.StatusInternalServerError)
return
}
nsIndexStats, err := gatherIndexesStats(h.mgr, rd, false)
if err != nil {
rest.ShowError(w, req, fmt.Sprintf("error in retrieving defs: %v", err),
http.StatusInternalServerError)
return
}
if LogEveryNStats != 0 && currentStatsCount%int64(LogEveryNStats) == 0 {
go func() {
var buf bytes.Buffer
err := rest.WriteManagerStatsJSON(h.mgr, &buf, "")
if err != nil {
log.Warnf("error formatting managerStatsJSON for logs: %v", err)
} else {
log.Printf("managerStats: %s", buf.String())
}
statsJSON, err := json.MarshalIndent(nsIndexStats, "", " ")
if err != nil {
log.Warnf("error formatting JSON for logs: %v", err)
return
}
log.Printf("stats: %s", string(statsJSON))
}()
}
rest.MustEncode(w, nsIndexStats)
}
// BucketsNsStatsHandler is a REST handler that provides the list
// of buckets which have partitions on the current node.
type BucketsNsStatsHandler struct {
mgr *cbgt.Manager
}
func NewBucketsNsStatsHandler(mgr *cbgt.Manager) *BucketsNsStatsHandler {
return &BucketsNsStatsHandler{mgr: mgr}
}
func (h *BucketsNsStatsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
_, pindexes := h.mgr.CurrentMaps()
bucketsMap := make(map[string]struct{})
for _, pindex := range pindexes {
bucketsMap[pindex.SourceName] = struct{}{}
}
result := struct {
IndexSourceNames map[string]struct{} `json:"indexSourceNames"`
}{
IndexSourceNames: bucketsMap,
}
rest.MustEncode(w, result)
}
// IndexNsStatsHandler is a REST handler that provides stats/metrics for
// for an index
type IndexNsStatsHandler struct {
mgr *cbgt.Manager
}
func NewIndexNsStatsHandler(mgr *cbgt.Manager) *IndexNsStatsHandler {
return &IndexNsStatsHandler{mgr: mgr}
}
func (h *IndexNsStatsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
initNsServerCaching(h.mgr)
indexName := rest.IndexNameLookup(req)
if indexName == "" {
rest.ShowError(w, req, "index name is required", http.StatusBadRequest)
return
}
indexDef, _, err := h.mgr.GetIndexDef(indexName, false)
if err != nil || indexDef == nil {
rest.ShowError(w, req,
fmt.Sprintf("unable to obtain index definition for `%v`, err: %v", indexName, err),
http.StatusBadRequest)
return
}
rd := getRecentInfo()
if rd.err != nil {
rest.ShowError(w, req, fmt.Sprintf("could not retrieve defs: %v", rd.err),
http.StatusInternalServerError)
return
}
var planPIndexes []*cbgt.PlanPIndex
if rd.planPIndexes != nil {
for _, planPIndex := range rd.planPIndexes.PlanPIndexes {
if planPIndex.IndexName != indexName {
continue
}
planPIndexes = append(planPIndexes, planPIndex)
}
}
nsIndexStat, _ := gatherIndexStats(h.mgr, indexDef, planPIndexes, nil, nil)
rest.MustEncode(w, nsIndexStat)
}
// -----------------------------------------------------------------------------
type NSIndexStats map[string]map[string]interface{}
// MarshalJSON formats the index stats using the
// colon separated convention found in other
// stats consumed by ns_server
func (n NSIndexStats) MarshalJSON() ([]byte, error) {
rv := make(map[string]interface{})
for k, nsis := range n {
for nsik, nsiv := range nsis {
if k == "" {
rv[nsik] = nsiv
} else {
rv[k+":"+nsik] = nsiv
}
}
}
return json.Marshal(rv)
}
var statkeys = []string{
// pindex
"doc_count",
"timer_batch_store_count",
// feed
"timer_opaque_set_count",
"timer_rollback_count",
"timer_data_update_count",
"timer_data_delete_count",
"timer_snapshot_start_count",
"timer_opaque_get_count",
// --------------------------------------------
// stats from "FTS Stats" spec, see:
// https://docs.google.com/spreadsheets/d/1w8P68gLBIs0VUN4egUuUH6U_92_5xi9azfvH8pPw21s/edit#gid=104567684
"num_mutations_to_index", // per-index stat.
// "doc_count", // per-index stat (see above).
"total_bytes_indexed", // per-index stat.
"num_bytes_written_at_index_time", // per-index stat.
"num_bytes_read_at_query_time", //per-index stat
"num_recs_to_persist", // per-index stat.
"num_bytes_used_disk", // per-index stat.
"num_bytes_used_disk_by_root", // per-index stat.
"num_files_on_disk", // per-index stat.
"num_bytes_used_disk_by_root_reclaimable", // per-index stat.
// "num_bytes_used_ram" -- PROCESS-LEVEL stat.
"num_pindexes_actual", // per-index stat.
"num_pindexes_target", // per-index stat.
"num_root_memorysegments", // per-index stat.
"num_root_filesegments", // per-index stat.
"num_persister_nap_pause_completed", // per-index stat.
"num_persister_nap_merger_break", // per-index stat.
"num_file_merge_ops", // per-index stat.
"num_mem_merge_ops", // per-index stat.
"total_compaction_written_bytes", // per-index stat.
// "total_gc" -- PROCESS-LEVEL stat.
// "pct_cpu_gc" -- PROCESS-LEVEL stat.
"total_queries", // per-index stat.
"avg_queries_latency", // per-index stat.
"total_internal_queries", // per-index stat.
"avg_internal_queries_latency", // per-index stat.
"total_request_time", // per-index stat.
"total_queries_slow", // per-index stat.
"total_queries_timeout", // per-index stat.
"total_queries_error", // per-index stat.
"total_grpc_queries", // per-index stat.
"avg_grpc_queries_latency", // per-index stat.
"total_grpc_internal_queries", // per-index stat.
"avg_grpc_internal_queries_latency", // per-index stat.
"total_grpc_request_time", // per-index stat.
"total_grpc_queries_slow", // per-index stat.
"total_grpc_queries_timeout", // per-index stat.
"total_grpc_queries_error", // per-index stat.
"total_bytes_query_results", // per-index stat.
"total_term_searchers", // per-index stat.
"total_term_searchers_finished", // per-index stat.
"total_knn_searches", // per-index stat.
// "curr_batches_blocked_by_herder" -- PROCESS-LEVEL stat.
// "total_queries_rejected_by_herder" -- PROCESS-LEVEL stat
}
// stats aggregated across all indexes
type aggrIndexesStats struct {
// focus stats aggregated across all indexes
focusStats *rest.RESTFocusStats
// bleveStats aggregated across all partitions of all indexes
numBytesUsedDisk float64
numFilesOnDisk float64
}
func (ais *aggrIndexesStats) getStatsMap() map[string]interface{} {
rv := make(map[string]interface{})
// # Focus Stats
totalQueries := ais.focusStats.TotClientRequest
rv["total_queries"] = totalQueries
if totalQueries > 0 {
// Convert from nanosecs to millisecs for avg_queries_latency.
rv["avg_queries_latency"] =
float64(ais.focusStats.TotClientRequestTimeNS/totalQueries) /
1000000.0
}
totalInternalQueries := ais.focusStats.TotInternalRequest
rv["total_internal_queries"] = totalInternalQueries
if totalInternalQueries > 0 {
// Convert from nanosecs to millisecs for avg_internal_queries_latency.
rv["avg_internal_queries_latency"] =
float64(ais.focusStats.TotInternalRequestTimeNS/
totalInternalQueries) / 1000000.0
}
rv["total_request_time"] = ais.focusStats.TotRequestTimeNS
rv["total_queries_slow"] = ais.focusStats.TotRequestSlow
rv["total_queries_timeout"] = ais.focusStats.TotRequestTimeout
rv["total_queries_error"] = ais.focusStats.TotRequestErr
rv["total_bytes_query_results"] = ais.focusStats.TotResponseBytes
// # Bleve Stats
rv["num_bytes_used_disk"] = ais.numBytesUsedDisk
rv["num_files_on_disk"] = ais.numFilesOnDisk
return rv
}
// NewIndexStat ensures that all index stats
// have the same shape and 0 values to
// prevent seeing N/A in ns_server UI
func NewIndexStat() map[string]interface{} {
rv := make(map[string]interface{})
for _, key := range statkeys {
rv[key] = float64(0)
}
return rv
}
func getRecentInfo() *recentInfo {
return (*recentInfo)(atomic.LoadPointer(&lastRecentInfo))
}
func gatherQueryErrorsStats() map[string]interface{} {
rv := make(map[string]interface{})
rv["total_queries_search_in_context_error"] =
atomic.LoadUint64(&totQuerySearchInContextErr)
rv["total_queries_bad_request_error"] =
atomic.LoadUint64(&totQueryBadRequestErr)
rv["total_queries_validation_error"] =
atomic.LoadUint64(&totQueryValidationErr)
rv["total_queries_consistency_error"] =
atomic.LoadUint64(&totQueryConsistencyErr)
rv["total_queries_max_result_window_exceeded_error"] =
atomic.LoadUint64(&totQueryMaxResultWindowExceededErr)
rv["total_queries_partial_results_error"] =
atomic.LoadUint64(&totQueryPartialResultsErr)
return rv
}
func gatherIndexesStats(mgr *cbgt.Manager, rd *recentInfo,
collAware bool) (NSIndexStats, error) {
if rd == nil || mgr == nil {
return nil, nil
}
indexDefsMap := rd.indexDefsMap
planPIndexes := rd.planPIndexes
nodeUUID := mgr.UUID()
nsIndexStats := make(NSIndexStats, len(indexDefsMap))
indexNameToSourceName := map[string]string{}
indexNameToPlanPIndexes := map[string][]*cbgt.PlanPIndex{}
if planPIndexes != nil {
for _, planPIndex := range planPIndexes.PlanPIndexes {
// Only focus on the planPIndex entries for this node.
if planPIndex.Nodes[nodeUUID] != nil {
indexNameToPlanPIndexes[planPIndex.IndexName] =
append(indexNameToPlanPIndexes[planPIndex.IndexName], planPIndex)
}
}
}
// Keyed by sourceName, sub-key is source partition id.
sourceNameToSourcePartitionSeqs := map[string]map[string]cbgt.UUIDSeq{}
ais := &aggrIndexesStats{
focusStats: &rest.RESTFocusStats{},
}
var numIndexes, numVectorIndexes int
for indexName, indexDef := range indexDefsMap {
var key string
if collAware {
key = getNsIndexStatsKey(indexName, indexDef.SourceName, indexDef.Params)
} else {
key = indexDef.SourceName + ":" + indexName
}
nsIndexStat, err := gatherIndexStats(
mgr,
indexDef,
indexNameToPlanPIndexes[indexName],
sourceNameToSourcePartitionSeqs,
ais,
)
if err != nil {
continue
}
nsIndexStats[key] = nsIndexStat
indexNameToSourceName[indexName] = key
numIndexes += 1
if indexHasVectorFields(indexDef.Params) {
numVectorIndexes += 1
}
}
nsIndexStats["regulatorStats"] = GetRegulatorStats()
if !collAware {
nsIndexStats[""] = gatherTopLevelStats(mgr, rd)
}
if nsIndexStats[""] == nil {
nsIndexStats[""] = make(map[string]interface{})
}
// insert aggregated stats as top level stats
for k, v := range ais.getStatsMap() {
nsIndexStats[""][k] = v
}
// insert query errors stats as top level stats
for k, v := range gatherQueryErrorsStats() {
nsIndexStats[""][k] = v
}
// insert create index error stats as top level stats
for k, v := range rest.GatherCreateIndexStats() {
nsIndexStats[""][k] = v
}
// insert delete index error stats as top level stats
for k, v := range rest.GatherDeleteIndexStats() {
nsIndexStats[""][k] = v
}
nsIndexStats[""]["num_indexes"] = numIndexes
nsIndexStats[""]["num_vector_indexes"] = numVectorIndexes
return nsIndexStats, nil
}
func gatherIndexStats(
mgr *cbgt.Manager,
indexDef *cbgt.IndexDef,
planPIndexes []*cbgt.PlanPIndex,
sourceNameToSourcePartitionSeqs map[string]map[string]cbgt.UUIDSeq,
aggrIdxStats *aggrIndexesStats,
) (map[string]interface{}, error) {
if indexDef == nil {
return nil, fmt.Errorf("gatherIndexStats: indexDef cannot be nil")
}
nsIndexStat := NewIndexStat()
var totalQueries, totalInternalQueries uint64
var totClientRequestTimeNS, totInternalRequestTimeNS uint64
var totRequestTimeNS, totRequestSlow, totRequestTimeout, totRequestErr, totResponseBytes uint64
for k := range queryPaths {
// Obtain focus stats for all query paths supported
indexQueryPathStats := MapRESTPathStats[k]
focusStats := indexQueryPathStats.FocusStats(indexDef.Name)
if focusStats != nil {
totalQueries += atomic.LoadUint64(&focusStats.TotClientRequest)
totClientRequestTimeNS += atomic.LoadUint64(&focusStats.TotClientRequestTimeNS)
totalInternalQueries += atomic.LoadUint64(&focusStats.TotInternalRequest)
totInternalRequestTimeNS += atomic.LoadUint64(&focusStats.TotInternalRequestTimeNS)
totRequestTimeNS += atomic.LoadUint64(&focusStats.TotRequestTimeNS)
totRequestSlow += atomic.LoadUint64(&focusStats.TotRequestSlow)
totRequestTimeout += atomic.LoadUint64(&focusStats.TotRequestTimeout)
totRequestErr += atomic.LoadUint64(&focusStats.TotRequestErr)
totResponseBytes += atomic.LoadUint64(&focusStats.TotResponseBytes)
}
}
// update aggregator map
if aggrIdxStats != nil {
aggrIdxStats.focusStats.TotClientRequest += totalQueries
aggrIdxStats.focusStats.TotClientRequestTimeNS += totClientRequestTimeNS
aggrIdxStats.focusStats.TotInternalRequest += totalInternalQueries
aggrIdxStats.focusStats.TotInternalRequestTimeNS += totInternalRequestTimeNS
aggrIdxStats.focusStats.TotRequestTimeNS += totRequestTimeNS
aggrIdxStats.focusStats.TotRequestSlow += totRequestSlow
aggrIdxStats.focusStats.TotRequestTimeout += totRequestTimeout
aggrIdxStats.focusStats.TotRequestErr += totRequestErr
aggrIdxStats.focusStats.TotResponseBytes += totResponseBytes
}
nsIndexStat["total_queries"] = totalQueries
if totalQueries > 0 {
// Convert from nanosecs to millisecs for avg_queries_latency.
nsIndexStat["avg_queries_latency"] =
float64(totClientRequestTimeNS/totalQueries) / 1000000.0
}
nsIndexStat["total_internal_queries"] = totalInternalQueries
if totalInternalQueries > 0 {
// Convert from nanosecs to millisecs for avg_internal_queries_latency.
nsIndexStat["avg_internal_queries_latency"] =
float64(totInternalRequestTimeNS/totalInternalQueries) / 1000000.0
}
nsIndexStat["total_request_time"] = totRequestTimeNS
nsIndexStat["total_queries_slow"] = totRequestSlow
nsIndexStat["total_queries_timeout"] = totRequestTimeout
nsIndexStat["total_queries_error"] = totRequestErr
nsIndexStat["total_bytes_query_results"] = totResponseBytes
nsIndexStat["num_pindexes_target"] = uint64(len(planPIndexes))
rpcFocusStats := GrpcPathStats.FocusStats(indexDef.Name)
if rpcFocusStats != nil {
totalQueries := atomic.LoadUint64(&rpcFocusStats.TotGrpcRequest)
nsIndexStat["total_grpc_queries"] = totalQueries
if totalQueries > 0 {
nsIndexStat["avg_grpc_queries_latency"] =
float64((atomic.LoadUint64(&rpcFocusStats.TotGrpcRequestTimeNS) /
totalQueries)) / 1000000.0 // Convert from nanosecs to millisecs.
}
totalInternalQueries := atomic.LoadUint64(&rpcFocusStats.TotGrpcInternalRequest)
nsIndexStat["total_grpc_internal_queries"] = totalInternalQueries
if totalInternalQueries > 0 {
nsIndexStat["avg_grpc_internal_queries_latency"] =
float64(atomic.LoadUint64(&rpcFocusStats.TotGrpcInternalRequestTimeNS)/
totalInternalQueries) / 1000000.0 // Convert from nanosecs to millisecs.
}
nsIndexStat["total_grpc_request_time"] =
atomic.LoadUint64(&rpcFocusStats.TotGrpcRequestTimeNS)
nsIndexStat["total_grpc_queries_slow"] =
atomic.LoadUint64(&rpcFocusStats.TotGrpcRequestSlow)
nsIndexStat["total_grpc_queries_timeout"] =
atomic.LoadUint64(&rpcFocusStats.TotGrpcRequestTimeout)
nsIndexStat["total_grpc_queries_error"] =
atomic.LoadUint64(&rpcFocusStats.TotGrpcRequestErr)
}
nsIndexStat["last_access_time"] =
querySupervisor.GetLastAccessTimeForIndex(indexDef.Name)
feeds, pindexes := mgr.CurrentMaps()
for _, feed := range feeds {
if feed.IndexName() != indexDef.Name {
continue
}
// automatically process all the feed stats
_ = addFeedStats(feed, nsIndexStat)
}
srcPartitionSeqs, exists := sourceNameToSourcePartitionSeqs[indexDef.SourceName]
if !exists {
feedType, exists := cbgt.FeedTypes[indexDef.SourceType]
if !exists || feedType == nil || feedType.PartitionSeqs == nil {
return nsIndexStat, nil
}
srcPartitionSeqs = GetSourcePartitionSeqs(SourceSpec{
SourceType: indexDef.SourceType,
SourceName: indexDef.SourceName,
SourceUUID: indexDef.SourceUUID,
SourceParams: indexDef.SourceParams,
Server: mgr.Server(),
})
if srcPartitionSeqs != nil && sourceNameToSourcePartitionSeqs != nil {
sourceNameToSourcePartitionSeqs[indexDef.SourceName] = srcPartitionSeqs
}
}
destPartitionSeqs := map[string]cbgt.UUIDSeq{}
for _, pindex := range pindexes {
if pindex.IndexName != indexDef.Name {
continue
}
oldValue, ok := nsIndexStat["num_pindexes_actual"]
if ok {
switch oldValue := oldValue.(type) {
case float64:
oldValue += float64(1)
nsIndexStat["num_pindexes_actual"] = oldValue
}
}
// automatically process all the pindex dest stats
_ = addPIndexStats(pindex, nsIndexStat, aggrIdxStats)
if pindex.Dest != nil {
destForwarder, ok := pindex.Dest.(*cbgt.DestForwarder)
if !ok {
continue
}
partitionSeqsProvider, ok :=
destForwarder.DestProvider.(PartitionSeqsProvider)
if !ok {
continue
}
if partitionSeqs, err := partitionSeqsProvider.PartitionSeqs(); err == nil {
for partitionId, uuidSeq := range partitionSeqs {
destPartitionSeqs[partitionId] = uuidSeq
}
}
}
}
if totSeqReceived, numMutationsToIndex, err := obtainDestSeqsForIndex(
indexDef,
srcPartitionSeqs,
destPartitionSeqs,
); err == nil {
nsIndexStat["tot_seq_received"] = totSeqReceived
nsIndexStat["num_mutations_to_index"] = numMutationsToIndex
}
return nsIndexStat, nil
}
// Utility function obtains the following for an index definition from
// it's source's and destination stats:
// - tot_seq_received
// - num_mutations_to_index
func obtainDestSeqsForIndex(indexDef *cbgt.IndexDef,
srcPartitionSeqs map[string]cbgt.UUIDSeq,
destPartitionSeqs map[string]cbgt.UUIDSeq) (uint64, uint64, error) {
var scope string
var collections []string
// obtain collections of interest from index definition only if
// srcPartitionSeqs was provided; skip determining source stats for
// the index otherwise
if len(srcPartitionSeqs) > 0 {
var err error
scope, collections = metaFieldValCache.getScopeCollectionNames(indexDef.Name)
if len(scope) == 0 || len(collections) == 0 {
scope, collections, err = GetScopeCollectionsFromIndexDef(indexDef)
if err != nil {
return 0, 0, err
}
}
}
var totDestSeq, totSrcSeq uint64
for partitionId, dstUUIDSeq := range destPartitionSeqs {
var srcSeq uint64
// the following loop is skipped if srcPartitionSeqs isn't available
for i := range collections {
uuidHighSeq, exists :=
srcPartitionSeqs[partitionId+":"+scope+":"+collections[i]]
if !exists {
continue
}
// account this collection's high seq only if it actually holds
// any items and is greater than the last accounted value
if uuidHighSeq.Seq > srcSeq {
srcSeq = uuidHighSeq.Seq
}
}
if srcSeq > 0 {
totSrcSeq += srcSeq
}
totDestSeq += dstUUIDSeq.Seq
}
if totSrcSeq >= totDestSeq {
return totDestSeq, totSrcSeq - totDestSeq, nil
}
return totDestSeq, 0, nil
}
// Returns usage reported from go and c separately
func getMemoryUtilization(memStats runtime.MemStats) (uint64, uint64) {
// Memory utilization to account for:
// - memory alloced for the process
// - memory released by process back to the OS
// - memory freed by the process but NOT released back to the OS just yet
//
// Per https://pkg.go.dev/runtime#MemStats
// - Sys is the total bytes of memory obtained from the OS.
// - (HeapIdle-HeapReleased) estimates the amount of memory that
// could be returned to the OS.
// - HeapReleased is bytes of physical memory returned to the OS.
// So our equation here should be ..
// Sys - (HeapIdle - HeapReleased) - HeapReleased
// cHeapAlloc represents memory allocated by the C code through cgo,
// which is not included in the Go runtime statistics. This memory
// comprises the heap memory utilized by either jemalloc or malloc,
// depending on whether the jemalloc go-tag was set.
return memStats.Sys - memStats.HeapIdle, cHeapAlloc()
}
func gatherNodeUtilStats(mgr *cbgt.Manager,
rv map[string]interface{}) {
var totalUnitsMetered uint64
if val, exists := GetRegulatorStats()["total_units_metered"]; exists {
totalUnitsMetered = val.(uint64)
}
options := mgr.Options()
rd := getRecentInfo()
if cpu, err := currentCPUPercent(); err == nil {
numCPU, _ := strconv.ParseFloat(options["ftsCpuQuota"], 64)
rv["utilization:cpuPercent"] = DetermineNewAverage(
"cpuPercent", uint64(cpu/numCPU))
}
rv["utilization:billableUnitsRate"] = DetermineNewAverage(
"totalUnitsMetered", totalUnitsMetered)
goUtil, cUtil := getMemoryUtilization(rd.memStats)
rv["utilization:memoryBytes"] = DetermineNewAverage(
"memoryBytes", goUtil+cUtil)
var size int64
_ = filepath.Walk(mgr.DataDir(), func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
rv["utilization:diskBytes"] = uint64(size)
if val, exists := options["resourceUtilizationHighWaterMark"]; exists {
if valFloat64, err := strconv.ParseFloat(val, 64); err == nil {
rv["resourceUtilizationHighWaterMark"] = valFloat64
}
}
if val, exists := options["resourceUtilizationLowWaterMark"]; exists {
if valFloat64, err := strconv.ParseFloat(val, 64); err == nil {
rv["resourceUtilizationLowWaterMark"] = valFloat64
}
}
if val, exists := options["resourceUnderUtilizationWaterMark"]; exists {
if valFloat64, err := strconv.ParseFloat(val, 64); err == nil {
rv["resourceUnderUtilizationWaterMark"] = valFloat64
}
}
if val, exists := options["maxBillableUnitsRate"]; exists {
if valUint64, err := strconv.ParseUint(val, 10, 64); err == nil {
rv["limits:billableUnitsRate"] = valUint64
}
}
if val, exists := options["maxDiskBytes"]; exists {
if valUint64, err := strconv.ParseUint(val, 10, 64); err == nil {
rv["limits:diskBytes"] = valUint64
}
}
if val, exists := options["ftsMemoryQuota"]; exists {
if valUint64, err := strconv.ParseUint(val, 10, 64); err == nil {
rv["limits:memoryBytes"] = valUint64
}
}
}
func gatherTopLevelStats(mgr *cbgt.Manager, rd *recentInfo) map[string]interface{} {
topLevelStats := map[string]interface{}{}
var ftsMemoryQuota uint64
if val := mgr.GetOption("ftsMemoryQuota"); len(val) > 0 {
if valUint64, err := strconv.ParseUint(val, 10, 64); err == nil {
ftsMemoryQuota = valUint64
}
}
goUtil, cUtil := getMemoryUtilization(rd.memStats)
memUtil := goUtil + cUtil
topLevelStats["num_bytes_used_ram"] = memUtil
topLevelStats["num_bytes_used_ram_c"] = cUtil
topLevelStats["num_bytes_ram_quota"] = ftsMemoryQuota
topLevelStats["pct_used_ram"] =
(float64(memUtil) / float64(ftsMemoryQuota)) * 100
topLevelStats["total_gc"] = rd.memStats.NumGC
topLevelStats["pct_cpu_gc"] = rd.memStats.GCCPUFraction
topLevelStats["tot_remote_http"] = atomic.LoadUint64(&totRemoteHttp)
topLevelStats["tot_remote_http2"] = atomic.LoadUint64(&totRemoteHttpSsl) // deprecated
topLevelStats["tot_remote_http_ssl"] = atomic.LoadUint64(&totRemoteHttpSsl)
topLevelStats["tot_queryreject_on_memquota"] =
atomic.LoadUint64(&totQueryRejectOnNotEnoughQuota)
topLevelStats["tot_http_limitlisteners_opened"] =
atomic.LoadUint64(&TotHTTPLimitListenersOpened)
topLevelStats["tot_http_limitlisteners_closed"] =
atomic.LoadUint64(&TotHTTPLimitListenersClosed)
topLevelStats["tot_https_limitlisteners_opened"] =
atomic.LoadUint64(&TotHTTPSLimitListenersOpened)
topLevelStats["tot_https_limitlisteners_closed"] =
atomic.LoadUint64(&TotHTTPSLimitListenersClosed)
topLevelStats["tot_remote_grpc"] = atomic.LoadUint64(&totRemoteGrpc)
topLevelStats["tot_remote_grpc_tls"] = atomic.LoadUint64(&totRemoteGrpcSsl) // deprecated
topLevelStats["tot_remote_grpc_ssl"] = atomic.LoadUint64(&totRemoteGrpcSsl)
topLevelStats["tot_grpc_queryreject_on_memquota"] =
atomic.LoadUint64(&totGrpcQueryRejectOnNotEnoughQuota)
topLevelStats["tot_grpc_listeners_opened"] =
atomic.LoadUint64(&TotGRPCListenersOpened)
topLevelStats["tot_grpc_listeners_closed"] =
atomic.LoadUint64(&TotGRPCListenersClosed)
topLevelStats["tot_grpcs_listeners_opened"] =
atomic.LoadUint64(&TotGRPCSListenersOpened)
topLevelStats["tot_grpcs_listeners_closed"] =
atomic.LoadUint64(&TotGRPCSListenersClosed)
topLevelStats["batch_bytes_added"] = atomic.LoadUint64(&BatchBytesAdded)
topLevelStats["batch_bytes_removed"] = atomic.LoadUint64(&BatchBytesRemoved)
topLevelStats["num_batches_introduced"] = atomic.LoadUint64(&NumBatchesIntroduced)
topLevelStats["tot_batches_flushed_on_maxops"] = atomic.LoadUint64(&TotBatchesFlushedOnMaxOps)
topLevelStats["tot_batches_flushed_on_timer"] = atomic.LoadUint64(&TotBatchesFlushedOnTimer)
topLevelStats["tot_batches_new"] = atomic.LoadUint64(&TotBatchesNew)
topLevelStats["tot_batches_merged"] = atomic.LoadUint64(&TotBatchesMerged)
topLevelStats["tot_bleve_dest_opened"] = atomic.LoadUint64(&TotBleveDestOpened)
topLevelStats["tot_bleve_dest_closed"] = atomic.LoadUint64(&TotBleveDestClosed)
topLevelStats["tot_rollback_full"] = atomic.LoadUint64(&TotRollbackFull)
topLevelStats["tot_rollback_partial"] = atomic.LoadUint64(&TotRollbackPartial)
topLevelStats["curr_batches_blocked_by_herder"] =
atomic.LoadUint64(&TotHerderOnBatchExecuteStartBeg) -
atomic.LoadUint64(&TotHerderOnBatchExecuteStartEnd)
topLevelStats["total_queries_rejected_by_herder"] =
atomic.LoadUint64(&TotHerderQueriesRejected)
topLevelStats["num_gocbcore_dcp_agents"] = cbgt.NumDCPAgents()
topLevelStats["num_gocbcore_stats_agents"] = cbgt.NumStatsAgents()
topLevelStats["num_knn_search_requests"] = atomic.LoadUint64(&numKNNSearchRequests)
topLevelStats["total_knn_queries_rejected_by_throttler"] = atomic.LoadUint64(&TotKNNQueriesRejectedByThrottler)
if ServerlessMode {
gatherNodeUtilStats(mgr, topLevelStats)
}
return topLevelStats
}
func addFeedStats(feed cbgt.Feed, nsIndexStat map[string]interface{}) error {
buffer := new(bytes.Buffer)
err := feed.Stats(buffer)
if err != nil {
return err
}
return massageStats(buffer, nsIndexStat)
}
func addPIndexStats(pindex *cbgt.PIndex, nsIndexStat map[string]interface{},
aggrIdxStats *aggrIndexesStats) error {
if destForwarder, ok := pindex.Dest.(*cbgt.DestForwarder); ok {
if bp, ok := destForwarder.DestProvider.(*BleveDest); ok {
bpsm, err := bp.StatsMap()
if err != nil {
return err
}
extractFieldStats(bpsm, nsIndexStat)
return extractStats(bpsm, nsIndexStat, aggrIdxStats)
}
}
return nil
}
func extractFieldStats(bpsm, nsIndexStat map[string]interface{}) {
v := gojson.Get(bpsm, "/bleveIndexStats/index")
if is, ok := v.(map[string]interface{}); ok {
for s, v := range is {
if strings.HasSuffix(s, ":num_vectors") {
updateFieldStats(s, v, nsIndexStat)
updateFieldStats("total_vectors", v, nsIndexStat)
}
}
}
}
func updateFieldStats(name string, val interface{}, nsIndexStat map[string]interface{}) {
if _, exist := nsIndexStat[name]; !exist {
nsIndexStat[name] = val
} else {
if oldVal, ok := nsIndexStat[name].(uint64); ok {
if newVal, ok := val.(uint64); ok {
nsIndexStat[name] = oldVal + newVal
}
}
}
}
func updateAggregateStats(ais *aggrIndexesStats, statName string, val float64) {
if ais != nil {
switch statName {
case "num_bytes_used_disk":
ais.numBytesUsedDisk += val
case "num_files_on_disk":
ais.numFilesOnDisk += val
}
}
}
func updateStat(name string, val float64, nsIndexStat map[string]interface{},
aggrIdxStats *aggrIndexesStats) {
oldValue, ok := nsIndexStat[name]
if ok {
switch oldValue := oldValue.(type) {
case float64:
oldValue += val
nsIndexStat[name] = oldValue
updateAggregateStats(aggrIdxStats, name, val)
}
}
}
func extractStats(bpsm, nsIndexStat map[string]interface{},
aggrIdxStats *aggrIndexesStats) error {
// common stats across different index types
v := gojson.Get(bpsm, "/DocCount")
if vuint64, ok := v.(uint64); ok {
updateStat("doc_count", float64(vuint64), nsIndexStat, aggrIdxStats)
}
v = gojson.Get(bpsm, "/bleveIndexStats/index/term_searchers_started")
if vuint64, ok := v.(uint64); ok {
updateStat("total_term_searchers", float64(vuint64), nsIndexStat,
aggrIdxStats)
}
v = gojson.Get(bpsm, "/bleveIndexStats/index/term_searchers_finished")
if vuint64, ok := v.(uint64); ok {
updateStat("total_term_searchers_finished", float64(vuint64), nsIndexStat,
aggrIdxStats)
}
v = gojson.Get(bpsm, "/bleveIndexStats/index/knn_searches")
if vuint64, ok := v.(uint64); ok {
updateStat("total_knn_searches", float64(vuint64), nsIndexStat,
aggrIdxStats)
}
v = gojson.Get(bpsm, "/bleveIndexStats/index/num_plain_text_bytes_indexed")
if vuint64, ok := v.(uint64); ok {
updateStat("total_bytes_indexed", float64(vuint64), nsIndexStat,
aggrIdxStats)
}
v = gojson.Get(bpsm, "/bleveIndexStats/index/TotFileMergeIntroductionsDone")
if vuint64, ok := v.(uint64); ok {
updateStat("num_file_merge_ops", float64(vuint64), nsIndexStat,
aggrIdxStats)
}
v = gojson.Get(bpsm, "/bleveIndexStats/index/TotMemMergeDone")
if vuint64, ok := v.(uint64); ok {
updateStat("num_mem_merge_ops", float64(vuint64), nsIndexStat,