-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
mongostat.go
1498 lines (1327 loc) · 55.2 KB
/
mongostat.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
// The code contained here came from https://github.com/mongodb/mongo-tools/blob/master/mongostat/stat_types.go
// and contains modifications so that no other dependency from that project is needed. Other modifications included
// removing unnecessary code specific to formatting the output and determine the current state of the database. It
// is licensed under Apache Version 2.0, http://www.apache.org/licenses/LICENSE-2.0.html
package mongodb
import (
"sort"
"strings"
"time"
)
const (
MongosProcess = "mongos"
)
// Flags to determine cases when to activate/deactivate columns for output.
const (
Always = 1 << iota // always activate the column
Discover // only active when mongostat is in discover mode
Repl // only active if one of the nodes being monitored is in a replset
Locks // only active if node is capable of calculating lock info
AllOnly // only active if mongostat was run with --all option
MMAPOnly // only active if node has mmap-specific fields
WTOnly // only active if node has wiredtiger-specific fields
)
type mongoStatus struct {
SampleTime time.Time
ServerStatus *serverStatus
ReplSetStatus *replSetStatus
ClusterStatus *clusterStatus
DbStats *dbStats
ColStats *colStats
ShardStats *shardStats
OplogStats *oplogStats
TopStats *topStats
}
type serverStatus struct {
SampleTime time.Time `bson:""`
Flattened map[string]interface{} `bson:""`
Host string `bson:"host"`
Version string `bson:"version"`
Process string `bson:"process"`
Pid int64 `bson:"pid"`
Uptime int64 `bson:"uptime"`
UptimeMillis int64 `bson:"uptimeMillis"`
UptimeEstimate int64 `bson:"uptimeEstimate"`
LocalTime time.Time `bson:"localTime"`
Asserts *assertsStats `bson:"asserts"`
BackgroundFlushing *flushStats `bson:"backgroundFlushing"`
ExtraInfo *extraInfo `bson:"extra_info"`
Connections *connectionStats `bson:"connections"`
Dur *durStats `bson:"dur"`
GlobalLock *globalLockStats `bson:"globalLock"`
Locks map[string]lockStats `bson:"locks,omitempty"`
Network *networkStats `bson:"network"`
Opcounters *opcountStats `bson:"opcounters"`
OpcountersRepl *opcountStats `bson:"opcountersRepl"`
OpLatencies *opLatenciesStats `bson:"opLatencies"`
RecordStats *dbRecordStats `bson:"recordStats"`
Mem *memStats `bson:"mem"`
Repl *replStatus `bson:"repl"`
ShardCursorType map[string]interface{} `bson:"shardCursorType"`
StorageEngine *storageEngine `bson:"storageEngine"`
WiredTiger *wiredTiger `bson:"wiredTiger"`
Metrics *metricsStats `bson:"metrics"`
TCMallocStats *tcMallocStats `bson:"tcmalloc"`
}
// dbStats stores stats from all dbs
type dbStats struct {
Dbs []db
}
// db represent a single DB
type db struct {
Name string
DbStatsData *dbStatsData
}
// dbStatsData stores stats from a db
type dbStatsData struct {
Db string `bson:"db"`
Collections int64 `bson:"collections"`
Objects int64 `bson:"objects"`
AvgObjSize float64 `bson:"avgObjSize"`
DataSize int64 `bson:"dataSize"`
StorageSize int64 `bson:"storageSize"`
NumExtents int64 `bson:"numExtents"`
Indexes int64 `bson:"indexes"`
IndexSize int64 `bson:"indexSize"`
Ok int64 `bson:"ok"`
GleStats interface{} `bson:"gleStats"`
FsUsedSize int64 `bson:"fsUsedSize"`
FsTotalSize int64 `bson:"fsTotalSize"`
}
type colStats struct {
Collections []collection
}
type collection struct {
Name string
DbName string
ColStatsData *colStatsData
}
type colStatsData struct {
Collection string `bson:"ns"`
Count int64 `bson:"count"`
Size int64 `bson:"size"`
AvgObjSize float64 `bson:"avgObjSize"`
StorageSize int64 `bson:"storageSize"`
TotalIndexSize int64 `bson:"totalIndexSize"`
Ok int64 `bson:"ok"`
}
// clusterStatus stores information related to the whole cluster
type clusterStatus struct {
JumboChunksCount int64
}
// replSetStatus stores information from replSetGetStatus
type replSetStatus struct {
Members []replSetMember `bson:"members"`
MyState int64 `bson:"myState"`
}
// oplogStats stores information from getReplicationInfo
type oplogStats struct {
TimeDiff int64
}
// replSetMember stores information related to a replica set member
type replSetMember struct {
Name string `bson:"name"`
Health int64 `bson:"health"`
State int64 `bson:"state"`
StateStr string `bson:"stateStr"`
OptimeDate time.Time `bson:"optimeDate"`
}
// wiredTiger stores information related to the wiredTiger storage engine.
type wiredTiger struct {
Transaction transactionStats `bson:"transaction"`
Concurrent concurrentTransactions `bson:"concurrentTransactions"`
Cache cacheStats `bson:"cache"`
Connection wtConnectionStats `bson:"connection"`
DataHandle dataHandleStats `bson:"data-handle"`
}
// shardStats stores information from shardConnPoolStats.
type shardStats struct {
shardStatsData `bson:",inline"`
Hosts map[string]shardHostStatsData `bson:"hosts"`
}
// shardStatsData is the total Shard Stats from shardConnPoolStats database command.
type shardStatsData struct {
TotalInUse int64 `bson:"totalInUse"`
TotalAvailable int64 `bson:"totalAvailable"`
TotalCreated int64 `bson:"totalCreated"`
TotalRefreshing int64 `bson:"totalRefreshing"`
}
// shardHostStatsData is the host-specific stats from shardConnPoolStats database command.
type shardHostStatsData struct {
InUse int64 `bson:"inUse"`
Available int64 `bson:"available"`
Created int64 `bson:"created"`
Refreshing int64 `bson:"refreshing"`
}
type topStats struct {
Totals map[string]topStatCollection `bson:"totals"`
}
type topStatCollection struct {
Total topStatCollectionData `bson:"total"`
ReadLock topStatCollectionData `bson:"readLock"`
WriteLock topStatCollectionData `bson:"writeLock"`
Queries topStatCollectionData `bson:"queries"`
GetMore topStatCollectionData `bson:"getmore"`
Insert topStatCollectionData `bson:"insert"`
Update topStatCollectionData `bson:"update"`
Remove topStatCollectionData `bson:"remove"`
Commands topStatCollectionData `bson:"commands"`
}
type topStatCollectionData struct {
Time int64 `bson:"time"`
Count int64 `bson:"count"`
}
type concurrentTransactions struct {
Write concurrentTransStats `bson:"write"`
Read concurrentTransStats `bson:"read"`
}
type concurrentTransStats struct {
Out int64 `bson:"out"`
Available int64 `bson:"available"`
TotalTickets int64 `bson:"totalTickets"`
}
// assertsStats stores information related to assertions raised since the MongoDB process started
type assertsStats struct {
Regular int64 `bson:"regular"`
Warning int64 `bson:"warning"`
Msg int64 `bson:"msg"`
User int64 `bson:"user"`
Rollovers int64 `bson:"rollovers"`
}
// cacheStats stores cache statistics for wiredTiger.
type cacheStats struct {
TrackedDirtyBytes int64 `bson:"tracked dirty bytes in the cache"`
CurrentCachedBytes int64 `bson:"bytes currently in the cache"`
MaxBytesConfigured int64 `bson:"maximum bytes configured"`
AppThreadsPageReadCount int64 `bson:"application threads page read from disk to cache count"`
AppThreadsPageReadTime int64 `bson:"application threads page read from disk to cache time (usecs)"`
AppThreadsPageWriteCount int64 `bson:"application threads page write from cache to disk count"`
AppThreadsPageWriteTime int64 `bson:"application threads page write from cache to disk time (usecs)"`
BytesWrittenFrom int64 `bson:"bytes written from cache"`
BytesReadInto int64 `bson:"bytes read into cache"`
PagesEvictedByAppThread int64 `bson:"pages evicted by application threads"`
PagesQueuedForEviction int64 `bson:"pages queued for eviction"`
PagesReadIntoCache int64 `bson:"pages read into cache"`
PagesWrittenFromCache int64 `bson:"pages written from cache"`
PagesRequestedFromCache int64 `bson:"pages requested from the cache"`
ServerEvictingPages int64 `bson:"eviction server evicting pages"`
WorkerThreadEvictingPages int64 `bson:"eviction worker thread evicting pages"`
InternalPagesEvicted int64 `bson:"internal pages evicted"`
ModifiedPagesEvicted int64 `bson:"modified pages evicted"`
UnmodifiedPagesEvicted int64 `bson:"unmodified pages evicted"`
}
type storageEngine struct {
Name string `bson:"name"`
}
// transactionStats stores transaction checkpoints in wiredTiger.
type transactionStats struct {
TransCheckpointsTotalTimeMsecs int64 `bson:"transaction checkpoint total time (msecs)"`
TransCheckpoints int64 `bson:"transaction checkpoints"`
}
// wtConnectionStats stores statistics on wiredTiger connections
type wtConnectionStats struct {
FilesCurrentlyOpen int64 `bson:"files currently open"`
}
// dataHandleStats stores statistics for wiredTiger data-handles
type dataHandleStats struct {
DataHandlesCurrentlyActive int64 `bson:"connection data handles currently active"`
}
// replStatus stores data related to replica sets.
type replStatus struct {
SetName string `bson:"setName"`
IsWritablePrimary interface{} `bson:"isWritablePrimary"` // mongodb 5.x
IsMaster interface{} `bson:"ismaster"`
Secondary interface{} `bson:"secondary"`
IsReplicaSet interface{} `bson:"isreplicaset"`
ArbiterOnly interface{} `bson:"arbiterOnly"`
Hosts []string `bson:"hosts"`
Passives []string `bson:"passives"`
Me string `bson:"me"`
}
// dbRecordStats stores data related to memory operations across databases.
type dbRecordStats struct {
AccessesNotInMemory int64 `bson:"accessesNotInMemory"`
PageFaultExceptionsThrown int64 `bson:"pageFaultExceptionsThrown"`
DBRecordAccesses map[string]recordAccesses `bson:",inline"`
}
// recordAccesses stores data related to memory operations scoped to a database.
type recordAccesses struct {
AccessesNotInMemory int64 `bson:"accessesNotInMemory"`
PageFaultExceptionsThrown int64 `bson:"pageFaultExceptionsThrown"`
}
// memStats stores data related to memory statistics.
type memStats struct {
Bits int64 `bson:"bits"`
Resident int64 `bson:"resident"`
Virtual int64 `bson:"virtual"`
Supported interface{} `bson:"supported"`
Mapped int64 `bson:"mapped"`
MappedWithJournal int64 `bson:"mappedWithJournal"`
}
// flushStats stores information about memory flushes.
type flushStats struct {
Flushes int64 `bson:"flushes"`
TotalMs int64 `bson:"total_ms"`
AverageMs float64 `bson:"average_ms"`
LastMs int64 `bson:"last_ms"`
LastFinished time.Time `bson:"last_finished"`
}
// connectionStats stores information related to incoming database connections.
type connectionStats struct {
Current int64 `bson:"current"`
Available int64 `bson:"available"`
TotalCreated int64 `bson:"totalCreated"`
}
// durTiming stores information related to journaling.
type durTiming struct {
Dt int64 `bson:"dt"`
PrepLogBuffer int64 `bson:"prepLogBuffer"`
WriteToJournal int64 `bson:"writeToJournal"`
WriteToDataFiles int64 `bson:"writeToDataFiles"`
RemapPrivateView int64 `bson:"remapPrivateView"`
}
// durStats stores information related to journaling statistics.
type durStats struct {
Commits float64 `bson:"commits"`
JournaledMB float64 `bson:"journaledMB"`
WriteToDataFilesMB float64 `bson:"writeToDataFilesMB"`
Compression float64 `bson:"compression"`
CommitsInWriteLock float64 `bson:"commitsInWriteLock"`
EarlyCommits float64 `bson:"earlyCommits"`
TimeMs durTiming
}
// queueStats stores the number of queued read/write operations.
type queueStats struct {
Total int64 `bson:"total"`
Readers int64 `bson:"readers"`
Writers int64 `bson:"writers"`
}
// clientStats stores the number of active read/write operations.
type clientStats struct {
Total int64 `bson:"total"`
Readers int64 `bson:"readers"`
Writers int64 `bson:"writers"`
}
// globalLockStats stores information related locks in the MMAP storage engine.
type globalLockStats struct {
TotalTime int64 `bson:"totalTime"`
LockTime int64 `bson:"lockTime"`
CurrentQueue *queueStats `bson:"currentQueue"`
ActiveClients *clientStats `bson:"activeClients"`
}
// networkStats stores information related to network traffic.
type networkStats struct {
BytesIn int64 `bson:"bytesIn"`
BytesOut int64 `bson:"bytesOut"`
NumRequests int64 `bson:"numRequests"`
}
// opcountStats stores information related to commands and basic CRUD operations.
type opcountStats struct {
Insert int64 `bson:"insert"`
Query int64 `bson:"query"`
Update int64 `bson:"update"`
Delete int64 `bson:"delete"`
GetMore int64 `bson:"getmore"`
Command int64 `bson:"command"`
}
// opLatenciesStats stores information related to operation latencies for the database as a whole
type opLatenciesStats struct {
Reads *latencyStats `bson:"reads"`
Writes *latencyStats `bson:"writes"`
Commands *latencyStats `bson:"commands"`
}
// latencyStats lists total latency in microseconds and count of operations, enabling you to obtain an average
type latencyStats struct {
Latency int64 `bson:"latency"`
Ops int64 `bson:"ops"`
}
// metricsStats stores information related to metrics
type metricsStats struct {
TTL *ttlStats `bson:"ttl"`
Cursor *cursorStats `bson:"cursor"`
Document *documentStats `bson:"document"`
Commands *commandsStats `bson:"commands"`
Operation *operationStats `bson:"operation"`
QueryExecutor *queryExecutorStats `bson:"queryExecutor"`
Repl *replStats `bson:"repl"`
Storage *storageStats `bson:"storage"`
}
// ttlStats stores information related to documents with a ttl index.
type ttlStats struct {
DeletedDocuments int64 `bson:"deletedDocuments"`
Passes int64 `bson:"passes"`
}
// cursorStats stores information related to cursor metrics.
type cursorStats struct {
TimedOut int64 `bson:"timedOut"`
Open *openCursorStats `bson:"open"`
}
// documentStats stores information related to document metrics.
type documentStats struct {
Deleted int64 `bson:"deleted"`
Inserted int64 `bson:"inserted"`
Returned int64 `bson:"returned"`
Updated int64 `bson:"updated"`
}
// commandsStats stores information related to document metrics.
type commandsStats struct {
Aggregate *commandsStatsValue `bson:"aggregate"`
Count *commandsStatsValue `bson:"count"`
Delete *commandsStatsValue `bson:"delete"`
Distinct *commandsStatsValue `bson:"distinct"`
Find *commandsStatsValue `bson:"find"`
FindAndModify *commandsStatsValue `bson:"findAndModify"`
GetMore *commandsStatsValue `bson:"getMore"`
Insert *commandsStatsValue `bson:"insert"`
Update *commandsStatsValue `bson:"update"`
}
type commandsStatsValue struct {
Failed int64 `bson:"failed"`
Total int64 `bson:"total"`
}
// openCursorStats stores information related to open cursor metrics
type openCursorStats struct {
NoTimeout int64 `bson:"noTimeout"`
Pinned int64 `bson:"pinned"`
Total int64 `bson:"total"`
}
// operationStats stores information related to query operations
// using special operation types
type operationStats struct {
ScanAndOrder int64 `bson:"scanAndOrder"`
WriteConflicts int64 `bson:"writeConflicts"`
}
// queryExecutorStats stores information related to query execution
type queryExecutorStats struct {
Scanned int64 `bson:"scanned"`
ScannedObjects int64 `bson:"scannedObjects"`
}
// replStats stores information related to replication process
type replStats struct {
Apply *replApplyStats `bson:"apply"`
Buffer *replBufferStats `bson:"buffer"`
Executor *replExecutorStats `bson:"executor,omitempty"`
Network *replNetworkStats `bson:"network"`
}
// replApplyStats stores information related to oplog application process
type replApplyStats struct {
Batches *basicStats `bson:"batches"`
Ops int64 `bson:"ops"`
}
// replBufferStats stores information related to oplog buffer
type replBufferStats struct {
Count int64 `bson:"count"`
SizeBytes int64 `bson:"sizeBytes"`
}
// replExecutorStats stores information related to replication executor
type replExecutorStats struct {
Pool map[string]int64 `bson:"pool"`
Queues map[string]int64 `bson:"queues"`
UnsignaledEvents int64 `bson:"unsignaledEvents"`
}
// replNetworkStats stores information related to network usage by replication process
type replNetworkStats struct {
Bytes int64 `bson:"bytes"`
GetMores *basicStats `bson:"getmores"`
Ops int64 `bson:"ops"`
}
// basicStats stores information about an operation
type basicStats struct {
Num int64 `bson:"num"`
TotalMillis int64 `bson:"totalMillis"`
}
// readWriteLockTimes stores time spent holding read/write locks.
type readWriteLockTimes struct {
Read int64 `bson:"R"`
Write int64 `bson:"W"`
ReadLower int64 `bson:"r"`
WriteLower int64 `bson:"w"`
}
// lockStats stores information related to time spent acquiring/holding locks for a given database.
type lockStats struct {
TimeLockedMicros readWriteLockTimes `bson:"timeLockedMicros"`
TimeAcquiringMicros readWriteLockTimes `bson:"timeAcquiringMicros"`
// AcquireCount and AcquireWaitCount are new fields of the lock stats only populated on 3.0 or newer.
// Typed as a pointer so that if it is nil, mongostat can assume the field is not populated
// with real namespace data.
AcquireCount *readWriteLockTimes `bson:"acquireCount,omitempty"`
AcquireWaitCount *readWriteLockTimes `bson:"acquireWaitCount,omitempty"`
}
// extraInfo stores additional platform specific information.
type extraInfo struct {
PageFaults *int64 `bson:"page_faults"`
}
// tcMallocStats stores information related to TCMalloc memory allocator metrics
type tcMallocStats struct {
Generic *genericTCMAllocStats `bson:"generic"`
TCMalloc *detailedTCMallocStats `bson:"tcmalloc"`
}
// genericTCMAllocStats stores generic TCMalloc memory allocator metrics
type genericTCMAllocStats struct {
CurrentAllocatedBytes int64 `bson:"current_allocated_bytes"`
HeapSize int64 `bson:"heap_size"`
}
// detailedTCMallocStats stores detailed TCMalloc memory allocator metrics
type detailedTCMallocStats struct {
PageheapFreeBytes int64 `bson:"pageheap_free_bytes"`
PageheapUnmappedBytes int64 `bson:"pageheap_unmapped_bytes"`
MaxTotalThreadCacheBytes int64 `bson:"max_total_thread_cache_bytes"`
CurrentTotalThreadCacheBytes int64 `bson:"current_total_thread_cache_bytes"`
TotalFreeBytes int64 `bson:"total_free_bytes"`
CentralCacheFreeBytes int64 `bson:"central_cache_free_bytes"`
TransferCacheFreeBytes int64 `bson:"transfer_cache_free_bytes"`
ThreadCacheFreeBytes int64 `bson:"thread_cache_free_bytes"`
PageheapComittedBytes int64 `bson:"pageheap_committed_bytes"`
PageheapScavengeCount int64 `bson:"pageheap_scavenge_count"`
PageheapCommitCount int64 `bson:"pageheap_commit_count"`
PageheapTotalCommitBytes int64 `bson:"pageheap_total_commit_bytes"`
PageheapDecommitCount int64 `bson:"pageheap_decommit_count"`
PageheapTotalDecommitBytes int64 `bson:"pageheap_total_decommit_bytes"`
PageheapReserveCount int64 `bson:"pageheap_reserve_count"`
PageheapTotalReserveBytes int64 `bson:"pageheap_total_reserve_bytes"`
SpinLockTotalDelayNanos int64 `bson:"spinlock_total_delay_ns"`
}
// storageStats stores information related to record allocations
type storageStats struct {
FreelistSearchBucketExhausted int64 `bson:"freelist.search.bucketExhausted"`
FreelistSearchRequests int64 `bson:"freelist.search.requests"`
FreelistSearchScanned int64 `bson:"freelist.search.scanned"`
}
// statHeader describes a single column for mongostat's terminal output, its formatting, and in which modes it should be displayed.
type statHeader struct {
// The text to appear in the column's header cell
HeaderText string
// Bitmask containing flags to determine if this header is active or not
ActivateFlags int
}
// StatHeaders are the complete set of data metrics supported by mongostat.
var StatHeaders = []statHeader{
{"", Always}, // placeholder for hostname column (blank header text)
{"insert", Always},
{"query", Always},
{"update", Always},
{"delete", Always},
{"getmore", Always},
{"command", Always},
{"% dirty", WTOnly},
{"% used", WTOnly},
{"flushes", Always},
{"mapped", MMAPOnly},
{"vsize", Always},
{"res", Always},
{"non-mapped", MMAPOnly | AllOnly},
{"faults", MMAPOnly},
{"lr|lw %", MMAPOnly | AllOnly},
{"lrt|lwt", MMAPOnly | AllOnly},
{" locked db", Locks},
{"qr|qw", Always},
{"ar|aw", Always},
{"netIn", Always},
{"netOut", Always},
{"conn", Always},
{"set", Repl},
{"repl", Repl},
{"time", Always},
}
// NamespacedLocks stores information on the lockStatus of namespaces.
type NamespacedLocks map[string]lockStatus
// lockUsage stores information related to a namespace's lock usage.
type lockUsage struct {
Namespace string
Reads int64
Writes int64
}
type lockUsages []lockUsage
func percentageInt64(value, outOf int64) float64 {
if value == 0 || outOf == 0 {
return 0
}
return 100 * (float64(value) / float64(outOf))
}
func averageInt64(value, outOf int64) int64 {
if value == 0 || outOf == 0 {
return 0
}
return value / outOf
}
func (slice lockUsages) Len() int {
return len(slice)
}
func (slice lockUsages) Less(i, j int) bool {
return slice[i].Reads+slice[i].Writes < slice[j].Reads+slice[j].Writes
}
func (slice lockUsages) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// collectionLockStatus stores a collection's lock statistics.
type collectionLockStatus struct {
ReadAcquireWaitsPercentage float64
WriteAcquireWaitsPercentage float64
ReadAcquireTimeMicros int64
WriteAcquireTimeMicros int64
}
// lockStatus stores a database's lock statistics.
type lockStatus struct {
DBName string
Percentage float64
Global bool
}
// statLine is a wrapper for all metrics reported by mongostat for monitored hosts.
type statLine struct {
Key string
// What storage engine is being used for the node with this stat line
StorageEngine string
Error error
IsMongos bool
Host string
Version string
UptimeNanos int64
// The time at which this statLine was generated.
Time time.Time
// The last time at which this statLine was printed to output.
LastPrinted time.Time
// Opcounter fields
Insert, InsertCnt int64
Query, QueryCnt int64
Update, UpdateCnt int64
Delete, DeleteCnt int64
GetMore, GetMoreCnt int64
Command, CommandCnt int64
// Asserts fields
Regular int64
Warning int64
Msg int64
User int64
Rollovers int64
// OpLatency fields
WriteOpsCnt int64
WriteLatency int64
ReadOpsCnt int64
ReadLatency int64
CommandOpsCnt int64
CommandLatency int64
// TTL fields
Passes, PassesCnt int64
DeletedDocuments, DeletedDocumentsCnt int64
// Cursor fields
TimedOutC, TimedOutCCnt int64
NoTimeoutC, NoTimeoutCCnt int64
PinnedC, PinnedCCnt int64
TotalC, TotalCCnt int64
// Document fields
DeletedD, InsertedD, ReturnedD, UpdatedD int64
// Commands fields
AggregateCommandTotal, AggregateCommandFailed int64
CountCommandTotal, CountCommandFailed int64
DeleteCommandTotal, DeleteCommandFailed int64
DistinctCommandTotal, DistinctCommandFailed int64
FindCommandTotal, FindCommandFailed int64
FindAndModifyCommandTotal, FindAndModifyCommandFailed int64
GetMoreCommandTotal, GetMoreCommandFailed int64
InsertCommandTotal, InsertCommandFailed int64
UpdateCommandTotal, UpdateCommandFailed int64
// Operation fields
ScanAndOrderOp, WriteConflictsOp int64
// Query Executor fields
TotalKeysScanned, TotalObjectsScanned int64
// Connection fields
CurrentC, AvailableC, TotalCreatedC int64
// Collection locks (3.0 mmap only)
CollectionLocks *collectionLockStatus
// Cache utilization (wiredtiger only)
CacheDirtyPercent float64
CacheUsedPercent float64
// Cache utilization extended (wiredtiger only)
TrackedDirtyBytes int64
CurrentCachedBytes int64
MaxBytesConfigured int64
AppThreadsPageReadCount int64
AppThreadsPageReadTime int64
AppThreadsPageWriteCount int64
BytesWrittenFrom int64
BytesReadInto int64
PagesEvictedByAppThread int64
PagesQueuedForEviction int64
PagesReadIntoCache int64
PagesWrittenFromCache int64
PagesRequestedFromCache int64
ServerEvictingPages int64
WorkerThreadEvictingPages int64
InternalPagesEvicted int64
ModifiedPagesEvicted int64
UnmodifiedPagesEvicted int64
// Connection statistics (wiredtiger only)
FilesCurrentlyOpen int64
// Data handles statistics (wiredtiger only)
DataHandlesCurrentlyActive int64
// Replicated Opcounter fields
InsertR, InsertRCnt int64
QueryR, QueryRCnt int64
UpdateR, UpdateRCnt int64
DeleteR, DeleteRCnt int64
GetMoreR, GetMoreRCnt int64
CommandR, CommandRCnt int64
ReplLag int64
OplogStats *oplogStats
Flushes, FlushesCnt int64
FlushesTotalTime int64
Mapped, Virtual, Resident, NonMapped int64
Faults, FaultsCnt int64
HighestLocked *lockStatus
QueuedReaders, QueuedWriters int64
ActiveReaders, ActiveWriters int64
AvailableReaders, AvailableWriters int64
TotalTicketsReaders, TotalTicketsWriters int64
NetIn, NetInCnt int64
NetOut, NetOutCnt int64
NumConnections int64
ReplSetName string
ReplHealthAvg float64
NodeType string
NodeState string
NodeStateInt int64
NodeHealthInt int64
// Replicated Metrics fields
ReplNetworkBytes int64
ReplNetworkGetmoresNum int64
ReplNetworkGetmoresTotalMillis int64
ReplNetworkOps int64
ReplBufferCount int64
ReplBufferSizeBytes int64
ReplApplyBatchesNum int64
ReplApplyBatchesTotalMillis int64
ReplApplyOps int64
ReplExecutorPoolInProgressCount int64
ReplExecutorQueuesNetworkInProgress int64
ReplExecutorQueuesSleepers int64
ReplExecutorUnsignaledEvents int64
// Cluster fields
JumboChunksCount int64
// DB stats field
DbStatsLines []dbStatLine
// Col Stats field
ColStatsLines []colStatLine
// Shard stats
TotalInUse, TotalAvailable, TotalCreated, TotalRefreshing int64
// Shard Hosts stats field
ShardHostStatsLines map[string]shardHostStatLine
TopStatLines []topStatLine
// TCMalloc stats field
TCMallocCurrentAllocatedBytes int64
TCMallocHeapSize int64
TCMallocCentralCacheFreeBytes int64
TCMallocCurrentTotalThreadCacheBytes int64
TCMallocMaxTotalThreadCacheBytes int64
TCMallocTotalFreeBytes int64
TCMallocTransferCacheFreeBytes int64
TCMallocThreadCacheFreeBytes int64
TCMallocSpinLockTotalDelayNanos int64
TCMallocPageheapFreeBytes int64
TCMallocPageheapUnmappedBytes int64
TCMallocPageheapComittedBytes int64
TCMallocPageheapScavengeCount int64
TCMallocPageheapCommitCount int64
TCMallocPageheapTotalCommitBytes int64
TCMallocPageheapDecommitCount int64
TCMallocPageheapTotalDecommitBytes int64
TCMallocPageheapReserveCount int64
TCMallocPageheapTotalReserveBytes int64
// Storage stats field
StorageFreelistSearchBucketExhausted int64
StorageFreelistSearchRequests int64
StorageFreelistSearchScanned int64
}
type dbStatLine struct {
Name string
Collections int64
Objects int64
AvgObjSize float64
DataSize int64
StorageSize int64
NumExtents int64
Indexes int64
IndexSize int64
Ok int64
FsUsedSize int64
FsTotalSize int64
}
type colStatLine struct {
Name string
DbName string
Count int64
Size int64
AvgObjSize float64
StorageSize int64
TotalIndexSize int64
Ok int64
}
type shardHostStatLine struct {
InUse int64
Available int64
Created int64
Refreshing int64
}
type topStatLine struct {
CollectionName string
TotalTime, TotalCount int64
ReadLockTime, ReadLockCount int64
WriteLockTime, WriteLockCount int64
QueriesTime, QueriesCount int64
GetMoreTime, GetMoreCount int64
InsertTime, InsertCount int64
UpdateTime, UpdateCount int64
RemoveTime, RemoveCount int64
CommandsTime, CommandsCount int64
}
func parseLocks(stat serverStatus) map[string]lockUsage {
returnVal := make(map[string]lockUsage, len(stat.Locks))
for namespace, lockInfo := range stat.Locks {
returnVal[namespace] = lockUsage{
namespace,
lockInfo.TimeLockedMicros.Read + lockInfo.TimeLockedMicros.ReadLower,
lockInfo.TimeLockedMicros.Write + lockInfo.TimeLockedMicros.WriteLower,
}
}
return returnVal
}
func computeLockDiffs(prevLocks, curLocks map[string]lockUsage) []lockUsage {
lockUsages := lockUsages(make([]lockUsage, 0, len(curLocks)))
for namespace, curUsage := range curLocks {
prevUsage, hasKey := prevLocks[namespace]
if !hasKey {
// This namespace didn't appear in the previous batch of lock info,
// so we can't compute a diff for it - skip it.
continue
}
// Calculate diff of lock usage for this namespace and add to the list
lockUsages = append(lockUsages,
lockUsage{
namespace,
curUsage.Reads - prevUsage.Reads,
curUsage.Writes - prevUsage.Writes,
})
}
// Sort the array in order of least to most locked
sort.Sort(lockUsages)
return lockUsages
}
func diff(newVal, oldVal, sampleTime int64) (avg, newValue int64) {
d := newVal - oldVal
if d < 0 {
d = newVal
}
return d / sampleTime, newVal
}
// NewStatLine constructs a statLine object from two mongoStatus objects.
func NewStatLine(oldMongo, newMongo mongoStatus, key string, all bool, sampleSecs int64) *statLine {
oldStat := *oldMongo.ServerStatus
newStat := *newMongo.ServerStatus
returnVal := &statLine{
Key: key,
Host: newStat.Host,
Version: newStat.Version,
Mapped: -1,
Virtual: -1,
Resident: -1,
NonMapped: -1,
Faults: -1,
}
returnVal.UptimeNanos = 1000 * 1000 * newStat.UptimeMillis
// set connection info
returnVal.CurrentC = newStat.Connections.Current
returnVal.AvailableC = newStat.Connections.Available
returnVal.TotalCreatedC = newStat.Connections.TotalCreated
// set the storage engine appropriately
if newStat.StorageEngine != nil && newStat.StorageEngine.Name != "" {
returnVal.StorageEngine = newStat.StorageEngine.Name
} else {
returnVal.StorageEngine = "mmapv1"
}
if newStat.Opcounters != nil && oldStat.Opcounters != nil {
returnVal.Insert, returnVal.InsertCnt = diff(newStat.Opcounters.Insert, oldStat.Opcounters.Insert, sampleSecs)
returnVal.Query, returnVal.QueryCnt = diff(newStat.Opcounters.Query, oldStat.Opcounters.Query, sampleSecs)
returnVal.Update, returnVal.UpdateCnt = diff(newStat.Opcounters.Update, oldStat.Opcounters.Update, sampleSecs)
returnVal.Delete, returnVal.DeleteCnt = diff(newStat.Opcounters.Delete, oldStat.Opcounters.Delete, sampleSecs)
returnVal.GetMore, returnVal.GetMoreCnt = diff(newStat.Opcounters.GetMore, oldStat.Opcounters.GetMore, sampleSecs)
returnVal.Command, returnVal.CommandCnt = diff(newStat.Opcounters.Command, oldStat.Opcounters.Command, sampleSecs)
}
if newStat.OpLatencies != nil {
if newStat.OpLatencies.Reads != nil {
returnVal.ReadOpsCnt = newStat.OpLatencies.Reads.Ops
returnVal.ReadLatency = newStat.OpLatencies.Reads.Latency
}
if newStat.OpLatencies.Writes != nil {
returnVal.WriteOpsCnt = newStat.OpLatencies.Writes.Ops
returnVal.WriteLatency = newStat.OpLatencies.Writes.Latency
}
if newStat.OpLatencies.Commands != nil {
returnVal.CommandOpsCnt = newStat.OpLatencies.Commands.Ops
returnVal.CommandLatency = newStat.OpLatencies.Commands.Latency
}
}
if newStat.Asserts != nil {
returnVal.Regular = newStat.Asserts.Regular
returnVal.Warning = newStat.Asserts.Warning
returnVal.Msg = newStat.Asserts.Msg
returnVal.User = newStat.Asserts.User
returnVal.Rollovers = newStat.Asserts.Rollovers
}
if newStat.TCMallocStats != nil {
if newStat.TCMallocStats.Generic != nil {
returnVal.TCMallocCurrentAllocatedBytes = newStat.TCMallocStats.Generic.CurrentAllocatedBytes
returnVal.TCMallocHeapSize = newStat.TCMallocStats.Generic.HeapSize
}