Start building out the packages.

This commit is contained in:
Will Rouesnel 2020-03-01 01:20:42 +11:00
parent 6fcfe4041a
commit 3ccdfc0777
No known key found for this signature in database
GPG Key ID: 72DC65802A1091C5
20 changed files with 673 additions and 608 deletions

View File

@ -1,32 +1,23 @@
package main
import (
"database/sql"
"errors"
"fmt"
"github.com/wrouesnel/postgres_exporter/pkg/pgdbconv"
"github.com/wrouesnel/postgres_exporter/pkg/queries"
"github.com/wrouesnel/postgres_exporter/pkg/queries/metricmaps"
"io/ioutil"
"math"
"net/http"
"net/url"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/blang/semver"
"github.com/lib/pq"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"github.com/prometheus/common/version"
"gopkg.in/alecthomas/kingpin.v2"
"gopkg.in/yaml.v2"
"github.com/wrouesnel/postgres_exporter/pkg/pgexporter"
"github.com/wrouesnel/postgres_exporter/pkg/servers"
)
@ -58,8 +49,6 @@ var (
excludeDatabases = kingpin.Flag("exclude-databases", "A list of databases to remove when autoDiscoverDatabases is enabled").Default("").Envar("PG_EXPORTER_EXCLUDE_DATABASES").String()
)
// Regex used to get the "short-version" from the postgres version field.
var versionRegex = regexp.MustCompile(`^\w+ ((\d+)(\.\d+)?(\.\d+)?)`)
var lowestSupportedVersion = semver.MustParse("9.1.0")
@ -75,8 +64,6 @@ func parseVersion(versionString string) (semver.Version, error) {
errors.New(fmt.Sprintln("Could not find a postgres version in string:", versionString))
}
// ErrorConnectToServer is a connection to PgSQL server error
type ErrorConnectToServer struct {
Msg string
@ -107,35 +94,6 @@ func dumpMaps() {
}
}
// Convert the query override file to the version-specific query override file
// for the exporter.
func makeQueryOverrideMap(pgVersion semver.Version, queryOverrides map[string][]OverrideQuery) map[string]string {
resultMap := make(map[string]string)
for name, overrideDef := range queryOverrides {
// Find a matching semver. We make it an error to have overlapping
// ranges at test-time, so only 1 should ever match.
matched := false
for _, queryDef := range overrideDef {
if queryDef.versionRange(pgVersion) {
resultMap[name] = queryDef.query
matched = true
break
}
}
if !matched {
log.Warnln("No query matched override for", name, "- disabling metric space.")
resultMap[name] = ""
}
}
return resultMap
}
// Add queries to the builtinMetricMaps and queryOverrides maps. Added queries do not
// respect version requirements, because it is assumed that the user knows
// what they are doing with their version of postgres.
@ -175,11 +133,6 @@ func addQueries(content []byte, pgVersion semver.Version, server *Server) error
return nil
}
type cachedMetrics struct {
metrics []prometheus.Metric
lastScrape time.Time
}
func parseConstLabels(s string) prometheus.Labels {
labels := make(prometheus.Labels)
@ -233,179 +186,6 @@ func queryDatabases(server *servers.Server) ([]string, error) {
return result, nil
}
// Query within a namespace mapping and emit metrics. Returns fatal errors if
// the scrape fails, and a slice of errors if they were non-fatal.
func queryNamespaceMapping(server *Server, namespace string, mapping MetricMapNamespace) ([]prometheus.Metric, []error, error) {
// Check for a query override for this namespace
query, found := server.queryOverrides[namespace]
// Was this query disabled (i.e. nothing sensible can be queried on cu
// version of PostgreSQL?
if query == "" && found {
// Return success (no pertinent data)
return []prometheus.Metric{}, []error{}, nil
}
// Don't fail on a bad scrape of one metric
var rows *sql.Rows
var err error
if !found {
// I've no idea how to avoid this properly at the moment, but this is
// an admin tool so you're not injecting SQL right?
rows, err = server.db.Query(fmt.Sprintf("SELECT * FROM %s;", namespace)) // nolint: gas, safesql
} else {
rows, err = server.db.Query(query) // nolint: safesql
}
if err != nil {
return []prometheus.Metric{}, []error{}, fmt.Errorf("Error running query on database %q: %s %v", server, namespace, err)
}
defer rows.Close() // nolint: errcheck
var columnNames []string
columnNames, err = rows.Columns()
if err != nil {
return []prometheus.Metric{}, []error{}, errors.New(fmt.Sprintln("Error retrieving column list for: ", namespace, err))
}
// Make a lookup map for the column indices
var columnIdx = make(map[string]int, len(columnNames))
for i, n := range columnNames {
columnIdx[n] = i
}
var columnData = make([]interface{}, len(columnNames))
var scanArgs = make([]interface{}, len(columnNames))
for i := range columnData {
scanArgs[i] = &columnData[i]
}
nonfatalErrors := []error{}
metrics := make([]prometheus.Metric, 0)
for rows.Next() {
err = rows.Scan(scanArgs...)
if err != nil {
return []prometheus.Metric{}, []error{}, errors.New(fmt.Sprintln("Error retrieving rows:", namespace, err))
}
// Get the label values for this row.
labels := make([]string, len(mapping.labels))
for idx, label := range mapping.labels {
labels[idx], _ = dbToString(columnData[columnIdx[label]])
}
// Loop over column names, and match to scan data. Unknown columns
// will be filled with an untyped metric number *if* they can be
// converted to float64s. NULLs are allowed and treated as NaN.
for idx, columnName := range columnNames {
var metric prometheus.Metric
if metricMapping, ok := mapping.columnMappings[columnName]; ok {
// Is this a metricy metric?
if metricMapping.discard {
continue
}
value, ok := dbToFloat64(columnData[idx])
if !ok {
nonfatalErrors = append(nonfatalErrors, errors.New(fmt.Sprintln("Unexpected error parsing column: ", namespace, columnName, columnData[idx])))
continue
}
// Generate the metric
metric = prometheus.MustNewConstMetric(metricMapping.desc, metricMapping.vtype, value, labels...)
} else {
// Unknown metric. Report as untyped if scan to float64 works, else note an error too.
metricLabel := fmt.Sprintf("%s_%s", namespace, columnName)
desc := prometheus.NewDesc(metricLabel, fmt.Sprintf("Unknown metric from %s", namespace), mapping.labels, server.labels)
// Its not an error to fail here, since the values are
// unexpected anyway.
value, ok := dbToFloat64(columnData[idx])
if !ok {
nonfatalErrors = append(nonfatalErrors, errors.New(fmt.Sprintln("Unparseable column type - discarding: ", namespace, columnName, err)))
continue
}
metric = prometheus.MustNewConstMetric(desc, prometheus.UntypedValue, value, labels...)
}
metrics = append(metrics, metric)
}
}
return metrics, nonfatalErrors, nil
}
// Iterate through all the namespace mappings in the exporter and run their
// queries.
func queryNamespaceMappings(ch chan<- prometheus.Metric, server *Server) map[string]error {
// Return a map of namespace -> errors
namespaceErrors := make(map[string]error)
scrapeStart := time.Now()
for namespace, mapping := range server.metricMap {
log.Debugln("Querying namespace: ", namespace)
if mapping.master && !server.master {
log.Debugln("Query skipped...")
continue
}
scrapeMetric := false
// Check if the metric is cached
server.cacheMtx.Lock()
cachedMetric, found := server.metricCache[namespace]
server.cacheMtx.Unlock()
// If found, check if needs refresh from cache
if found {
if scrapeStart.Sub(cachedMetric.lastScrape).Seconds() > float64(mapping.cacheSeconds) {
scrapeMetric = true
}
} else {
scrapeMetric = true
}
var metrics []prometheus.Metric
var nonFatalErrors []error
var err error
if scrapeMetric {
metrics, nonFatalErrors, err = queryNamespaceMapping(server, namespace, mapping)
} else {
metrics = cachedMetric.metrics
}
// Serious error - a namespace disappeared
if err != nil {
namespaceErrors[namespace] = err
log.Infoln(err)
}
// Non-serious errors - likely version or parsing problems.
if len(nonFatalErrors) > 0 {
for _, err := range nonFatalErrors {
log.Infoln(err.Error())
}
}
// Emit the metrics into the channel
for _, metric := range metrics {
ch <- metric
}
if scrapeMetric {
// Only cache if metric is meaningfully cacheable
if mapping.cacheSeconds > 0 {
server.cacheMtx.Lock()
server.metricCache[namespace] = cachedMetrics{
metrics: metrics,
lastScrape: scrapeStart,
}
server.cacheMtx.Unlock()
}
}
}
return namespaceErrors
}
// getDataSources tries to get a datasource connection ID.
// DATA_SOURCE_NAME always wins so we do not break older versions
// reading secrets from files wins over secrets in environment variables

View File

@ -72,4 +72,4 @@ func DBToString(t interface{}) (string, bool) {
default:
return "", false
}
}
}

View File

@ -300,4 +300,4 @@ func (e *Exporter) scrapeDSN(ch chan<- prometheus.Metric, dsn string) error {
}
return server.Scrape(ch, e.disableSettingsMetrics)
}
}

View File

@ -45,4 +45,4 @@ func WithConstantLabels(s string) ExporterOpt {
return func(e *Exporter) {
e.constantLabels = parseConstLabels(s)
}
}
}

View File

@ -2,144 +2,256 @@
package builtin
import (
"github.com/blang/semver"
. "github.com/wrouesnel/postgres_exporter/pkg/queries/metricmaps"
)
// builtinMetricMaps is a suite of standard metrics for all postgres versions.
var builtinMetricMaps = MetricMaps{
"pg_stat_bgwriter": {
map[string]ColumnMapping{
"checkpoints_timed": {COUNTER, "Number of scheduled checkpoints that have been performed", nil, nil},
"checkpoints_req": {COUNTER, "Number of requested checkpoints that have been performed", nil, nil},
"checkpoint_write_time": {COUNTER, "Total amount of time that has been spent in the portion of checkpoint processing where files are written to disk, in milliseconds", nil, nil},
"checkpoint_sync_time": {COUNTER, "Total amount of time that has been spent in the portion of checkpoint processing where files are synchronized to disk, in milliseconds", nil, nil},
"buffers_checkpoint": {COUNTER, "Number of buffers written during checkpoints", nil, nil},
"buffers_clean": {COUNTER, "Number of buffers written by the background writer", nil, nil},
"maxwritten_clean": {COUNTER, "Number of times the background writer stopped a cleaning scan because it had written too many buffers", nil, nil},
"buffers_backend": {COUNTER, "Number of buffers written directly by a backend", nil, nil},
"buffers_backend_fsync": {COUNTER, "Number of times a backend had to execute its own fsync call (normally the background writer handles those even when the backend does its own write)", nil, nil},
"buffers_alloc": {COUNTER, "Number of buffers allocated", nil, nil},
"stats_reset": {COUNTER, "Time at which these statistics were last reset", nil, nil},
var builtin = QueryMap{
Global: &QueryConfig{
MetricMap: MetricMaps{
"pg_stat_bgwriter": {
map[string]ColumnMapping{
"checkpoints_timed": {COUNTER, "Number of scheduled checkpoints that have been performed", nil, nil},
"checkpoints_req": {COUNTER, "Number of requested checkpoints that have been performed", nil, nil},
"checkpoint_write_time": {COUNTER, "Total amount of time that has been spent in the portion of checkpoint processing where files are written to disk, in milliseconds", nil, nil},
"checkpoint_sync_time": {COUNTER, "Total amount of time that has been spent in the portion of checkpoint processing where files are synchronized to disk, in milliseconds", nil, nil},
"buffers_checkpoint": {COUNTER, "Number of buffers written during checkpoints", nil, nil},
"buffers_clean": {COUNTER, "Number of buffers written by the background writer", nil, nil},
"maxwritten_clean": {COUNTER, "Number of times the background writer stopped a cleaning scan because it had written too many buffers", nil, nil},
"buffers_backend": {COUNTER, "Number of buffers written directly by a backend", nil, nil},
"buffers_backend_fsync": {COUNTER, "Number of times a backend had to execute its own fsync call (normally the background writer handles those even when the backend does its own write)", nil, nil},
"buffers_alloc": {COUNTER, "Number of buffers allocated", nil, nil},
"stats_reset": {COUNTER, "Time at which these statistics were last reset", nil, nil},
},
true,
0,
},
"pg_stat_database": {
map[string]ColumnMapping{
"datid": {LABEL, "OID of a database", nil, nil},
"datname": {LABEL, "Name of this database", nil, nil},
"numbackends": {GAUGE, "Number of backends currently connected to this database. This is the only column in this view that returns a value reflecting current state; all other columns return the accumulated values since the last reset.", nil, nil},
"xact_commit": {COUNTER, "Number of transactions in this database that have been committed", nil, nil},
"xact_rollback": {COUNTER, "Number of transactions in this database that have been rolled back", nil, nil},
"blks_read": {COUNTER, "Number of disk blocks read in this database", nil, nil},
"blks_hit": {COUNTER, "Number of times disk blocks were found already in the buffer cache, so that a read was not necessary (this only includes hits in the PostgreSQL buffer cache, not the operating system's file system cache)", nil, nil},
"tup_returned": {COUNTER, "Number of rows returned by queries in this database", nil, nil},
"tup_fetched": {COUNTER, "Number of rows fetched by queries in this database", nil, nil},
"tup_inserted": {COUNTER, "Number of rows inserted by queries in this database", nil, nil},
"tup_updated": {COUNTER, "Number of rows updated by queries in this database", nil, nil},
"tup_deleted": {COUNTER, "Number of rows deleted by queries in this database", nil, nil},
"conflicts": {COUNTER, "Number of queries canceled due to conflicts with recovery in this database. (Conflicts occur only on standby servers; see pg_stat_database_conflicts for details.)", nil, nil},
"temp_files": {COUNTER, "Number of temporary files created by queries in this database. All temporary files are counted, regardless of why the temporary file was created (e.g., sorting or hashing), and regardless of the log_temp_files setting.", nil, nil},
"temp_bytes": {COUNTER, "Total amount of data written to temporary files by queries in this database. All temporary files are counted, regardless of why the temporary file was created, and regardless of the log_temp_files setting.", nil, nil},
"deadlocks": {COUNTER, "Number of deadlocks detected in this database", nil, nil},
"blk_read_time": {COUNTER, "Time spent reading data file blocks by backends in this database, in milliseconds", nil, nil},
"blk_write_time": {COUNTER, "Time spent writing data file blocks by backends in this database, in milliseconds", nil, nil},
"stats_reset": {COUNTER, "Time at which these statistics were last reset", nil, nil},
},
true,
0,
},
"pg_stat_database_conflicts": {
map[string]ColumnMapping{
"datid": {LABEL, "OID of a database", nil, nil},
"datname": {LABEL, "Name of this database", nil, nil},
"confl_tablespace": {COUNTER, "Number of queries in this database that have been canceled due to dropped tablespaces", nil, nil},
"confl_lock": {COUNTER, "Number of queries in this database that have been canceled due to lock timeouts", nil, nil},
"confl_snapshot": {COUNTER, "Number of queries in this database that have been canceled due to old snapshots", nil, nil},
"confl_bufferpin": {COUNTER, "Number of queries in this database that have been canceled due to pinned buffers", nil, nil},
"confl_deadlock": {COUNTER, "Number of queries in this database that have been canceled due to deadlocks", nil, nil},
},
true,
0,
},
"pg_locks": {
map[string]ColumnMapping{
"datname": {LABEL, "Name of this database", nil, nil},
"mode": {LABEL, "Type of Lock", nil, nil},
"count": {GAUGE, "Number of locks", nil, nil},
},
true,
0,
},
"pg_stat_replication": {
map[string]ColumnMapping{
"procpid": {DISCARD, "Process ID of a WAL sender process", nil, MustParseSemverRange("<9.2.0")},
"pid": {DISCARD, "Process ID of a WAL sender process", nil, MustParseSemverRange(">=9.2.0")},
"usesysid": {DISCARD, "OID of the user logged into this WAL sender process", nil, nil},
"usename": {DISCARD, "Name of the user logged into this WAL sender process", nil, nil},
"application_name": {LABEL, "Name of the application that is connected to this WAL sender", nil, nil},
"client_addr": {LABEL, "IP address of the client connected to this WAL sender. If this field is null, it indicates that the client is connected via a Unix socket on the server machine.", nil, nil},
"client_hostname": {DISCARD, "Host name of the connected client, as reported by a reverse DNS lookup of client_addr. This field will only be non-null for IP connections, and only when log_hostname is enabled.", nil, nil},
"client_port": {DISCARD, "TCP port number that the client is using for communication with this WAL sender, or -1 if a Unix socket is used", nil, nil},
"backend_start": {DISCARD, "with time zone Time when this process was started, i.e., when the client connected to this WAL sender", nil, nil},
"backend_xmin": {DISCARD, "The current backend's xmin horizon.", nil, nil},
"state": {LABEL, "Current WAL sender state", nil, nil},
"sent_location": {DISCARD, "Last transaction log position sent on this connection", nil, MustParseSemverRange("<10.0.0")},
"write_location": {DISCARD, "Last transaction log position written to disk by this standby server", nil, MustParseSemverRange("<10.0.0")},
"flush_location": {DISCARD, "Last transaction log position flushed to disk by this standby server", nil, MustParseSemverRange("<10.0.0")},
"replay_location": {DISCARD, "Last transaction log position replayed into the database on this standby server", nil, MustParseSemverRange("<10.0.0")},
"sent_lsn": {DISCARD, "Last transaction log position sent on this connection", nil, MustParseSemverRange(">=10.0.0")},
"write_lsn": {DISCARD, "Last transaction log position written to disk by this standby server", nil, MustParseSemverRange(">=10.0.0")},
"flush_lsn": {DISCARD, "Last transaction log position flushed to disk by this standby server", nil, MustParseSemverRange(">=10.0.0")},
"replay_lsn": {DISCARD, "Last transaction log position replayed into the database on this standby server", nil, MustParseSemverRange(">=10.0.0")},
"sync_priority": {DISCARD, "Priority of this standby server for being chosen as the synchronous standby", nil, nil},
"sync_state": {DISCARD, "Synchronous state of this standby server", nil, nil},
"slot_name": {LABEL, "A unique, cluster-wide identifier for the replication slot", nil, MustParseSemverRange(">=9.2.0")},
"plugin": {DISCARD, "The base name of the shared object containing the output plugin this logical slot is using, or null for physical slots", nil, nil},
"slot_type": {DISCARD, "The slot type - physical or logical", nil, nil},
"datoid": {DISCARD, "The OID of the database this slot is associated with, or null. Only logical slots have an associated database", nil, nil},
"database": {DISCARD, "The name of the database this slot is associated with, or null. Only logical slots have an associated database", nil, nil},
"active": {DISCARD, "True if this slot is currently actively being used", nil, nil},
"active_pid": {DISCARD, "Process ID of a WAL sender process", nil, nil},
"xmin": {DISCARD, "The oldest transaction that this slot needs the database to retain. VACUUM cannot remove tuples deleted by any later transaction", nil, nil},
"catalog_xmin": {DISCARD, "The oldest transaction affecting the system catalogs that this slot needs the database to retain. VACUUM cannot remove catalog tuples deleted by any later transaction", nil, nil},
"restart_lsn": {DISCARD, "The address (LSN) of oldest WAL which still might be required by the consumer of this slot and thus won't be automatically removed during checkpoints", nil, nil},
"pg_current_xlog_location": {DISCARD, "pg_current_xlog_location", nil, nil},
"pg_current_wal_lsn": {DISCARD, "pg_current_xlog_location", nil, MustParseSemverRange(">=10.0.0")},
"pg_current_wal_lsn_bytes": {GAUGE, "WAL position in bytes", nil, MustParseSemverRange(">=10.0.0")},
"pg_xlog_location_diff": {GAUGE, "Lag in bytes between master and slave", nil, MustParseSemverRange(">=9.2.0 <10.0.0")},
"pg_wal_lsn_diff": {GAUGE, "Lag in bytes between master and slave", nil, MustParseSemverRange(">=10.0.0")},
"confirmed_flush_lsn": {DISCARD, "LSN position a consumer of a slot has confirmed flushing the data received", nil, nil},
"write_lag": {DISCARD, "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written it (but not yet flushed it or applied it). This can be used to gauge the delay that synchronous_commit level remote_write incurred while committing if this server was configured as a synchronous standby.", nil, MustParseSemverRange(">=10.0.0")},
"flush_lag": {DISCARD, "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written and flushed it (but not yet applied it). This can be used to gauge the delay that synchronous_commit level remote_flush incurred while committing if this server was configured as a synchronous standby.", nil, MustParseSemverRange(">=10.0.0")},
"replay_lag": {DISCARD, "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written, flushed and applied it. This can be used to gauge the delay that synchronous_commit level remote_apply incurred while committing if this server was configured as a synchronous standby.", nil, MustParseSemverRange(">=10.0.0")},
},
true,
0,
},
"pg_stat_archiver": {
map[string]ColumnMapping{
"archived_count": {COUNTER, "Number of WAL files that have been successfully archived", nil, nil},
"last_archived_wal": {DISCARD, "Name of the last WAL file successfully archived", nil, nil},
"last_archived_time": {DISCARD, "Time of the last successful archive operation", nil, nil},
"failed_count": {COUNTER, "Number of failed attempts for archiving WAL files", nil, nil},
"last_failed_wal": {DISCARD, "Name of the WAL file of the last failed archival operation", nil, nil},
"last_failed_time": {DISCARD, "Time of the last failed archival operation", nil, nil},
"stats_reset": {DISCARD, "Time at which these statistics were last reset", nil, nil},
"last_archive_age": {GAUGE, "Time in seconds since last WAL segment was successfully archived", nil, nil},
},
true,
0,
},
"pg_stat_activity": {
map[string]ColumnMapping{
"datname": {LABEL, "Name of this database", nil, nil},
"state": {LABEL, "connection state", nil, MustParseSemverRange(">=9.2.0")},
"count": {GAUGE, "number of connections in this state", nil, nil},
"max_tx_duration": {GAUGE, "max duration in seconds any active transaction has been running", nil, nil},
},
true,
0,
},
},
true,
0,
},
"pg_stat_database": {
map[string]ColumnMapping{
"datid": {LABEL, "OID of a database", nil, nil},
"datname": {LABEL, "Name of this database", nil, nil},
"numbackends": {GAUGE, "Number of backends currently connected to this database. This is the only column in this view that returns a value reflecting current state; all other columns return the accumulated values since the last reset.", nil, nil},
"xact_commit": {COUNTER, "Number of transactions in this database that have been committed", nil, nil},
"xact_rollback": {COUNTER, "Number of transactions in this database that have been rolled back", nil, nil},
"blks_read": {COUNTER, "Number of disk blocks read in this database", nil, nil},
"blks_hit": {COUNTER, "Number of times disk blocks were found already in the buffer cache, so that a read was not necessary (this only includes hits in the PostgreSQL buffer cache, not the operating system's file system cache)", nil, nil},
"tup_returned": {COUNTER, "Number of rows returned by queries in this database", nil, nil},
"tup_fetched": {COUNTER, "Number of rows fetched by queries in this database", nil, nil},
"tup_inserted": {COUNTER, "Number of rows inserted by queries in this database", nil, nil},
"tup_updated": {COUNTER, "Number of rows updated by queries in this database", nil, nil},
"tup_deleted": {COUNTER, "Number of rows deleted by queries in this database", nil, nil},
"conflicts": {COUNTER, "Number of queries canceled due to conflicts with recovery in this database. (Conflicts occur only on standby servers; see pg_stat_database_conflicts for details.)", nil, nil},
"temp_files": {COUNTER, "Number of temporary files created by queries in this database. All temporary files are counted, regardless of why the temporary file was created (e.g., sorting or hashing), and regardless of the log_temp_files setting.", nil, nil},
"temp_bytes": {COUNTER, "Total amount of data written to temporary files by queries in this database. All temporary files are counted, regardless of why the temporary file was created, and regardless of the log_temp_files setting.", nil, nil},
"deadlocks": {COUNTER, "Number of deadlocks detected in this database", nil, nil},
"blk_read_time": {COUNTER, "Time spent reading data file blocks by backends in this database, in milliseconds", nil, nil},
"blk_write_time": {COUNTER, "Time spent writing data file blocks by backends in this database, in milliseconds", nil, nil},
"stats_reset": {COUNTER, "Time at which these statistics were last reset", nil, nil},
QueryOverrides: QueryOverrides{
"pg_locks": {
{
MustParseSemverRange(">0.0.0"),
`SELECT pg_database.datname,tmp.mode,COALESCE(count,0) as count
FROM
(
VALUES ('accesssharelock'),
('rowsharelock'),
('rowexclusivelock'),
('shareupdateexclusivelock'),
('sharelock'),
('sharerowexclusivelock'),
('exclusivelock'),
('accessexclusivelock')
) AS tmp(mode) CROSS JOIN pg_database
LEFT JOIN
(SELECT database, lower(mode) AS mode,count(*) AS count
FROM pg_locks WHERE database IS NOT NULL
GROUP BY database, lower(mode)
) AS tmp2
ON tmp.mode=tmp2.mode and pg_database.oid = tmp2.database ORDER BY 1`,
},
},
"pg_stat_replication": {
{
MustParseSemverRange(">=10.0.0"),
`
SELECT *,
(case pg_is_in_recovery() when 't' then null else pg_current_wal_lsn() end) AS pg_current_wal_lsn,
(case pg_is_in_recovery() when 't' then null else pg_wal_lsn_diff(pg_current_wal_lsn(), pg_lsn('0/0'))::float end) AS pg_current_wal_lsn_bytes,
(case pg_is_in_recovery() when 't' then null else pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)::float end) AS pg_wal_lsn_diff
FROM pg_stat_replication
`,
},
{
MustParseSemverRange(">=9.2.0 <10.0.0"),
`
SELECT *,
(case pg_is_in_recovery() when 't' then null else pg_current_xlog_location() end) AS pg_current_xlog_location,
(case pg_is_in_recovery() when 't' then null else pg_xlog_location_diff(pg_current_xlog_location(), replay_location)::float end) AS pg_xlog_location_diff
FROM pg_stat_replication
`,
},
{
MustParseSemverRange("<9.2.0"),
`
SELECT *,
(case pg_is_in_recovery() when 't' then null else pg_current_xlog_location() end) AS pg_current_xlog_location
FROM pg_stat_replication
`,
},
},
"pg_stat_archiver": {
{
MustParseSemverRange(">=0.0.0"),
`
SELECT *,
extract(epoch from now() - last_archived_time) AS last_archive_age
FROM pg_stat_archiver
`,
},
},
"pg_stat_activity": {
// This query only works
{
MustParseSemverRange(">=9.2.0"),
`
SELECT
pg_database.datname,
tmp.state,
COALESCE(count,0) as count,
COALESCE(max_tx_duration,0) as max_tx_duration
FROM
(
VALUES ('active'),
('idle'),
('idle in transaction'),
('idle in transaction (aborted)'),
('fastpath function call'),
('disabled')
) AS tmp(state) CROSS JOIN pg_database
LEFT JOIN
(
SELECT
datname,
state,
count(*) AS count,
MAX(EXTRACT(EPOCH FROM now() - xact_start))::float AS max_tx_duration
FROM pg_stat_activity GROUP BY datname,state) AS tmp2
ON tmp.state = tmp2.state AND pg_database.datname = tmp2.datname
`,
},
{
MustParseSemverRange("<9.2.0"),
`
SELECT
datname,
'unknown' AS state,
COALESCE(count(*),0) AS count,
COALESCE(MAX(EXTRACT(EPOCH FROM now() - xact_start))::float,0) AS max_tx_duration
FROM pg_stat_activity GROUP BY datname
`,
},
},
},
true,
0,
},
"pg_stat_database_conflicts": {
map[string]ColumnMapping{
"datid": {LABEL, "OID of a database", nil, nil},
"datname": {LABEL, "Name of this database", nil, nil},
"confl_tablespace": {COUNTER, "Number of queries in this database that have been canceled due to dropped tablespaces", nil, nil},
"confl_lock": {COUNTER, "Number of queries in this database that have been canceled due to lock timeouts", nil, nil},
"confl_snapshot": {COUNTER, "Number of queries in this database that have been canceled due to old snapshots", nil, nil},
"confl_bufferpin": {COUNTER, "Number of queries in this database that have been canceled due to pinned buffers", nil, nil},
"confl_deadlock": {COUNTER, "Number of queries in this database that have been canceled due to deadlocks", nil, nil},
},
true,
0,
},
"pg_locks": {
map[string]ColumnMapping{
"datname": {LABEL, "Name of this database", nil, nil},
"mode": {LABEL, "Type of Lock", nil, nil},
"count": {GAUGE, "Number of locks", nil, nil},
},
true,
0,
},
"pg_stat_replication": {
map[string]ColumnMapping{
"procpid": {DISCARD, "Process ID of a WAL sender process", nil, semver.MustParseRange("<9.2.0")},
"pid": {DISCARD, "Process ID of a WAL sender process", nil, semver.MustParseRange(">=9.2.0")},
"usesysid": {DISCARD, "OID of the user logged into this WAL sender process", nil, nil},
"usename": {DISCARD, "Name of the user logged into this WAL sender process", nil, nil},
"application_name": {LABEL, "Name of the application that is connected to this WAL sender", nil, nil},
"client_addr": {LABEL, "IP address of the client connected to this WAL sender. If this field is null, it indicates that the client is connected via a Unix socket on the server machine.", nil, nil},
"client_hostname": {DISCARD, "Host name of the connected client, as reported by a reverse DNS lookup of client_addr. This field will only be non-null for IP connections, and only when log_hostname is enabled.", nil, nil},
"client_port": {DISCARD, "TCP port number that the client is using for communication with this WAL sender, or -1 if a Unix socket is used", nil, nil},
"backend_start": {DISCARD, "with time zone Time when this process was started, i.e., when the client connected to this WAL sender", nil, nil},
"backend_xmin": {DISCARD, "The current backend's xmin horizon.", nil, nil},
"state": {LABEL, "Current WAL sender state", nil, nil},
"sent_location": {DISCARD, "Last transaction log position sent on this connection", nil, semver.MustParseRange("<10.0.0")},
"write_location": {DISCARD, "Last transaction log position written to disk by this standby server", nil, semver.MustParseRange("<10.0.0")},
"flush_location": {DISCARD, "Last transaction log position flushed to disk by this standby server", nil, semver.MustParseRange("<10.0.0")},
"replay_location": {DISCARD, "Last transaction log position replayed into the database on this standby server", nil, semver.MustParseRange("<10.0.0")},
"sent_lsn": {DISCARD, "Last transaction log position sent on this connection", nil, semver.MustParseRange(">=10.0.0")},
"write_lsn": {DISCARD, "Last transaction log position written to disk by this standby server", nil, semver.MustParseRange(">=10.0.0")},
"flush_lsn": {DISCARD, "Last transaction log position flushed to disk by this standby server", nil, semver.MustParseRange(">=10.0.0")},
"replay_lsn": {DISCARD, "Last transaction log position replayed into the database on this standby server", nil, semver.MustParseRange(">=10.0.0")},
"sync_priority": {DISCARD, "Priority of this standby server for being chosen as the synchronous standby", nil, nil},
"sync_state": {DISCARD, "Synchronous state of this standby server", nil, nil},
"slot_name": {LABEL, "A unique, cluster-wide identifier for the replication slot", nil, semver.MustParseRange(">=9.2.0")},
"plugin": {DISCARD, "The base name of the shared object containing the output plugin this logical slot is using, or null for physical slots", nil, nil},
"slot_type": {DISCARD, "The slot type - physical or logical", nil, nil},
"datoid": {DISCARD, "The OID of the database this slot is associated with, or null. Only logical slots have an associated database", nil, nil},
"database": {DISCARD, "The name of the database this slot is associated with, or null. Only logical slots have an associated database", nil, nil},
"active": {DISCARD, "True if this slot is currently actively being used", nil, nil},
"active_pid": {DISCARD, "Process ID of a WAL sender process", nil, nil},
"xmin": {DISCARD, "The oldest transaction that this slot needs the database to retain. VACUUM cannot remove tuples deleted by any later transaction", nil, nil},
"catalog_xmin": {DISCARD, "The oldest transaction affecting the system catalogs that this slot needs the database to retain. VACUUM cannot remove catalog tuples deleted by any later transaction", nil, nil},
"restart_lsn": {DISCARD, "The address (LSN) of oldest WAL which still might be required by the consumer of this slot and thus won't be automatically removed during checkpoints", nil, nil},
"pg_current_xlog_location": {DISCARD, "pg_current_xlog_location", nil, nil},
"pg_current_wal_lsn": {DISCARD, "pg_current_xlog_location", nil, semver.MustParseRange(">=10.0.0")},
"pg_current_wal_lsn_bytes": {GAUGE, "WAL position in bytes", nil, semver.MustParseRange(">=10.0.0")},
"pg_xlog_location_diff": {GAUGE, "Lag in bytes between master and slave", nil, semver.MustParseRange(">=9.2.0 <10.0.0")},
"pg_wal_lsn_diff": {GAUGE, "Lag in bytes between master and slave", nil, semver.MustParseRange(">=10.0.0")},
"confirmed_flush_lsn": {DISCARD, "LSN position a consumer of a slot has confirmed flushing the data received", nil, nil},
"write_lag": {DISCARD, "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written it (but not yet flushed it or applied it). This can be used to gauge the delay that synchronous_commit level remote_write incurred while committing if this server was configured as a synchronous standby.", nil, semver.MustParseRange(">=10.0.0")},
"flush_lag": {DISCARD, "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written and flushed it (but not yet applied it). This can be used to gauge the delay that synchronous_commit level remote_flush incurred while committing if this server was configured as a synchronous standby.", nil, semver.MustParseRange(">=10.0.0")},
"replay_lag": {DISCARD, "Time elapsed between flushing recent WAL locally and receiving notification that this standby server has written, flushed and applied it. This can be used to gauge the delay that synchronous_commit level remote_apply incurred while committing if this server was configured as a synchronous standby.", nil, semver.MustParseRange(">=10.0.0")},
},
true,
0,
},
"pg_stat_archiver": {
map[string]ColumnMapping{
"archived_count": {COUNTER, "Number of WAL files that have been successfully archived", nil, nil},
"last_archived_wal": {DISCARD, "Name of the last WAL file successfully archived", nil, nil},
"last_archived_time": {DISCARD, "Time of the last successful archive operation", nil, nil},
"failed_count": {COUNTER, "Number of failed attempts for archiving WAL files", nil, nil},
"last_failed_wal": {DISCARD, "Name of the WAL file of the last failed archival operation", nil, nil},
"last_failed_time": {DISCARD, "Time of the last failed archival operation", nil, nil},
"stats_reset": {DISCARD, "Time at which these statistics were last reset", nil, nil},
"last_archive_age": {GAUGE, "Time in seconds since last WAL segment was successfully archived", nil, nil},
},
true,
0,
},
"pg_stat_activity": {
map[string]ColumnMapping{
"datname": {LABEL, "Name of this database", nil, nil},
"state": {LABEL, "connection state", nil, semver.MustParseRange(">=9.2.0")},
"count": {GAUGE, "number of connections in this state", nil, nil},
"max_tx_duration": {GAUGE, "max duration in seconds any active transaction has been running", nil, nil},
},
true,
0,
},
ByServer: nil,
}

View File

@ -0,0 +1,21 @@
package builtin
import (
"fmt"
. "gopkg.in/check.v1"
"gopkg.in/yaml.v1"
"testing"
)
// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { TestingT(t) }
type MetricMapsSuite struct{}
var _ = Suite(&MetricMapsSuite{})
func (s *MetricMapsSuite) TestEncodeYAML(c *C) {
data, err := yaml.Marshal(&builtin)
c.Assert(err, IsNil)
fmt.Println(string(data))
}

View File

@ -1,118 +0,0 @@
package builtin
import (
"github.com/blang/semver"
. "github.com/wrouesnel/postgres_exporter/pkg/queries/metricmaps"
)
// Overriding queries for namespaces above.
// TODO: validate this is a closed set in tests, and there are no overlaps
var queryOverrides = map[string][]OverrideQuery{
"pg_locks": {
{
semver.MustParseRange(">0.0.0"),
`SELECT pg_database.datname,tmp.mode,COALESCE(count,0) as count
FROM
(
VALUES ('accesssharelock'),
('rowsharelock'),
('rowexclusivelock'),
('shareupdateexclusivelock'),
('sharelock'),
('sharerowexclusivelock'),
('exclusivelock'),
('accessexclusivelock')
) AS tmp(mode) CROSS JOIN pg_database
LEFT JOIN
(SELECT database, lower(mode) AS mode,count(*) AS count
FROM pg_locks WHERE database IS NOT NULL
GROUP BY database, lower(mode)
) AS tmp2
ON tmp.mode=tmp2.mode and pg_database.oid = tmp2.database ORDER BY 1`,
},
},
"pg_stat_replication": {
{
semver.MustParseRange(">=10.0.0"),
`
SELECT *,
(case pg_is_in_recovery() when 't' then null else pg_current_wal_lsn() end) AS pg_current_wal_lsn,
(case pg_is_in_recovery() when 't' then null else pg_wal_lsn_diff(pg_current_wal_lsn(), pg_lsn('0/0'))::float end) AS pg_current_wal_lsn_bytes,
(case pg_is_in_recovery() when 't' then null else pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)::float end) AS pg_wal_lsn_diff
FROM pg_stat_replication
`,
},
{
semver.MustParseRange(">=9.2.0 <10.0.0"),
`
SELECT *,
(case pg_is_in_recovery() when 't' then null else pg_current_xlog_location() end) AS pg_current_xlog_location,
(case pg_is_in_recovery() when 't' then null else pg_xlog_location_diff(pg_current_xlog_location(), replay_location)::float end) AS pg_xlog_location_diff
FROM pg_stat_replication
`,
},
{
semver.MustParseRange("<9.2.0"),
`
SELECT *,
(case pg_is_in_recovery() when 't' then null else pg_current_xlog_location() end) AS pg_current_xlog_location
FROM pg_stat_replication
`,
},
},
"pg_stat_archiver": {
{
semver.MustParseRange(">=0.0.0"),
`
SELECT *,
extract(epoch from now() - last_archived_time) AS last_archive_age
FROM pg_stat_archiver
`,
},
},
"pg_stat_activity": {
// This query only works
{
semver.MustParseRange(">=9.2.0"),
`
SELECT
pg_database.datname,
tmp.state,
COALESCE(count,0) as count,
COALESCE(max_tx_duration,0) as max_tx_duration
FROM
(
VALUES ('active'),
('idle'),
('idle in transaction'),
('idle in transaction (aborted)'),
('fastpath function call'),
('disabled')
) AS tmp(state) CROSS JOIN pg_database
LEFT JOIN
(
SELECT
datname,
state,
count(*) AS count,
MAX(EXTRACT(EPOCH FROM now() - xact_start))::float AS max_tx_duration
FROM pg_stat_activity GROUP BY datname,state) AS tmp2
ON tmp.state = tmp2.state AND pg_database.datname = tmp2.datname
`,
},
{
semver.MustParseRange("<9.2.0"),
`
SELECT
datname,
'unknown' AS state,
COALESCE(count(*),0) AS count,
COALESCE(MAX(EXTRACT(EPOCH FROM now() - xact_start))::float,0) AS max_tx_duration
FROM pg_stat_activity GROUP BY datname
`,
},
},
}

View File

@ -3,12 +3,12 @@ package metricmaps
// Metric name parts.
const (
// Namespace for all metrics.
namespace = "pg"
ExporterNamespaceLabel = "pg"
// Subsystems.
exporter = "exporter"
ExporterSubsystemLabel = "ExporterSubsystemLabel"
// Metric label used for static string data thats handy to send to Prometheus
// e.g. version
staticLabelName = "static"
StaticLabelName = "static"
// Metric label used for server identification.
serverLabelName = "server"
)
ServerLabelName = "server"
)

View File

@ -1,7 +1,17 @@
package metricmaps
import (
"fmt"
"github.com/blang/semver"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
"github.com/wrouesnel/postgres_exporter/pkg/pgdbconv"
"math"
"time"
)
// Turn the MetricMap column mapping into a prometheus descriptor mapping.
func makeDescMap(pgVersion semver.Version, serverLabels prometheus.Labels, metricMaps map[string]intermediateMetricMap) map[string]MetricMapNamespace {
func makeDescMap(pgVersion semver.Version, serverLabels prometheus.Labels, metricMaps map[string]IntermediateMetricMap) map[string]MetricMapNamespace {
var metricMap = make(map[string]MetricMapNamespace)
for namespace, intermediateMappings := range metricMaps {
@ -9,23 +19,23 @@ func makeDescMap(pgVersion semver.Version, serverLabels prometheus.Labels, metri
// Get the constant labels
var variableLabels []string
for columnName, columnMapping := range intermediateMappings.columnMappings {
if columnMapping.usage == queries.LABEL {
for columnName, columnMapping := range intermediateMappings.ColumnMappings {
if columnMapping.Usage == LABEL {
variableLabels = append(variableLabels, columnName)
}
}
for columnName, columnMapping := range intermediateMappings.columnMappings {
for columnName, columnMapping := range intermediateMappings.ColumnMappings {
// Check column version compatibility for the current map
// Force to discard if not compatible.
if columnMapping.supportedVersions != nil {
if !columnMapping.supportedVersions(pgVersion) {
if columnMapping.SupportedVersions != nil {
if !columnMapping.SupportedVersions.Range(pgVersion) {
// It's very useful to be able to see what columns are being
// rejected.
log.Debugln(columnName, "is being forced to discard due to version incompatibility.")
thisMap[columnName] = MetricMap{
discard: true,
conversion: func(_ interface{}) (float64, bool) {
Discard: true,
Conversion: func(_ interface{}) (float64, bool) {
return math.NaN(), true
},
}
@ -35,52 +45,52 @@ func makeDescMap(pgVersion semver.Version, serverLabels prometheus.Labels, metri
// Determine how to convert the column based on its usage.
// nolint: dupl
switch columnMapping.usage {
case queries.DISCARD, queries.LABEL:
switch columnMapping.Usage {
case DISCARD, LABEL:
thisMap[columnName] = MetricMap{
discard: true,
conversion: func(_ interface{}) (float64, bool) {
Discard: true,
Conversion: func(_ interface{}) (float64, bool) {
return math.NaN(), true
},
}
case queries.COUNTER:
case COUNTER:
thisMap[columnName] = MetricMap{
vtype: prometheus.CounterValue,
desc: prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.description, variableLabels, serverLabels),
conversion: func(in interface{}) (float64, bool) {
ValueType: prometheus.CounterValue,
Desc: prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.Description, variableLabels, serverLabels),
Conversion: func(in interface{}) (float64, bool) {
return pgdbconv.DBToFloat64(in)
},
}
case queries.GAUGE:
case GAUGE:
thisMap[columnName] = MetricMap{
vtype: prometheus.GaugeValue,
desc: prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.description, variableLabels, serverLabels),
conversion: func(in interface{}) (float64, bool) {
ValueType: prometheus.GaugeValue,
Desc: prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.Description, variableLabels, serverLabels),
Conversion: func(in interface{}) (float64, bool) {
return pgdbconv.DBToFloat64(in)
},
}
case queries.MAPPEDMETRIC:
case MAPPEDMETRIC:
thisMap[columnName] = MetricMap{
vtype: prometheus.GaugeValue,
desc: prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.description, variableLabels, serverLabels),
conversion: func(in interface{}) (float64, bool) {
ValueType: prometheus.GaugeValue,
Desc: prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.Description, variableLabels, serverLabels),
Conversion: func(in interface{}) (float64, bool) {
text, ok := in.(string)
if !ok {
return math.NaN(), false
}
val, ok := columnMapping.mapping[text]
val, ok := columnMapping.Mapping[text]
if !ok {
return math.NaN(), false
}
return val, true
},
}
case queries.DURATION:
case DURATION:
thisMap[columnName] = MetricMap{
vtype: prometheus.GaugeValue,
desc: prometheus.NewDesc(fmt.Sprintf("%s_%s_milliseconds", namespace, columnName), columnMapping.description, variableLabels, serverLabels),
conversion: func(in interface{}) (float64, bool) {
ValueType: prometheus.GaugeValue,
Desc: prometheus.NewDesc(fmt.Sprintf("%s_%s_milliseconds", namespace, columnName), columnMapping.Description, variableLabels, serverLabels),
Conversion: func(in interface{}) (float64, bool) {
var durationString string
switch t := in.(type) {
case []byte:
@ -108,11 +118,11 @@ func makeDescMap(pgVersion semver.Version, serverLabels prometheus.Labels, metri
}
metricMap[namespace] = MetricMapNamespace{
labels: variableLabels,
columnMappings: thisMap,
master: intermediateMappings.master,
cacheSeconds: intermediateMappings.cacheSeconds}
Labels: variableLabels,
ColumnMappings: thisMap,
Master: intermediateMappings.Master,
CacheSeconds: intermediateMappings.CacheSeconds}
}
return metricMap
}
}

View File

@ -0,0 +1,9 @@
package metricmaps
import (
. "gopkg.in/check.v1"
"testing"
)
// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { TestingT(t) }

View File

@ -5,6 +5,18 @@ import (
"github.com/prometheus/client_golang/prometheus"
)
// QueryMap is the global holder structure for the new unified configuration format.
type QueryMap struct {
Global *QueryConfig `yaml:"global"`
ByServer map[string]*QueryConfig `yaml:"by_server"`
}
// QueryConfig holds a specific mapping and query override config
type QueryConfig struct {
MetricMap MetricMaps `yaml:"metric_maps"`
QueryOverrides QueryOverrides `yaml:"query_override"`
}
// MappingOptions is a copy of ColumnMapping used only for parsing
type MappingOptions struct {
Usage string `yaml:"usage"`
@ -14,7 +26,7 @@ type MappingOptions struct {
}
// QueryOverrides ensures our query types are consistent
type QueryOverrides map[string]string
type QueryOverrides map[string][]OverrideQuery
// MetricMaps is a stub type to assist with checking
type MetricMaps map[string]IntermediateMetricMap
@ -27,20 +39,19 @@ type IntermediateMetricMap struct {
CacheSeconds uint64
}
// MetricMapNamespace groups metric maps under a shared set of labels.
type MetricMapNamespace struct {
Labels []string // Label names for this namespace
ColumnMappings map[string]MetricMap // Column mappings in this namespace
Labels []string // Label names for this ExporterNamespaceLabel
ColumnMappings map[string]MetricMap // Column mappings in this ExporterNamespaceLabel
Master bool // Call query only for master database
CacheSeconds uint64 // Number of seconds this metric namespace can be cached. 0 disables.
CacheSeconds uint64 // Number of seconds this metric ExporterNamespaceLabel can be cached. 0 disables.
}
// MetricMap stores the prometheus metric description which a given column will
// be mapped to by the collector
type MetricMap struct {
Discard bool // Should metric be discarded during mapping?
ValueType prometheus.ValueType // Prometheus valuetype
ValueType prometheus.ValueType // Prometheus valuetype
Desc *prometheus.Desc // Prometheus descriptor
Conversion func(interface{}) (float64, bool) // Conversion function to turn PG result into float64
}
}

View File

@ -7,16 +7,15 @@ import (
// ColumnUsage should be one of several enum values which describe how a
// queried row is to be converted to a Prometheus metric.
type ColumnUsage int
type ColumnUsage string
// nolint: golint
const (
DISCARD ColumnUsage = iota // Ignore this column
LABEL ColumnUsage = iota // Use this column as a label
COUNTER ColumnUsage = iota // Use this column as a counter
GAUGE ColumnUsage = iota // Use this column as a gauge
MAPPEDMETRIC ColumnUsage = iota // Use this column with the supplied mapping of text values
DURATION ColumnUsage = iota // This column should be interpreted as a text duration (and converted to milliseconds)
DISCARD ColumnUsage = "DISCARD" // Ignore this column
LABEL ColumnUsage = "LABEL" // Use this column as a label
COUNTER ColumnUsage = "COUNTER" // Use this column as a counter
GAUGE ColumnUsage = "GAUGE" // Use this column as a gauge
MAPPEDMETRIC ColumnUsage = "MAPPEDMETRIC" // Use this column with the supplied mapping of text values
DURATION ColumnUsage = "DURATION" // This column should be interpreted as a text duration (and converted to milliseconds)
)
// UnmarshalYAML implements the yaml.Unmarshaller interface.
@ -26,51 +25,29 @@ func (cu *ColumnUsage) UnmarshalYAML(unmarshal func(interface{}) error) error {
return err
}
columnUsage, err := StringToColumnUsage(value)
if err != nil {
return err
var columnUsage ColumnUsage
switch value {
case "DISCARD",
"LABEL",
"COUNTER",
"GAUGE",
"MAPPEDMETRIC",
"DURATION":
columnUsage = ColumnUsage(value)
default:
return fmt.Errorf("value is not a valid ColumnUsage value: %s", value)
}
*cu = columnUsage
return nil
}
// StringToColumnUsage converts a string to the corresponding ColumnUsage
func StringToColumnUsage(s string) (ColumnUsage, error) {
var u ColumnUsage
var err error
switch s {
case "DISCARD":
u = DISCARD
case "LABEL":
u = LABEL
case "COUNTER":
u = COUNTER
case "GAUGE":
u = GAUGE
case "MAPPEDMETRIC":
u = MAPPEDMETRIC
case "DURATION":
u = DURATION
default:
err = fmt.Errorf("wrong ColumnUsage given : %s", s)
}
return u, err
}
// ColumnMapping is the user-friendly representation of a prometheus descriptor map
type ColumnMapping struct {
Usage ColumnUsage `yaml:"usage"`
Description string `yaml:"description"`
Mapping map[string]float64 `yaml:"metric_mapping"` // Optional column mapping for MAPPEDMETRIC
SupportedVersions semver.Range `yaml:"pg_version"` // Semantic version ranges which are supported. Unsupported columns are not queried (internally converted to DISCARD).
SupportedVersions *SemverRange `yaml:"pg_version"` // Semantic version ranges which are supported. Unsupported columns are not queried (internally converted to DISCARD).
}
// UnmarshalYAML implements yaml.Unmarshaller
@ -79,26 +56,78 @@ func (cm *ColumnMapping) UnmarshalYAML(unmarshal func(interface{}) error) error
return unmarshal((*plain)(cm))
}
// nolint: golint
type Mapping map[string]MappingOptions
// nolint: golint
type UserQuery struct {
Query string `yaml:"query"`
Metrics []Mapping `yaml:"metrics"`
Master bool `yaml:"master"` // Querying only for master database
CacheSeconds uint64 `yaml:"cache_seconds"` // Number of seconds to cache the namespace result metrics for.
CacheSeconds uint64 `yaml:"cache_seconds"` // Number of seconds to cache the ExporterNamespaceLabel result metrics for.
}
// nolint: golint
type UserQueries map[string]UserQuery
// OverrideQuery are run in-place of simple namespace look ups, and provide
// OverrideQuery are run in-place of simple ExporterNamespaceLabel look ups, and provide
// advanced functionality. But they have a tendency to postgres version specific.
// There aren't too many versions, so we simply store customized versions using
// the semver matching we do for columns.
type OverrideQuery struct {
VersionRange semver.Range
Query string
}
// SemverRange implements YAML marshalling for semver.Range
type SemverRange struct {
r string
semver.Range
}
// MustParseSemverRange parses a semver
func MustParseSemverRange(s string) *SemverRange {
r, err := ParseSemverRange(s)
if err != nil {
panic(err)
}
return r
}
// ParseSemverRange parses a semver
func ParseSemverRange(s string) (*SemverRange, error) {
r, err := semver.ParseRange(s)
if err != nil {
return nil, err
}
return &SemverRange{s, r}, nil
}
func (sr *SemverRange) String() string {
if sr != nil {
return sr.r
} else {
return "(any)"
}
}
// MarshalYAML implements yaml.Marshaller
func (sr *SemverRange) MarshalYAML() (interface{}, error) {
if sr == nil {
return nil, nil
}
return sr.r, nil
}
// UnmarshalYAML implements yaml.Unmarshaller
func (sr *SemverRange) UnmarshalYAML(unmarshal func(interface{}) error) error {
var err error
var rangeStr string
if err = unmarshal(&rangeStr); err != nil {
return err
}
sr, err = ParseSemverRange(rangeStr)
if err != nil {
return err
}
return nil
}

View File

@ -0,0 +1,21 @@
package metricmaps
import (
"fmt"
. "gopkg.in/check.v1"
"gopkg.in/yaml.v2"
)
type SemverSuite struct{}
var _ = Suite(&SemverSuite{})
func (s *SemverSuite) TestEncodeYAML(c *C) {
sr, err := ParseSemverRange(">=1.0.0")
c.Assert(err, IsNil)
fmt.Println(sr)
b, err := yaml.Marshal(&sr)
c.Check(err, IsNil)
fmt.Println(string(b))
}

View File

@ -43,4 +43,4 @@ func parseUserQueries(content []byte) (map[string]intermediateMetricMap, map[str
}
}
return metricMaps, newQueryOverrides, nil
}
}

View File

@ -0,0 +1,11 @@
package servers
import (
"github.com/prometheus/client_golang/prometheus"
"time"
)
type cachedMetrics struct {
metrics []prometheus.Metric
lastScrape time.Time
}

View File

@ -51,4 +51,4 @@ func loggableDSN(dsn string) string {
}
return pDSN.String()
}
}

View File

@ -1,7 +1,8 @@
package main
package servers
import (
"fmt"
"github.com/wrouesnel/postgres_exporter/pkg/queries/metricmaps"
"math"
"strconv"
"strings"
@ -10,35 +11,6 @@ import (
"github.com/prometheus/common/log"
)
// Query the pg_settings view containing runtime variables
func querySettings(ch chan<- prometheus.Metric, server *Server) error {
log.Debugf("Querying pg_setting view on %q", server)
// pg_settings docs: https://www.postgresql.org/docs/current/static/view-pg-settings.html
//
// NOTE: If you add more vartypes here, you must update the supported
// types in normaliseUnit() below
query := "SELECT name, setting, COALESCE(unit, ''), short_desc, vartype FROM pg_settings WHERE vartype IN ('bool', 'integer', 'real');"
rows, err := server.db.Query(query)
if err != nil {
return fmt.Errorf("Error running query on database %q: %s %v", server, namespace, err)
}
defer rows.Close() // nolint: errcheck
for rows.Next() {
s := &pgSetting{}
err = rows.Scan(&s.name, &s.setting, &s.unit, &s.shortDesc, &s.vartype)
if err != nil {
return fmt.Errorf("Error retrieving rows on %q: %s %v", server, namespace, err)
}
ch <- s.metric(server.labels)
}
return nil
}
// pgSetting is represents a PostgreSQL runtime variable as returned by the
// pg_settings view.
type pgSetting struct {

View File

@ -1,6 +1,6 @@
// +build !integration
package main
package servers
import (
"github.com/prometheus/client_golang/prometheus"

View File

@ -4,14 +4,17 @@ import (
"database/sql"
"fmt"
"github.com/blang/semver"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
"github.com/wrouesnel/postgres_exporter/pkg/pgdbconv"
"github.com/wrouesnel/postgres_exporter/pkg/queries/metricmaps"
"sync"
"time"
)
// Server describes a connection to a Postgresql database, and describes the
// metric maps and overrides in-place for it.
// Also it contains metrics map and query overrides.
type Server struct {
db *sql.DB
labels prometheus.Labels
@ -21,7 +24,7 @@ type Server struct {
// then maps are recalculated.
lastMapVersion semver.Version
// Currently active metric map
metricMap map[string]MetricMapNamespace
metricMap map[string]metricmaps.MetricMapNamespace
// Currently active query overrides
queryOverrides map[string]string
mappingMtx sync.RWMutex
@ -50,7 +53,7 @@ func NewServer(dsn string, opts ...ServerOpt) (*Server, error) {
db: db,
master: false,
labels: prometheus.Labels{
serverLabelName: fingerprint,
metricmaps.ServerLabelName: fingerprint,
},
metricCache: make(map[string]cachedMetrics),
}
@ -80,7 +83,7 @@ func (s *Server) Ping() error {
// String returns server's fingerprint.
func (s *Server) String() string {
return s.labels[serverLabelName]
return s.labels[metricmaps.ServerLabelName]
}
// Scrape loads metrics.
@ -104,9 +107,211 @@ func (s *Server) Scrape(ch chan<- prometheus.Metric, disableSettingsMetrics bool
return err
}
// Query within a namespace mapping and emit metrics. Returns fatal errors if
// the scrape fails, and a slice of errors if they were non-fatal.
func (s *Server) queryNamespaceMapping(namespace string, mapping MetricMapNamespace) ([]prometheus.Metric, []error, error) {
// Check for a query override for this namespace
query, found := s.queryOverrides[namespace]
// Was this query disabled (i.e. nothing sensible can be queried on cu
// version of PostgreSQL?
if query == "" && found {
// Return success (no pertinent data)
return []prometheus.Metric{}, []error{}, nil
}
// Don't fail on a bad scrape of one metric
var rows *sql.Rows
var err error
if !found {
// I've no idea how to avoid this properly at the moment, but this is
// an admin tool so you're not injecting SQL right?
rows, err = s.db.Query(fmt.Sprintf("SELECT * FROM %s;", namespace)) // nolint: gas, safesql
} else {
rows, err = s.db.Query(query) // nolint: safesql
}
if err != nil {
return []prometheus.Metric{}, []error{}, fmt.Errorf("Error running query on database %q: %s %v", s, namespace, err)
}
defer rows.Close() // nolint: errcheck
var columnNames []string
columnNames, err = rows.Columns()
if err != nil {
return []prometheus.Metric{}, []error{}, errors.New(fmt.Sprintln("Error retrieving column list for: ", namespace, err))
}
// Make a lookup map for the column indices
var columnIdx = make(map[string]int, len(columnNames))
for i, n := range columnNames {
columnIdx[n] = i
}
var columnData = make([]interface{}, len(columnNames))
var scanArgs = make([]interface{}, len(columnNames))
for i := range columnData {
scanArgs[i] = &columnData[i]
}
nonfatalErrors := []error{}
metrics := make([]prometheus.Metric, 0)
for rows.Next() {
err = rows.Scan(scanArgs...)
if err != nil {
return []prometheus.Metric{}, []error{}, errors.New(fmt.Sprintln("Error retrieving rows:", namespace, err))
}
// Get the label values for this row.
labels := make([]string, len(mapping.labels))
for idx, label := range mapping.labels {
labels[idx], _ = pgdbconv.DBToString(columnData[columnIdx[label]])
}
// Loop over column names, and match to scan data. Unknown columns
// will be filled with an untyped metric number *if* they can be
// converted to float64s. NULLs are allowed and treated as NaN.
for idx, columnName := range columnNames {
var metric prometheus.Metric
if metricMapping, ok := mapping.columnMappings[columnName]; ok {
// Is this a metricy metric?
if metricMapping.discard {
continue
}
value, ok := pgdbconv.DBToFloat64(columnData[idx])
if !ok {
nonfatalErrors = append(nonfatalErrors, errors.New(fmt.Sprintln("Unexpected error parsing column: ", namespace, columnName, columnData[idx])))
continue
}
// Generate the metric
metric = prometheus.MustNewConstMetric(metricMapping.desc, metricMapping.vtype, value, labels...)
} else {
// Unknown metric. Report as untyped if scan to float64 works, else note an error too.
metricLabel := fmt.Sprintf("%s_%s", namespace, columnName)
desc := prometheus.NewDesc(metricLabel, fmt.Sprintf("Unknown metric from %s", namespace), mapping.labels, s.labels)
// Its not an error to fail here, since the values are
// unexpected anyway.
value, ok := pgdbconv.DBToFloat64(columnData[idx])
if !ok {
nonfatalErrors = append(nonfatalErrors, errors.New(fmt.Sprintln("Unparseable column type - discarding: ", namespace, columnName, err)))
continue
}
metric = prometheus.MustNewConstMetric(desc, prometheus.UntypedValue, value, labels...)
}
metrics = append(metrics, metric)
}
}
return metrics, nonfatalErrors, nil
}
// Iterate through all the namespace mappings in the exporter and run their
// queries.
func (s *Server) queryNamespaceMappings(ch chan<- prometheus.Metric) map[string]error {
// Return a map of namespace -> errors
namespaceErrors := make(map[string]error)
scrapeStart := time.Now()
for namespace, mapping := range s.metricMap {
log.Debugln("Querying namespace: ", namespace)
if mapping.master && !s.master {
log.Debugln("Query skipped...")
continue
}
scrapeMetric := false
// Check if the metric is cached
s.cacheMtx.Lock()
cachedMetric, found := s.metricCache[namespace]
s.cacheMtx.Unlock()
// If found, check if needs refresh from cache
if found {
if scrapeStart.Sub(cachedMetric.lastScrape).Seconds() > float64(mapping.cacheSeconds) {
scrapeMetric = true
}
} else {
scrapeMetric = true
}
var metrics []prometheus.Metric
var nonFatalErrors []error
var err error
if scrapeMetric {
metrics, nonFatalErrors, err = s.queryNamespaceMapping(namespace, mapping)
} else {
metrics = cachedMetric.metrics
}
// Serious error - a namespace disappeared
if err != nil {
namespaceErrors[namespace] = err
log.Infoln(err)
}
// Non-serious errors - likely version or parsing problems.
if len(nonFatalErrors) > 0 {
for _, err := range nonFatalErrors {
log.Infoln(err.Error())
}
}
// Emit the metrics into the channel
for _, metric := range metrics {
ch <- metric
}
if scrapeMetric {
// Only cache if metric is meaningfully cacheable
if mapping.cacheSeconds > 0 {
s.cacheMtx.Lock()
s.metricCache[namespace] = cachedMetrics{
metrics: metrics,
lastScrape: scrapeStart,
}
s.cacheMtx.Unlock()
}
}
}
return namespaceErrors
}
// AddQueries adds queries to the builtinMetricMaps and queryOverrides maps.
// Added queries do not respect version requirements, because it is assumed
// that the user knows what they are doing with their version of postgres.
func (s *Server) AddQueries() {
}
// Query the pg_settings view containing runtime variables
func (s *Server) querySettings(ch chan<- prometheus.Metric) error {
log.Debugf("Querying pg_setting view on %q", s)
// pg_settings docs: https://www.postgresql.org/docs/current/static/view-pg-settings.html
//
// NOTE: If you add more vartypes here, you must update the supported
// types in normaliseUnit() below
query := "SELECT name, setting, COALESCE(unit, ''), short_desc, vartype FROM pg_settings WHERE vartype IN ('bool', 'integer', 'real');"
rows, err := s.db.Query(query)
if err != nil {
return fmt.Errorf("Error running query on database %q: %s %v", s, metricmaps.ExporterNamespaceLabel, err)
}
defer rows.Close() // nolint: errcheck
for rows.Next() {
setting := &pgSetting{}
err = rows.Scan(&setting.name, &setting.setting, &setting.unit, &setting.shortDesc, &setting.vartype)
if err != nil {
return fmt.Errorf("Error retrieving rows on %q: %s %v", s, metricmaps.ExporterNamespaceLabel, err)
}
ch <- setting.metric(s.labels)
}
return nil
}

View File

@ -1,5 +1,7 @@
package servers
import "github.com/prometheus/client_golang/prometheus"
type ServerOpt func(*Server)
// ServerWithLabels configures a set of labels.
@ -9,4 +11,4 @@ func ServerWithLabels(labels prometheus.Labels) ServerOpt {
s.labels[k] = v
}
}
}
}