1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
|
// Copyright 2021 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 exporter
import (
"fmt"
"net/url"
"os"
"regexp"
"slices"
"strings"
"github.com/prometheus/client_golang/prometheus"
)
func (e *Exporter) discoverDatabaseDSNs() []string {
// connstring syntax is complex (and not sure if even regular).
// we don't need to parse it, so just superficially validate that it starts
// with a valid-ish keyword pair
connstringRe := regexp.MustCompile(`^ *[a-zA-Z0-9]+ *= *[^= ]+`)
dsns := make(map[string]struct{})
for _, dsn := range e.dsn {
var dsnURI *url.URL
var dsnConnstring string
if strings.HasPrefix(dsn, "postgresql://") || strings.HasPrefix(dsn, "postgres://") {
var err error
dsnURI, err = url.Parse(dsn)
if err != nil {
e.logger.Error("Unable to parse DSN as URI", "dsn", loggableDSN(dsn), "err", err)
continue
}
} else if connstringRe.MatchString(dsn) {
dsnConnstring = dsn
} else {
e.logger.Error("Unable to parse DSN as either URI or connstring", "dsn", loggableDSN(dsn))
continue
}
server, err := e.servers.GetServer(dsn)
if err != nil {
e.logger.Error("Error opening connection to database", "dsn", loggableDSN(dsn), "err", err)
continue
}
dsns[dsn] = struct{}{}
// If autoDiscoverDatabases is true, set first dsn as master database (Default: false)
server.master = true
databaseNames, err := queryDatabases(server)
if err != nil {
e.logger.Error("Error querying databases", "dsn", loggableDSN(dsn), "err", err)
continue
}
for _, databaseName := range databaseNames {
if slices.Contains(e.excludeDatabases, databaseName) {
continue
}
if len(e.includeDatabases) != 0 && !slices.Contains(e.includeDatabases, databaseName) {
continue
}
if dsnURI != nil {
dsnURI.Path = databaseName
dsn = dsnURI.String()
} else {
// replacing one dbname with another is complicated.
// just append new dbname to override.
dsn = fmt.Sprintf("%s dbname=%s", dsnConnstring, databaseName)
}
dsns[dsn] = struct{}{}
}
}
result := make([]string, len(dsns))
index := 0
for dsn := range dsns {
result[index] = dsn
index++
}
return result
}
func (e *Exporter) scrapeDSN(ch chan<- prometheus.Metric, dsn string) error {
server, err := e.servers.GetServer(dsn)
if err != nil {
return &ErrorConnectToServer{fmt.Sprintf("Error opening connection to database (%s): %s", loggableDSN(dsn), err.Error())}
}
// Check if autoDiscoverDatabases is false, set dsn as master database (Default: false)
if !e.autoDiscoverDatabases {
server.master = true
}
// Check if map versions need to be updated
if err := e.checkMapVersions(ch, server); err != nil {
e.logger.Warn("Proceeding with outdated query maps, as the Postgres version could not be determined", "err", err)
}
return server.Scrape(ch, e.disableSettingsMetrics)
}
// try to get the DataSource
// DATA_SOURCE_NAME always wins so we do not break older versions
// reading secrets from files wins over secrets in environment variables
// DATA_SOURCE_NAME > DATA_SOURCE_{USER|PASS}_FILE > DATA_SOURCE_{USER|PASS}
func GetDataSources() ([]string, error) {
var dsn = os.Getenv("DATA_SOURCE_NAME")
if len(dsn) != 0 {
return strings.Split(dsn, ","), nil
}
var user, pass, uri string
dataSourceUserFile := os.Getenv("DATA_SOURCE_USER_FILE")
if len(dataSourceUserFile) != 0 {
fileContents, err := os.ReadFile(dataSourceUserFile)
if err != nil {
return nil, fmt.Errorf("failed loading data source user file %s: %s", dataSourceUserFile, err.Error())
}
user = strings.TrimSpace(string(fileContents))
} else {
user = os.Getenv("DATA_SOURCE_USER")
}
dataSourcePassFile := os.Getenv("DATA_SOURCE_PASS_FILE")
if len(dataSourcePassFile) != 0 {
fileContents, err := os.ReadFile(dataSourcePassFile)
if err != nil {
return nil, fmt.Errorf("failed loading data source pass file %s: %s", dataSourcePassFile, err.Error())
}
pass = strings.TrimSpace(string(fileContents))
} else {
pass = os.Getenv("DATA_SOURCE_PASS")
}
ui := url.UserPassword(user, pass).String()
dataSrouceURIFile := os.Getenv("DATA_SOURCE_URI_FILE")
if len(dataSrouceURIFile) != 0 {
fileContents, err := os.ReadFile(dataSrouceURIFile)
if err != nil {
return nil, fmt.Errorf("failed loading data source URI file %s: %s", dataSrouceURIFile, err.Error())
}
uri = strings.TrimSpace(string(fileContents))
} else {
uri = os.Getenv("DATA_SOURCE_URI")
}
// No datasources found. This allows us to support the multi-target pattern
// without an explicit datasource.
if uri == "" {
return []string{}, nil
}
dsn = "postgresql://" + ui + "@" + uri
return []string{dsn}, nil
}
|