pangolin_exporter

Форк
0
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

14
package collector
15

16
import (
17
	"database/sql"
18
	"fmt"
19
	"regexp"
20

21
	"github.com/blang/semver/v4"
22
)
23

24
type instance struct {
25
	dsn     string
26
	db      *sql.DB
27
	version semver.Version
28
}
29

30
func newInstance(dsn string) (*instance, error) {
31
	i := &instance{
32
		dsn: dsn,
33
	}
34

35
	// "Create" a database handle to verify the DSN provided is valid.
36
	// Open is not guaranteed to create a connection.
37
	db, err := sql.Open("postgres", dsn)
38
	if err != nil {
39
		return nil, err
40
	}
41
	db.Close()
42

43
	return i, nil
44
}
45

46
// copy returns a copy of the instance.
47
func (i *instance) copy() *instance {
48
	return &instance{
49
		dsn: i.dsn,
50
	}
51
}
52

53
func (i *instance) setup() error {
54
	db, err := sql.Open("postgres", i.dsn)
55
	if err != nil {
56
		return err
57
	}
58
	db.SetMaxOpenConns(1)
59
	db.SetMaxIdleConns(1)
60
	i.db = db
61

62
	version, err := queryVersion(i.db)
63
	if err != nil {
64
		return fmt.Errorf("error querying postgresql version: %w", err)
65
	} else {
66
		i.version = version
67
	}
68
	return nil
69
}
70

71
func (i *instance) getDB() *sql.DB {
72
	return i.db
73
}
74

75
func (i *instance) Close() error {
76
	return 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"
81
var versionRegex = regexp.MustCompile(`^\w+ ((\d+)(\.\d+)?(\.\d+)?)`)
82
var serverVersionRegex = regexp.MustCompile(`^((\d+)(\.\d+)?(\.\d+)?)`)
83

84
func queryVersion(db *sql.DB) (semver.Version, error) {
85
	var version string
86
	err := db.QueryRow("SELECT version();").Scan(&version)
87
	if err != nil {
88
		return semver.Version{}, err
89
	}
90
	submatches := versionRegex.FindStringSubmatch(version)
91
	if len(submatches) > 1 {
92
		return 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)
97
	err = db.QueryRow("SHOW server_version;").Scan(&version)
98
	if err != nil {
99
		return semver.Version{}, err
100
	}
101
	submatches = serverVersionRegex.FindStringSubmatch(version)
102
	if len(submatches) > 1 {
103
		return semver.ParseTolerant(submatches[1])
104
	}
105
	return semver.Version{}, fmt.Errorf("could not parse version from %q", version)
106
}
107

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.