/
report.go
1933 lines (1791 loc) · 47.2 KB
/
report.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 2023 RapidLoop, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"fmt"
"io"
"math"
"sort"
"strconv"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/rapidloop/pgmetrics"
)
// Postgres version constants
const (
pgv94 = 9_04_00
pgv95 = 9_05_00
pgv96 = 9_06_00
pgv10 = 10_00_00
pgv11 = 11_00_00
pgv12 = 12_00_00
pgv13 = 13_00_00
pgv14 = 14_00_00
)
func writeHumanTo(fd io.Writer, o options, result *pgmetrics.Model) {
if result.PgBouncer != nil {
pgbouncerWriteHumanTo(fd, o, result)
} else if result.Pgpool != nil {
pgpoolWriteHumanTo(fd, o, result)
} else {
postgresWriteHumanTo(fd, o, result)
}
}
func postgresWriteHumanTo(fd io.Writer, o options, result *pgmetrics.Model) {
version := getVersion(result)
sincePrior, _ := lsnDiff(result.RedoLSN, result.PriorLSN)
sinceRedo, _ := lsnDiff(result.CheckpointLSN, result.RedoLSN)
fmt.Fprintf(fd, `
pgmetrics run at: %s
PostgreSQL Cluster:
Name: %s
Server Version: %s
Server Started: %s`,
fmtTimeAndSince(result.Metadata.At),
getSetting(result, "cluster_name"),
getSetting(result, "server_version"),
fmtTimeAndSince(result.StartTime),
)
if version >= pgv96 {
fmt.Fprintf(fd, `
System Identifier: %s
Timeline: %d
Last Checkpoint: %s`,
result.SystemIdentifier,
result.TimelineID,
fmtTimeAndSince(result.CheckpointTime),
)
if result.PriorLSN != "" && result.RedoLSN != "" && result.CheckpointLSN != "" {
fmt.Fprintf(fd, `
Prior LSN: %s
REDO LSN: %s (%s since Prior)
Checkpoint LSN: %s (%s since REDO)`,
result.PriorLSN,
result.RedoLSN, humanize.IBytes(uint64(sincePrior)),
result.CheckpointLSN, humanize.IBytes(uint64(sinceRedo)),
)
} else if result.PriorLSN == "" && result.RedoLSN != "" && result.CheckpointLSN != "" {
fmt.Fprintf(fd, `
REDO LSN: %s
Checkpoint LSN: %s (%s since REDO)`,
result.RedoLSN,
result.CheckpointLSN, humanize.IBytes(uint64(sinceRedo)),
)
}
fmt.Fprintf(fd, `
Transaction IDs: %s`,
fmtXIDRange(int64(result.OldestXid), int64(result.NextXid)),
)
}
if result.LastXactTimestamp != 0 {
fmt.Fprintf(fd, `
Last Transaction: %s`,
fmtTimeAndSince(result.LastXactTimestamp),
)
}
if version >= pgv96 {
fmt.Fprintf(fd, `
Notification Queue: %.1f%% used`, result.NotificationQueueUsage)
}
fmt.Fprintf(fd, `
Active Backends: %d (max %s)
Recovery Mode? %s
`,
len(result.Backends), getSetting(result, "max_connections"),
fmtYesNo(result.IsInRecovery),
)
if result.System != nil {
reportSystem(fd, result)
}
if result.IsInRecovery {
reportRecovery(fd, result)
}
if result.ReplicationIncoming != nil {
reportReplicationIn(fd, result)
}
if len(result.ReplicationOutgoing) > 0 {
reportReplicationOut(fd, result)
}
if len(result.ReplicationSlots) > 0 {
reportReplicationSlots(fd, result, version)
}
reportWAL(fd, result, version)
reportBGWriter(fd, result)
reportBackends(fd, o.tooLongSec, result)
reportLocks(fd, result)
if version >= pgv96 {
reportVacuumProgress(fd, result)
}
reportProgress(fd, result)
reportDeadlocks(fd, result)
reportAutovacuums(fd, result)
reportRoles(fd, result)
reportTablespaces(fd, result)
reportDatabases(fd, result)
reportTables(fd, result)
fmt.Fprintln(fd)
}
func reportRecovery(fd io.Writer, result *pgmetrics.Model) {
fmt.Fprintf(fd, `
Recovery Status:
Replay paused: %s
Received LSN: %s
Replayed LSN: %s%s
Last Replayed Txn: %s
`,
fmtYesNo(result.IsWalReplayPaused),
result.LastWALReceiveLSN,
result.LastWALReplayLSN,
fmtLag(result.LastWALReceiveLSN, result.LastWALReplayLSN, ""),
fmtTimeAndSince(result.LastXActReplayTimestamp))
}
func reportReplicationIn(fd io.Writer, result *pgmetrics.Model) {
ri := result.ReplicationIncoming
var recvDiff string
if d, ok := lsnDiff(ri.ReceivedLSN, ri.ReceiveStartLSN); ok && d > 0 {
recvDiff = ", " + humanize.IBytes(uint64(d))
}
fmt.Fprintf(fd, `
Incoming Replication Stats:
Status: %s
Received LSN: %s (started at %s%s)
Timeline: %d (was %d at start)
Latency: %s
Replication Slot: %s
`,
ri.Status,
ri.ReceivedLSN, ri.ReceiveStartLSN, recvDiff,
ri.ReceivedTLI, ri.ReceiveStartTLI,
fmtMicros(ri.Latency),
ri.SlotName)
}
func reportReplicationOut(fd io.Writer, result *pgmetrics.Model) {
routs := result.ReplicationOutgoing
fmt.Fprintf(fd, `
Outgoing Replication Stats:`)
for i, r := range routs {
var sp string
if r.SyncPriority != -1 {
sp = strconv.Itoa(r.SyncPriority)
}
fmt.Fprintf(fd, `
Destination #%d:
User: %s
Application: %s
Client Address: %s
State: %s
Started At: %s
Sent LSN: %s
Written Until: %s%s
Flushed Until: %s%s
Replayed Until: %s%s
Sync Priority: %s
Sync State: %s`,
i+1,
r.RoleName,
r.ApplicationName,
r.ClientAddr,
r.State,
fmtTimeAndSince(r.BackendStart),
r.SentLSN,
r.WriteLSN, fmtLag(r.SentLSN, r.WriteLSN, "write"),
r.FlushLSN, fmtLag(r.WriteLSN, r.FlushLSN, "flush"),
r.ReplayLSN, fmtLag(r.FlushLSN, r.ReplayLSN, "replay"),
sp,
r.SyncState,
)
}
fmt.Fprintln(fd)
}
func reportReplicationSlots(fd io.Writer, result *pgmetrics.Model, version int) {
var phy, log int
for _, r := range result.ReplicationSlots {
if r.SlotType == "physical" {
phy++
} else {
log++
}
}
if phy > 0 {
fmt.Fprintf(fd, `
Physical Replication Slots:
`)
var tw tableWriter
cols := []interface{}{"Name", "Active", "Oldest Txn ID", "Restart LSN"}
if version >= pgv10 {
cols = append(cols, "Temporary")
}
tw.add(cols...)
for _, r := range result.ReplicationSlots {
if r.SlotType != "physical" {
continue
}
vals := []interface{}{r.SlotName, fmtYesNo(r.Active),
fmtIntZero(r.Xmin), r.RestartLSN}
if version >= pgv10 {
vals = append(vals, fmtYesNo(r.Temporary))
}
tw.add(vals...)
}
tw.write(fd, " ")
}
if log > 0 {
fmt.Fprintf(fd, `
Logical Replication Slots:
`)
var tw tableWriter
cols := []interface{}{"Name", "Plugin", "Database", "Active",
"Oldest Txn ID", "Restart LSN", "Flushed Until"}
if version >= pgv10 {
cols = append(cols, "Temporary")
}
tw.add(cols...)
for _, r := range result.ReplicationSlots {
if r.SlotType != "logical" {
continue
}
vals := []interface{}{r.SlotName, r.Plugin, r.DBName,
fmtYesNo(r.Active), fmtIntZero(r.Xmin), r.RestartLSN,
r.ConfirmedFlushLSN}
if version >= pgv10 {
vals = append(vals, fmtYesNo(r.Temporary))
}
tw.add(vals...)
}
tw.write(fd, " ")
}
}
// WAL files and archiving
func reportWAL(fd io.Writer, result *pgmetrics.Model, version int) {
archiveMode := getSetting(result, "archive_mode") == "on"
fmt.Fprintf(fd, `
WAL Files:
WAL Archiving? %s`,
fmtYesNo(archiveMode),
)
if result.WALCount != -1 {
fmt.Fprintf(fd, `
WAL Files: %d`,
result.WALCount)
}
if archiveMode {
var rate float64
secs := result.Metadata.At - result.WALArchiving.StatsReset
if secs > 0 {
rate = float64(result.WALArchiving.ArchivedCount) / (float64(secs) / 60)
}
var rf string
if result.WALReadyCount > -1 {
rf = strconv.Itoa(result.WALReadyCount)
}
fmt.Fprintf(fd, `
Ready Files: %s
Archive Rate: %.2f per min
Last Archived: %s
Last Failure: %s
Totals: %d succeeded, %d failed
Totals Since: %s`,
rf,
rate,
fmtTimeAndSince(result.WALArchiving.LastArchivedTime),
fmtTimeAndSince(result.WALArchiving.LastFailedTime),
result.WALArchiving.ArchivedCount, result.WALArchiving.FailedCount,
fmtTimeAndSince(result.WALArchiving.StatsReset),
)
}
fmt.Fprintln(fd)
maxwalk, maxwalv := getMaxWalSize(result)
var tw1 tableWriter
tw1.add("Setting", "Value")
tw1.add("wal_level", getSetting(result, "wal_level"))
tw1.add("archive_timeout", getSetting(result, "archive_timeout"))
tw1.add("wal_compression", getSetting(result, "wal_compression"))
tw1.add(maxwalk, maxwalv)
if mws := getMinWalSize(result); mws != "" {
tw1.add("min_wal_size", mws)
}
tw1.add("checkpoint_timeout", getSetting(result, "checkpoint_timeout"))
tw1.add("full_page_writes", getSetting(result, "full_page_writes"))
if version >= pgv13 {
tw1.add("wal_keep_size", getSettingBytes(result, "wal_keep_size", 1024*1024))
} else {
tw1.add("wal_keep_segments", getSetting(result, "wal_keep_segments"))
}
tw1.write(fd, " ")
}
func reportBGWriter(fd io.Writer, result *pgmetrics.Model) {
bgw := result.BGWriter
blkSize := getBlockSize(result)
var rate float64
secs := result.Metadata.At - bgw.StatsReset
ncps := bgw.CheckpointsTimed + bgw.CheckpointsRequested
if secs > 0 {
rate = float64(ncps) / (float64(secs) / 60)
}
totBuffers := bgw.BuffersCheckpoint + bgw.BuffersClean + bgw.BuffersBackend
var pctSched, pctReq, avgWrite, rateBuffers float64
if ncps > 0 {
ncpsf := float64(ncps)
pctSched = 100 * float64(bgw.CheckpointsTimed) / ncpsf
pctReq = 100 * float64(bgw.CheckpointsRequested) / ncpsf
avgWrite = float64(bgw.BuffersCheckpoint) * float64(blkSize) / ncpsf
}
if secs > 0 {
rateBuffers = float64(totBuffers) / float64(secs)
}
var pctBufCP, pctBufBGW, pctBufBE float64
if totBuffers > 0 {
totBuffersf := float64(totBuffers)
pctBufCP = 100 * float64(bgw.BuffersCheckpoint) / totBuffersf
pctBufBGW = 100 * float64(bgw.BuffersClean) / totBuffersf
pctBufBE = 100 * float64(bgw.BuffersBackend) / totBuffersf
}
fmt.Fprintf(fd, `
BG Writer:
Checkpoint Rate: %.2f per min
Average Write: %s per checkpoint
Total Checkpoints: %d sched (%.1f%%) + %d req (%.1f%%) = %d
Total Write: %s, @ %s per sec
Buffers Allocated: %d (%s)
Buffers Written: %d chkpt (%.1f%%) + %d bgw (%.1f%%) + %d be (%.1f%%)
Clean Scan Stops: %d
BE fsyncs: %d
Counts Since: %s
`,
rate,
humanize.IBytes(uint64(avgWrite)),
bgw.CheckpointsTimed, pctSched,
bgw.CheckpointsRequested, pctReq, ncps,
humanize.IBytes(uint64(blkSize)*uint64(totBuffers)),
humanize.IBytes(uint64(float64(blkSize)*rateBuffers)),
bgw.BuffersAlloc, humanize.IBytes(uint64(blkSize)*uint64(bgw.BuffersAlloc)),
bgw.BuffersCheckpoint, pctBufCP,
bgw.BuffersClean, pctBufBGW,
bgw.BuffersBackend, pctBufBE,
bgw.MaxWrittenClean, bgw.BuffersBackendFsync,
fmtTimeAndSince(bgw.StatsReset),
)
var tw tableWriter
tw.add("Setting", "Value")
tw.add("bgwriter_delay", getSetting(result, "bgwriter_delay")+" msec")
tw.add("bgwriter_flush_after", getSettingBytes(result, "bgwriter_flush_after", uint64(blkSize)))
tw.add("bgwriter_lru_maxpages", getSetting(result, "bgwriter_lru_maxpages"))
tw.add("bgwriter_lru_multiplier", getSetting(result, "bgwriter_lru_multiplier"))
tw.add("block_size", getSetting(result, "block_size"))
tw.add("checkpoint_timeout", getSetting(result, "checkpoint_timeout")+" sec")
tw.add("checkpoint_completion_target", getSetting(result, "checkpoint_completion_target"))
tw.write(fd, " ")
}
func isWaitingLock(be *pgmetrics.Backend) bool {
if be.WaitEventType == "waiting" && be.WaitEvent == "waiting" {
return true // before v9.6, see collector.getActivity94
}
return be.WaitEventType == "Lock"
}
func isWaitingOther(be *pgmetrics.Backend) bool {
return len(be.WaitEventType) > 0 && be.WaitEventType != "Lock" && be.WaitEventType != "waiting"
}
func reportBackends(fd io.Writer, tooLongSecs uint, result *pgmetrics.Model) {
n := len(result.Backends)
max := getSettingInt(result, "max_connections")
isTooLong := func(be *pgmetrics.Backend) bool {
return be.XactStart > 0 && result.Metadata.At-be.XactStart > int64(tooLongSecs)
}
var waitingLocks, waitingOther, idlexact, toolong int
for _, be := range result.Backends {
if isWaitingLock(&be) {
waitingLocks++
}
if isWaitingOther(&be) {
waitingOther++
}
if strings.HasPrefix(be.State, "idle in transaction") {
idlexact++
}
if isTooLong(&be) {
toolong++
}
}
// header
fmt.Fprintf(fd, `
Backends:
Total Backends: %d (%.1f%% of max %d)
Problematic: %d waiting on locks, %d waiting on other, %d xact too long, %d idle in xact`,
n, 100*safeDiv(int64(n), int64(max)), max,
waitingLocks, waitingOther, toolong, idlexact,
)
// "waiting for locks" backends
if waitingLocks > 0 {
fmt.Fprint(fd, `
Waiting for Locks:
`)
var tw tableWriter
tw.add("PID", "User", "App", "Client Addr", "Database", "Wait", "Query Start")
for _, be := range result.Backends {
if isWaitingLock(&be) {
tw.add(be.PID, be.RoleName, be.ApplicationName, be.ClientAddr,
be.DBName, be.WaitEventType+" / "+be.WaitEvent,
fmtTime(be.QueryStart))
}
}
tw.write(fd, " ")
}
// "other waiting" backends
if waitingOther > 0 {
fmt.Fprint(fd, `
Other Waiting Backends:
`)
var tw tableWriter
tw.add("PID", "User", "App", "Client Addr", "Database", "Wait", "Query Start")
for _, be := range result.Backends {
if isWaitingOther(&be) {
tw.add(be.PID, be.RoleName, be.ApplicationName, be.ClientAddr,
be.DBName, be.WaitEventType+" / "+be.WaitEvent,
fmtTime(be.QueryStart))
}
}
tw.write(fd, " ")
}
// long running xacts
if toolong > 0 {
fmt.Fprintf(fd, `
Long Running (>%d sec) Transactions:
`, tooLongSecs)
var tw tableWriter
tw.add("PID", "User", "App", "Client Addr", "Database", "Transaction Start")
for _, be := range result.Backends {
if isTooLong(&be) {
tw.add(be.PID, be.RoleName, be.ApplicationName, be.ClientAddr, be.DBName,
fmtTimeAndSince(be.XactStart))
}
}
tw.write(fd, " ")
}
// idle in xact backends
if idlexact > 0 {
fmt.Fprint(fd, `
Idling in Transaction:
`)
var tw tableWriter
tw.add("PID", "User", "App", "Client Addr", "Database", "Aborted?", "State Change")
for _, be := range result.Backends {
if strings.HasPrefix(be.State, "idle in transaction") {
tw.add(be.PID, be.RoleName, be.ApplicationName, be.ClientAddr,
be.DBName, fmtYesNo(strings.Contains(be.State, "aborted")),
fmtTime(be.StateChange))
}
}
tw.write(fd, " ")
}
if waitingOther+waitingLocks+idlexact+toolong == 0 {
fmt.Fprintln(fd)
}
}
type lockCount struct {
notGranted int
total int
}
func reportLocks(fd io.Writer, result *pgmetrics.Model) {
if len(result.Locks) == 0 {
return
}
c := make(map[string]*lockCount)
for _, l := range result.Locks {
lc, ok := c[l.LockType]
if !ok {
lc = &lockCount{}
c[l.LockType] = lc
}
if !l.Granted {
lc.notGranted++
}
lc.total++
}
lt := make([]string, 0, len(c))
for k := range c {
lt = append(lt, k)
}
sort.Strings(lt)
fmt.Fprint(fd, `
Locks:
`)
var tw tableWriter
tw.add("Lock Type", "Not Granted", "Total")
var tot1, tot2 int
for _, t := range lt {
lc, ok := c[t]
if !ok || lc == nil {
continue
}
tw.add(t, lc.notGranted, lc.total)
tot1 += lc.notGranted
tot2 += lc.total
}
tw.add("", tot1, tot2)
tw.hasFooter = true
tw.write(fd, " ")
}
func reportVacuumProgress(fd io.Writer, result *pgmetrics.Model) {
fmt.Fprint(fd, `
Vacuum Progress:`)
if len(result.VacuumProgress) > 0 {
for i, v := range result.VacuumProgress {
sp := fmt.Sprintf("%d of %d (%.1f%% complete)", v.HeapBlksScanned,
v.HeapBlksTotal, 100*safeDiv(v.HeapBlksScanned, v.HeapBlksTotal))
fmt.Fprintf(fd, `
Vacuum Process #%d:
Phase: %s
Database: %s
Table: %s
Scan Progress: %s
Heap Blks Vac'ed: %d of %d
Idx Vac Cycles: %d
Dead Tuples: %d
Dead Tuples Max: %d`,
i+1,
v.Phase,
v.DBName,
v.TableName,
sp,
v.HeapBlksVacuumed, v.HeapBlksTotal,
v.IndexVacuumCount,
v.NumDeadTuples,
v.MaxDeadTuples,
)
}
} else {
fmt.Fprint(fd, `
No manual or auto vacuum jobs in progress.`)
}
fmt.Fprintln(fd)
// settings
var tw tableWriter
add := func(s string) { tw.add(s, getSetting(result, s)) }
tw.add("Setting", "Value")
tw.add("maintenance_work_mem", getSettingBytes(result, "maintenance_work_mem", 1024))
add("autovacuum")
add("autovacuum_analyze_threshold")
add("autovacuum_vacuum_threshold")
add("autovacuum_freeze_max_age")
add("autovacuum_max_workers")
tw.add("autovacuum_naptime", getSetting(result, "autovacuum_naptime")+" sec")
add("vacuum_freeze_min_age")
add("vacuum_freeze_table_age")
tw.write(fd, " ")
}
func reportProgress(fd io.Writer, result *pgmetrics.Model) {
if len(result.VacuumProgress)+len(result.AnalyzeProgress)+
len(result.BasebackupProgress)+len(result.ClusterProgress)+
len(result.CopyProgress)+len(result.CreateIndexProgress) == 0 {
return // no jobs in progress
}
var tw tableWriter
tw.add("Job", "Backend", "Working On", "Status")
// analyze
for _, a := range result.AnalyzeProgress {
object := "?"
if t := result.TableByOID(a.TableOID); t != nil {
object = a.DBName + "." + t.Name
}
tw.add("ANALYZE", a.PID, object, a.Phase)
}
// basebackup
for _, b := range result.BasebackupProgress {
tw.add("BASEBACKUP", b.PID, "", b.Phase)
}
// cluster / vacuum full
for _, c := range result.ClusterProgress {
object := "?"
if t := result.TableByOID(c.TableOID); t != nil {
object = c.DBName + "." + t.Name
}
tw.add(c.Command, c.PID, object, c.Phase)
}
// copy from / copy to
for _, c := range result.CopyProgress {
object := "(query)"
if t := result.TableByOID(c.TableOID); t != nil {
object = c.DBName + "." + t.Name
}
tw.add(c.Command, c.PID, object, "")
}
// create index (concurrently) / reindex (concurrently)
for _, c := range result.CreateIndexProgress {
object := "?"
if t := result.TableByOID(c.TableOID); t != nil {
object = c.DBName + "." + t.Name
if idx := result.IndexByOID(c.IndexOID); idx != nil {
object += "." + idx.Name
}
}
tw.add(c.Command, c.PID, object, c.Phase)
}
// vacuum
for _, v := range result.VacuumProgress {
object := "?"
if t := result.TableByOID(v.TableOID); t != nil {
object = v.DBName + "." + t.Name
}
tw.add("VACUUM", v.PID, object, v.Phase)
}
fmt.Fprint(fd, `
Jobs In Progress:
`)
tw.write(fd, " ")
}
func reportDeadlocks(fd io.Writer, result *pgmetrics.Model) {
if len(result.Deadlocks) == 0 {
return // no recent deadlocks
}
var tw tableWriter
tw.add("At", "Detail")
for i, d := range result.Deadlocks {
detail := strings.ReplaceAll(d.Detail, "\r", "")
detail = strings.TrimSpace(detail)
lines := strings.Split(detail, "\n")
if n := len(lines); n > 0 {
tw.add(fmtTime(d.At), lines[0])
for j := 1; j < n; j++ {
tw.add("", lines[j])
}
if i < len(result.Deadlocks)-1 {
tw.add(twLine, 0)
}
}
}
fmt.Fprint(fd, `
Recent Deadlocks:
`)
tw.write(fd, " ")
}
func reportAutovacuums(fd io.Writer, result *pgmetrics.Model) {
if len(result.AutoVacuums) == 0 {
return // no recent autovacuums
}
var tw tableWriter
tw.add("At", "Table", "Time Taken (sec)")
for _, a := range result.AutoVacuums {
tw.add(fmtTime(a.At), a.Table, fmt.Sprintf("%.1f", a.Elapsed))
}
fmt.Fprint(fd, `
Recent Autovacuums:
`)
tw.write(fd, " ")
}
func reportRoles(fd io.Writer, result *pgmetrics.Model) {
fmt.Fprint(fd, `
Roles:
`)
var tw tableWriter
tw.add("Name", "Login", "Repl", "Super", "Creat Rol", "Creat DB", "Bypass RLS", "Inherit", "Expires", "Member Of")
for _, r := range result.Roles {
tw.add(
r.Name,
fmtYesBlank(r.Rolcanlogin),
fmtYesBlank(r.Rolreplication),
fmtYesBlank(r.Rolsuper),
fmtYesBlank(r.Rolcreaterole),
fmtYesBlank(r.Rolcreatedb),
fmtYesBlank(r.Rolbypassrls),
fmtYesBlank(r.Rolinherit),
fmtTime(r.Rolvaliduntil),
strings.Join(r.MemberOf, ", "),
)
}
tw.write(fd, " ")
}
func reportTablespaces(fd io.Writer, result *pgmetrics.Model) {
fmt.Fprint(fd, `
Tablespaces:
`)
var tw tableWriter
if result.Metadata.Local {
tw.add("Name", "Owner", "Location", "Size", "Disk Used", "Inode Used")
} else {
tw.add("Name", "Owner", "Location", "Size")
}
for _, t := range result.Tablespaces {
var s, du, iu string
if t.Size != -1 {
s = humanize.IBytes(uint64(t.Size))
}
if result.Metadata.Local && t.DiskUsed > 0 && t.DiskTotal > 0 {
du = fmt.Sprintf("%s (%.1f%%) of %s",
humanize.IBytes(uint64(t.DiskUsed)),
100*safeDiv(t.DiskUsed, t.DiskTotal),
humanize.IBytes(uint64(t.DiskTotal)))
}
if result.Metadata.Local && t.InodesUsed > 0 && t.InodesTotal > 0 {
iu = fmt.Sprintf("%d (%.1f%%) of %d",
t.InodesUsed,
100*safeDiv(t.InodesUsed, t.InodesTotal),
t.InodesTotal)
}
if (t.Name == "pg_default" || t.Name == "pg_global") && t.Location != "" {
t.Location = "$PGDATA = " + t.Location
}
if result.Metadata.Local {
tw.add(t.Name, t.Owner, t.Location, s, du, iu)
} else {
tw.add(t.Name, t.Owner, t.Location, s)
}
}
tw.write(fd, " ")
}
func getTablespaceName(oid int, result *pgmetrics.Model) string {
for _, t := range result.Tablespaces {
if t.OID == oid {
return t.Name
}
}
return ""
}
func getRoleName(oid int, result *pgmetrics.Model) string {
for _, r := range result.Roles {
if r.OID == oid {
return r.Name
}
}
return ""
}
func fmtConns(d *pgmetrics.Database) string {
if d.DatConnLimit < 0 {
return fmt.Sprintf("%d (no max limit)", d.NumBackends)
}
pct := 100 * safeDiv(int64(d.NumBackends), int64(d.DatConnLimit))
return fmt.Sprintf("%d (%.1f%%) of %d", d.NumBackends, pct, d.DatConnLimit)
}
func reportDatabases(fd io.Writer, result *pgmetrics.Model) {
for i, d := range result.Databases {
fmt.Fprintf(fd, `
Database #%d:
Name: %s
Owner: %s
Tablespace: %s
Connections: %s
Frozen Xid Age: %d
Transactions: %d (%.1f%%) commits, %d (%.1f%%) rollbacks
Cache Hits: %.1f%%
Rows Changed: ins %.1f%%, upd %.1f%%, del %.1f%%
Total Temp: %s in %d files
Problems: %d deadlocks, %d conflicts
Totals Since: %s`,
i+1,
d.Name,
getRoleName(d.DatDBA, result),
getTablespaceName(d.DatTablespace, result),
fmtConns(&d),
d.AgeDatFrozenXid,
d.XactCommit, 100*safeDiv(d.XactCommit, d.XactCommit+d.XactRollback),
d.XactRollback, 100*safeDiv(d.XactRollback, d.XactCommit+d.XactRollback),
100*safeDiv(d.BlksHit, d.BlksHit+d.BlksRead),
100*safeDiv(d.TupInserted, d.TupInserted+d.TupUpdated+d.TupDeleted),
100*safeDiv(d.TupUpdated, d.TupInserted+d.TupUpdated+d.TupDeleted),
100*safeDiv(d.TupDeleted, d.TupInserted+d.TupUpdated+d.TupDeleted),
humanize.IBytes(uint64(d.TempBytes)), d.TempFiles,
d.Deadlocks, d.Conflicts,
fmtTimeAndSince(d.StatsReset),
)
if d.Size != -1 {
fmt.Fprintf(fd, `
Size: %s`, humanize.IBytes(uint64(d.Size)))
}
fmt.Fprintln(fd)
gap := false
if sqs := filterSequencesByDB(result, d.Name); len(sqs) > 0 {
fmt.Fprint(fd, ` Sequences:
`)
var tw tableWriter
tw.add("Sequence", "Cache Hits")
for _, sq := range sqs {
tw.add(sq.Name, fmtPct(sq.BlksHit, sq.BlksHit+sq.BlksRead))
}
tw.write(fd, " ")
gap = true
}
if ufs := filterUserFuncsByDB(result, d.Name); len(ufs) > 0 {
if gap {
fmt.Fprintln(fd)
}
fmt.Fprint(fd, ` Tracked Functions:
`)
var tw tableWriter
tw.add("Function", "Calls", "Time (self)", "Time (self+children)")
for _, uf := range ufs {
tw.add(
uf.Name,
uf.Calls,
time.Duration(uf.SelfTime*1e6),
time.Duration(uf.TotalTime*1e6),
)
}
tw.write(fd, " ")
gap = true
}
if exts := filterExtensionsByDB(result, d.Name); len(exts) > 0 {
if gap {
fmt.Fprintln(fd)
}
fmt.Fprint(fd, ` Installed Extensions:
`)
var tw tableWriter
tw.add("Name", "Version", "Comment")
for _, ext := range exts {
tw.add(ext.Name, ext.InstalledVersion, ext.Comment)
}
tw.write(fd, " ")
gap = true
}
if dts := filterTriggersByDB(result, d.Name); len(dts) > 0 {
if gap {
fmt.Fprintln(fd)
}
fmt.Fprint(fd, ` Disabled Triggers:
`)
var tw tableWriter
tw.add("Name", "Table", "Procedure")
for _, dt := range dts {
tw.add(
dt.Name,
dt.SchemaName+"."+dt.TableName,
dt.ProcName,
)
}
tw.write(fd, " ")
gap = true
}
if ss := filterStatementsByDB(result, d.Name); len(ss) > 0 {
if gap {
fmt.Fprintln(fd)
}
fmt.Fprint(fd, ` Slow Queries:
`)
var tw tableWriter
tw.add("Calls", "Avg Time", "Total Time", "Rows/Call", "Query")
for _, s := range ss {
var rpc int64
if s.Calls > 0 {
rpc = s.Rows / s.Calls
}
tw.add(
s.Calls,
prepmsec(s.TotalTime/float64(s.Calls)),
prepmsec(s.TotalTime),
rpc,
prepQ(s.Query),
)
}
tw.write(fd, " ")
gap = true
}
if pp := filterPublicationsByDB(result, d.Name); len(pp) > 0 {
if gap {
fmt.Fprintln(fd)
}
fmt.Fprintf(fd, ` Logical Replication Publications:
`)
var tw tableWriter
tw.add("Name", "All Tables?", "Propagate", "Tables")
for _, p := range pp {
tw.add(
p.Name,
fmtYesNo(p.AllTables),
fmtPropagate(p.Insert, p.Update, p.Delete),
p.TableCount,
)
}
tw.write(fd, " ")
gap = true
}
if ss := filterSubscriptionsByDB(result, d.Name); len(ss) > 0 {
if gap {
fmt.Fprintln(fd)
}
fmt.Fprintf(fd, ` Logical Replication Subscriptions:
`)
for i, s := range ss {
fmt.Fprintf(fd, ` Subscription #%d:
Name: %s
Enabled? %s
Publications: %d
Tables: %d
Workers: %d
Received Until: %s
Latency: %s
`,
i+1,
s.Name,