Skip to content
This repository was archived by the owner on Nov 28, 2022. It is now read-only.

Commit a71195b

Browse files
committed
Add live tuples metric
1 parent c82d8e8 commit a71195b

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

gauges/table_rows.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,51 @@ func (g *Gauges) DatabaseDeadRows() prometheus.Gauge {
5353
"SELECT sum(coalesce(n_dead_tup, 0)) as n_dead_tup FROM pg_stat_user_tables",
5454
)
5555
}
56+
57+
type tableLiveRows struct {
58+
Table string `db:"relname"`
59+
LiveTuples float64 `db:"n_live_tup"`
60+
}
61+
62+
// TableLiveRows returns the estimated number of live rows of a given table
63+
func (g *Gauges) TableLiveRows() *prometheus.GaugeVec {
64+
var gauge = prometheus.NewGaugeVec(
65+
prometheus.GaugeOpts{
66+
Name: "postgresql_table_live_rows",
67+
Help: "Estimated number of live rows in table",
68+
ConstLabels: g.labels,
69+
},
70+
[]string{"table"},
71+
)
72+
73+
const tableLiveRowsQuery = `
74+
SELECT relname, coalesce(n_live_tup, 0) as n_live_tup FROM pg_stat_user_tables
75+
`
76+
77+
go func() {
78+
for {
79+
var tableLiveRows []tableLiveRows
80+
if err := g.query(tableLiveRowsQuery, &tableLiveRows, emptyParams); err == nil {
81+
for _, table := range tableLiveRows {
82+
gauge.With(prometheus.Labels{
83+
"table": table.Table,
84+
}).Set(table.LiveTuples)
85+
}
86+
}
87+
time.Sleep(g.interval)
88+
}
89+
}()
90+
return gauge
91+
}
92+
93+
// DatabaseLiveRows returns the sum of estimated number of live rows of all tables in a database
94+
func (g *Gauges) DatabaseLiveRows() prometheus.Gauge {
95+
return g.new(
96+
prometheus.GaugeOpts{
97+
Name: "postgresql_database_live_rows",
98+
Help: "Estimated number of live rows in database",
99+
ConstLabels: g.labels,
100+
},
101+
"SELECT sum(coalesce(n_live_tup, 0)) as n_live_tup FROM pg_stat_user_tables",
102+
)
103+
}

main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,9 @@ func watch(db *sql.DB, reg prometheus.Registerer, name string) {
110110
reg.MustRegister(gauges.DatabaseReadingUsage())
111111
reg.MustRegister(gauges.DatabaseWritingUsage())
112112
reg.MustRegister(gauges.HOTUpdates())
113+
reg.MustRegister(gauges.TableLiveRows())
113114
reg.MustRegister(gauges.TableDeadRows())
115+
reg.MustRegister(gauges.DatabaseLiveRows())
114116
reg.MustRegister(gauges.DatabaseDeadRows())
115117
reg.MustRegister(gauges.UnvacuumedTransactions())
116118
reg.MustRegister(gauges.LastTimeVacuumRan())

0 commit comments

Comments
 (0)