Skip to content

Gitlab Collector: Xid collector and test #848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions collector/collector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ func readMetric(m prometheus.Metric) MetricResult {
func sanitizeQuery(q string) string {
q = strings.Join(strings.Fields(q), " ")
q = strings.Replace(q, "(", "\\(", -1)
q = strings.Replace(q, "?", "\\?", -1)
q = strings.Replace(q, ")", "\\)", -1)
q = strings.Replace(q, "[", "\\[", -1)
q = strings.Replace(q, "]", "\\]", -1)
Expand Down
99 changes: 99 additions & 0 deletions collector/pg_xid.go
Original file line number Diff line number Diff line change
@@ -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 changes: 111 additions & 0 deletions collector/pg_xid_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}