pangolin_exporter
106 строк · 2.7 Кб
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"database/sql"
18"fmt"
19"regexp"
20
21"github.com/blang/semver/v4"
22)
23
24type instance struct {
25dsn string
26db *sql.DB
27version semver.Version
28}
29
30func newInstance(dsn string) (*instance, error) {
31i := &instance{
32dsn: dsn,
33}
34
35// "Create" a database handle to verify the DSN provided is valid.
36// Open is not guaranteed to create a connection.
37db, err := sql.Open("postgres", dsn)
38if err != nil {
39return nil, err
40}
41db.Close()
42
43return i, nil
44}
45
46// copy returns a copy of the instance.
47func (i *instance) copy() *instance {
48return &instance{
49dsn: i.dsn,
50}
51}
52
53func (i *instance) setup() error {
54db, err := sql.Open("postgres", i.dsn)
55if err != nil {
56return err
57}
58db.SetMaxOpenConns(1)
59db.SetMaxIdleConns(1)
60i.db = db
61
62version, err := queryVersion(i.db)
63if err != nil {
64return fmt.Errorf("error querying postgresql version: %w", err)
65} else {
66i.version = version
67}
68return nil
69}
70
71func (i *instance) getDB() *sql.DB {
72return i.db
73}
74
75func (i *instance) Close() error {
76return i.db.Close()
77}
78
79// Regex used to get the "short-version" from the postgres version field.
80// The result of SELECT version() is something like "PostgreSQL 9.6.2 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 6.2.1 20160830, 64-bit"
81var versionRegex = regexp.MustCompile(`^\w+ ((\d+)(\.\d+)?(\.\d+)?)`)
82var serverVersionRegex = regexp.MustCompile(`^((\d+)(\.\d+)?(\.\d+)?)`)
83
84func queryVersion(db *sql.DB) (semver.Version, error) {
85var version string
86err := db.QueryRow("SELECT version();").Scan(&version)
87if err != nil {
88return semver.Version{}, err
89}
90submatches := versionRegex.FindStringSubmatch(version)
91if len(submatches) > 1 {
92return semver.ParseTolerant(submatches[1])
93}
94
95// We could also try to parse the version from the server_version field.
96// This is of the format 13.3 (Debian 13.3-1.pgdg100+1)
97err = db.QueryRow("SHOW server_version;").Scan(&version)
98if err != nil {
99return semver.Version{}, err
100}
101submatches = serverVersionRegex.FindStringSubmatch(version)
102if len(submatches) > 1 {
103return semver.ParseTolerant(submatches[1])
104}
105return semver.Version{}, fmt.Errorf("could not parse version from %q", version)
106}
107