pangolin_exporter
91 строка · 2.4 Кб
1// Copyright 2023 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
14package collector
15
16import (
17"context"
18
19"github.com/blang/semver/v4"
20"github.com/go-kit/log"
21"github.com/go-kit/log/level"
22"github.com/prometheus/client_golang/prometheus"
23)
24
25const xlogLocationSubsystem = "xlog_location"
26
27func init() {
28registerCollector(xlogLocationSubsystem, defaultDisabled, NewPGXlogLocationCollector)
29}
30
31type PGXlogLocationCollector struct {
32log log.Logger
33}
34
35func NewPGXlogLocationCollector(config collectorConfig) (Collector, error) {
36return &PGXlogLocationCollector{log: config.logger}, nil
37}
38
39var (
40xlogLocationBytes = prometheus.NewDesc(
41prometheus.BuildFQName(namespace, xlogLocationSubsystem, "bytes"),
42"Postgres LSN (log sequence number) being generated on primary or replayed on replica (truncated to low 52 bits)",
43[]string{},
44prometheus.Labels{},
45)
46
47xlogLocationQuery = `
48SELECT CASE
49WHEN pg_is_in_recovery() THEN (pg_last_xlog_replay_location() - '0/0') % (2^52)::bigint
50ELSE (pg_current_xlog_location() - '0/0') % (2^52)::bigint
51END AS bytes
52`
53)
54
55func (c PGXlogLocationCollector) Update(ctx context.Context, instance *instance, ch chan<- prometheus.Metric) error {
56db := instance.getDB()
57
58// xlog was renmaed to WAL in PostgreSQL 10
59// https://wiki.postgresql.org/wiki/New_in_postgres_10#Renaming_of_.22xlog.22_to_.22wal.22_Globally_.28and_location.2Flsn.29
60after10 := instance.version.Compare(semver.MustParse("10.0.0"))
61if after10 >= 0 {
62level.Warn(c.log).Log("msg", "xlog_location collector is not available on PostgreSQL >= 10.0.0, skipping")
63return nil
64}
65
66rows, err := db.QueryContext(ctx,
67xlogLocationQuery)
68
69if err != nil {
70return err
71}
72defer rows.Close()
73
74for rows.Next() {
75var bytes float64
76
77if err := rows.Scan(&bytes); err != nil {
78return err
79}
80
81ch <- prometheus.MustNewConstMetric(
82xlogLocationBytes,
83prometheus.GaugeValue,
84bytes,
85)
86}
87if err := rows.Err(); err != nil {
88return err
89}
90return nil
91}
92