Skip to content

Commit a66da1d

Browse files
authored
Add collector for database/sql#DBStats (#866)
* Add collector for database/sql#DBStats Signed-off-by: Mitsuo Heijo <[email protected]>
1 parent b89620c commit a66da1d

4 files changed

+283
-0
lines changed
+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Copyright 2021 The Prometheus Authors
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package collectors
15+
16+
import (
17+
"database/sql"
18+
19+
"github.com/prometheus/client_golang/prometheus"
20+
)
21+
22+
type dbStatsCollector struct {
23+
db *sql.DB
24+
25+
maxOpenConnections *prometheus.Desc
26+
27+
openConnections *prometheus.Desc
28+
inUseConnections *prometheus.Desc
29+
idleConnections *prometheus.Desc
30+
31+
waitCount *prometheus.Desc
32+
waitDuration *prometheus.Desc
33+
maxIdleClosed *prometheus.Desc
34+
maxIdleTimeClosed *prometheus.Desc
35+
maxLifetimeClosed *prometheus.Desc
36+
}
37+
38+
// NewDBStatsCollector returns a collector that exports metrics about the given *sql.DB.
39+
// See https://golang.org/pkg/database/sql/#DBStats for more information on stats.
40+
func NewDBStatsCollector(db *sql.DB, dbName string) prometheus.Collector {
41+
fqName := func(name string) string {
42+
return "go_sql_" + name
43+
}
44+
return &dbStatsCollector{
45+
db: db,
46+
maxOpenConnections: prometheus.NewDesc(
47+
fqName("max_open_connections"),
48+
"Maximum number of open connections to the database.",
49+
nil, prometheus.Labels{"db_name": dbName},
50+
),
51+
openConnections: prometheus.NewDesc(
52+
fqName("open_connections"),
53+
"The number of established connections both in use and idle.",
54+
nil, prometheus.Labels{"db_name": dbName},
55+
),
56+
inUseConnections: prometheus.NewDesc(
57+
fqName("in_use_connections"),
58+
"The number of connections currently in use.",
59+
nil, prometheus.Labels{"db_name": dbName},
60+
),
61+
idleConnections: prometheus.NewDesc(
62+
fqName("idle_connections"),
63+
"The number of idle connections.",
64+
nil, prometheus.Labels{"db_name": dbName},
65+
),
66+
waitCount: prometheus.NewDesc(
67+
fqName("wait_count_total"),
68+
"The total number of connections waited for.",
69+
nil, prometheus.Labels{"db_name": dbName},
70+
),
71+
waitDuration: prometheus.NewDesc(
72+
fqName("wait_duration_seconds_total"),
73+
"The total time blocked waiting for a new connection.",
74+
nil, prometheus.Labels{"db_name": dbName},
75+
),
76+
maxIdleClosed: prometheus.NewDesc(
77+
fqName("max_idle_closed_total"),
78+
"The total number of connections closed due to SetMaxIdleConns.",
79+
nil, prometheus.Labels{"db_name": dbName},
80+
),
81+
maxIdleTimeClosed: prometheus.NewDesc(
82+
fqName("max_idle_time_closed_total"),
83+
"The total number of connections closed due to SetConnMaxIdleTime.",
84+
nil, prometheus.Labels{"db_name": dbName},
85+
),
86+
maxLifetimeClosed: prometheus.NewDesc(
87+
fqName("max_lifetime_closed_total"),
88+
"The total number of connections closed due to SetConnMaxLifetime.",
89+
nil, prometheus.Labels{"db_name": dbName},
90+
),
91+
}
92+
}
93+
94+
// Describe implements Collector.
95+
func (c *dbStatsCollector) Describe(ch chan<- *prometheus.Desc) {
96+
c.describe(ch)
97+
}
98+
99+
// Collect implements Collector.
100+
func (c *dbStatsCollector) Collect(ch chan<- prometheus.Metric) {
101+
c.collect(ch)
102+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2021 The Prometheus Authors
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
// +build go1.15
15+
16+
package collectors
17+
18+
import "github.com/prometheus/client_golang/prometheus"
19+
20+
func (c *dbStatsCollector) describe(ch chan<- *prometheus.Desc) {
21+
ch <- c.maxOpenConnections
22+
ch <- c.openConnections
23+
ch <- c.inUseConnections
24+
ch <- c.idleConnections
25+
ch <- c.waitCount
26+
ch <- c.waitDuration
27+
ch <- c.maxIdleClosed
28+
ch <- c.maxIdleTimeClosed
29+
ch <- c.maxLifetimeClosed
30+
}
31+
32+
func (c *dbStatsCollector) collect(ch chan<- prometheus.Metric) {
33+
stats := c.db.Stats()
34+
ch <- prometheus.MustNewConstMetric(c.maxOpenConnections, prometheus.GaugeValue, float64(stats.MaxOpenConnections))
35+
ch <- prometheus.MustNewConstMetric(c.openConnections, prometheus.GaugeValue, float64(stats.OpenConnections))
36+
ch <- prometheus.MustNewConstMetric(c.inUseConnections, prometheus.GaugeValue, float64(stats.InUse))
37+
ch <- prometheus.MustNewConstMetric(c.idleConnections, prometheus.GaugeValue, float64(stats.Idle))
38+
ch <- prometheus.MustNewConstMetric(c.waitCount, prometheus.CounterValue, float64(stats.WaitCount))
39+
ch <- prometheus.MustNewConstMetric(c.waitDuration, prometheus.CounterValue, stats.WaitDuration.Seconds())
40+
ch <- prometheus.MustNewConstMetric(c.maxIdleClosed, prometheus.CounterValue, float64(stats.MaxIdleClosed))
41+
ch <- prometheus.MustNewConstMetric(c.maxIdleTimeClosed, prometheus.CounterValue, float64(stats.MaxIdleTimeClosed))
42+
ch <- prometheus.MustNewConstMetric(c.maxLifetimeClosed, prometheus.CounterValue, float64(stats.MaxLifetimeClosed))
43+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Copyright 2021 The Prometheus Authors
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
// +build !go1.15
15+
16+
package collectors
17+
18+
import "github.com/prometheus/client_golang/prometheus"
19+
20+
func (c *dbStatsCollector) describe(ch chan<- *prometheus.Desc) {
21+
ch <- c.maxOpenConnections
22+
ch <- c.openConnections
23+
ch <- c.inUseConnections
24+
ch <- c.idleConnections
25+
ch <- c.waitCount
26+
ch <- c.waitDuration
27+
ch <- c.maxIdleClosed
28+
ch <- c.maxLifetimeClosed
29+
}
30+
31+
func (c *dbStatsCollector) collect(ch chan<- prometheus.Metric) {
32+
stats := c.db.Stats()
33+
ch <- prometheus.MustNewConstMetric(c.maxOpenConnections, prometheus.GaugeValue, float64(stats.MaxOpenConnections))
34+
ch <- prometheus.MustNewConstMetric(c.openConnections, prometheus.GaugeValue, float64(stats.OpenConnections))
35+
ch <- prometheus.MustNewConstMetric(c.inUseConnections, prometheus.GaugeValue, float64(stats.InUse))
36+
ch <- prometheus.MustNewConstMetric(c.idleConnections, prometheus.GaugeValue, float64(stats.Idle))
37+
ch <- prometheus.MustNewConstMetric(c.waitCount, prometheus.CounterValue, float64(stats.WaitCount))
38+
ch <- prometheus.MustNewConstMetric(c.waitDuration, prometheus.CounterValue, stats.WaitDuration.Seconds())
39+
ch <- prometheus.MustNewConstMetric(c.maxIdleClosed, prometheus.CounterValue, float64(stats.MaxIdleClosed))
40+
ch <- prometheus.MustNewConstMetric(c.maxLifetimeClosed, prometheus.CounterValue, float64(stats.MaxLifetimeClosed))
41+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// Copyright 2021 The Prometheus Authors
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package collectors
15+
16+
import (
17+
"database/sql"
18+
"runtime"
19+
"testing"
20+
21+
"github.com/prometheus/client_golang/prometheus"
22+
)
23+
24+
func TestDBStatsCollector(t *testing.T) {
25+
reg := prometheus.NewRegistry()
26+
{
27+
db := new(sql.DB)
28+
if err := reg.Register(NewDBStatsCollector(db, "db_A")); err != nil {
29+
t.Fatal(err)
30+
}
31+
}
32+
{
33+
db := new(sql.DB)
34+
if err := reg.Register(NewDBStatsCollector(db, "db_B")); err != nil {
35+
t.Fatal(err)
36+
}
37+
}
38+
39+
mfs, err := reg.Gather()
40+
if err != nil {
41+
t.Fatal(err)
42+
}
43+
44+
names := []string{
45+
"go_sql_max_open_connections",
46+
"go_sql_open_connections",
47+
"go_sql_in_use_connections",
48+
"go_sql_idle_connections",
49+
"go_sql_wait_count_total",
50+
"go_sql_wait_duration_seconds_total",
51+
"go_sql_max_idle_closed_total",
52+
"go_sql_max_lifetime_closed_total",
53+
}
54+
if runtime.Version() >= "go1.15" {
55+
names = append(names, "go_sql_max_idle_time_closed_total")
56+
}
57+
type result struct {
58+
found bool
59+
}
60+
results := make(map[string]result)
61+
for _, name := range names {
62+
results[name] = result{found: false}
63+
}
64+
for _, mf := range mfs {
65+
m := mf.GetMetric()
66+
if len(m) != 2 {
67+
t.Errorf("expected 2 metrics bug got %d", len(m))
68+
}
69+
labelA := m[0].GetLabel()[0]
70+
if name := labelA.GetName(); name != "db_name" {
71+
t.Errorf("expected to get label \"db_name\" but got %s", name)
72+
}
73+
if value := labelA.GetValue(); value != "db_A" {
74+
t.Errorf("expected to get value \"db_A\" but got %s", value)
75+
}
76+
labelB := m[1].GetLabel()[0]
77+
if name := labelB.GetName(); name != "db_name" {
78+
t.Errorf("expected to get label \"db_name\" but got %s", name)
79+
}
80+
if value := labelB.GetValue(); value != "db_B" {
81+
t.Errorf("expected to get value \"db_B\" but got %s", value)
82+
}
83+
84+
for _, name := range names {
85+
if name == mf.GetName() {
86+
results[name] = result{found: true}
87+
break
88+
}
89+
}
90+
}
91+
92+
for name, result := range results {
93+
if !result.found {
94+
t.Errorf("%s not found", name)
95+
}
96+
}
97+
}

0 commit comments

Comments
 (0)