This commit is contained in:
Felix Yuan 2025-03-26 06:33:08 +00:00 committed by GitHub
commit ac630530e2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 210 additions and 0 deletions

99
collector/pg_xid.go Normal file
View File

@ -0,0 +1,99 @@
// Copyright 2023 The Prometheus Authors
// 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 collector
import (
"context"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus"
)
const xidSubsystem = "xid"
func init() {
registerCollector(xidSubsystem, defaultDisabled, NewPGXidCollector)
}
type PGXidCollector struct {
log log.Logger
}
func NewPGXidCollector(config collectorConfig) (Collector, error) {
return &PGXidCollector{log: config.logger}, nil
}
var (
xidCurrent = prometheus.NewDesc(
prometheus.BuildFQName(namespace, xidSubsystem, "current"),
"Current 64-bit transaction id of the query used to collect this metric (truncated to low 52 bits)",
[]string{}, prometheus.Labels{},
)
xidXmin = prometheus.NewDesc(
prometheus.BuildFQName(namespace, xidSubsystem, "xmin"),
"Oldest transaction id of a transaction still in progress, i.e. not known committed or aborted (truncated to low 52 bits)",
[]string{}, prometheus.Labels{},
)
xidXminAge = prometheus.NewDesc(
prometheus.BuildFQName(namespace, xidSubsystem, "xmin_age"),
"Age of oldest transaction still not committed or aborted measured in transaction ids",
[]string{}, prometheus.Labels{},
)
xidQuery = `
SELECT
CASE WHEN pg_is_in_recovery() THEN 'NaN'::float ELSE txid_current() % (2^52)::bigint END AS current,
CASE WHEN pg_is_in_recovery() THEN 'NaN'::float ELSE txid_snapshot_xmin(txid_current_snapshot()) % (2^52)::bigint END AS xmin,
CASE WHEN pg_is_in_recovery() THEN 'NaN'::float ELSE txid_current() - txid_snapshot_xmin(txid_current_snapshot()) END AS xmin_age
`
)
func (PGXidCollector) Update(ctx context.Context, instance *instance, ch chan<- prometheus.Metric) error {
db := instance.getDB()
rows, err := db.QueryContext(ctx,
xidQuery)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var current, xmin, xminAge float64
if err := rows.Scan(&current, &xmin, &xminAge); err != nil {
return err
}
ch <- prometheus.MustNewConstMetric(
xidCurrent,
prometheus.GaugeValue,
current,
)
ch <- prometheus.MustNewConstMetric(
xidXmin,
prometheus.GaugeValue,
xmin,
)
ch <- prometheus.MustNewConstMetric(
xidXminAge,
prometheus.GaugeValue,
xminAge,
)
}
if err := rows.Err(); err != nil {
return err
}
return nil
}

111
collector/pg_xid_test.go Normal file
View File

@ -0,0 +1,111 @@
// Copyright 2023 The Prometheus Authors
// 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 collector
import (
"context"
"math"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/smartystreets/goconvey/convey"
)
func TestPgXidCollector(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("Error opening a stub db connection: %s", err)
}
defer db.Close()
inst := &instance{db: db}
columns := []string{
"current",
"xmin",
"xmin_age",
}
rows := sqlmock.NewRows(columns).
AddRow(22, 25, 30)
mock.ExpectQuery(sanitizeQuery(xidQuery)).WillReturnRows(rows)
ch := make(chan prometheus.Metric)
go func() {
defer close(ch)
c := PGXidCollector{}
if err := c.Update(context.Background(), inst, ch); err != nil {
t.Errorf("Error calling PGXidCollector.Update: %s", err)
}
}()
expected := []MetricResult{
{labels: labelMap{}, value: 22, metricType: dto.MetricType_GAUGE},
{labels: labelMap{}, value: 25, metricType: dto.MetricType_GAUGE},
{labels: labelMap{}, value: 30, metricType: dto.MetricType_GAUGE},
}
convey.Convey("Metrics comparison", t, func() {
for _, expect := range expected {
m := readMetric(<-ch)
convey.So(expect, convey.ShouldResemble, m)
}
})
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled exceptions: %s", err)
}
}
func TestPgNanCollector(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("Error opening a stub db connection: %s", err)
}
defer db.Close()
inst := &instance{db: db}
columns := []string{
"current",
"xmin",
"xmin_age",
}
rows := sqlmock.NewRows(columns).
AddRow(math.NaN(), math.NaN(), math.NaN())
mock.ExpectQuery(sanitizeQuery(xidQuery)).WillReturnRows(rows)
ch := make(chan prometheus.Metric)
go func() {
defer close(ch)
c := PGXidCollector{}
if err := c.Update(context.Background(), inst, ch); err != nil {
t.Errorf("Error calling PGXidCollector.Update: %s", err)
}
}()
expected := []MetricResult{
{labels: labelMap{}, value: math.NaN(), metricType: dto.MetricType_GAUGE},
{labels: labelMap{}, value: math.NaN(), metricType: dto.MetricType_GAUGE},
{labels: labelMap{}, value: math.NaN(), metricType: dto.MetricType_GAUGE},
}
convey.Convey("Metrics comparison", t, func() {
for _, expect := range expected {
m := readMetric(<-ch)
convey.So(expect.labels, convey.ShouldResemble, m.labels)
convey.So(math.IsNaN(m.value), convey.ShouldResemble, math.IsNaN(expect.value))
convey.So(expect.metricType, convey.ShouldEqual, m.metricType)
}
})
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled exceptions: %s", err)
}
}