Add support for optional namespace caching. (#319)

In the user queries.yml file, the created namespaces can now be optionally
cached by setting cache_seconds, which will prevent the query being re-run
within that timeframe if previous results are available.

Supercedes #211, credit to @SamSaffron for the original PR.
This commit is contained in:
Will Rouesnel 2019-11-01 00:17:31 +11:00 committed by GitHub
parent 1385b4f658
commit 34fdb69ee2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 198 additions and 122 deletions

View File

@ -98,8 +98,9 @@ type Mapping map[string]MappingOptions
// nolint: golint // nolint: golint
type UserQuery struct { type UserQuery struct {
Query string `yaml:"query"` Query string `yaml:"query"`
Metrics []Mapping `yaml:"metrics"` Metrics []Mapping `yaml:"metrics"`
CacheSeconds uint64 `yaml:"cache_seconds"` // Number of seconds to cache the namespace result metrics for.
} }
// nolint: golint // nolint: golint
@ -134,10 +135,18 @@ func (cm *ColumnMapping) UnmarshalYAML(unmarshal func(interface{}) error) error
return unmarshal((*plain)(cm)) return unmarshal((*plain)(cm))
} }
// intermediateMetricMap holds the partially loaded metric map parsing.
// This is mainly so we can parse cacheSeconds around.
type intermediateMetricMap struct {
columnMappings map[string]ColumnMapping
cacheSeconds uint64
}
// MetricMapNamespace groups metric maps under a shared set of labels. // MetricMapNamespace groups metric maps under a shared set of labels.
type MetricMapNamespace struct { type MetricMapNamespace struct {
labels []string // Label names for this namespace labels []string // Label names for this namespace
columnMappings map[string]MetricMap // Column mappings in this namespace columnMappings map[string]MetricMap // Column mappings in this namespace
cacheSeconds uint64 // Number of seconds this metric namespace can be cached. 0 disables.
} }
// MetricMap stores the prometheus metric description which a given column will // MetricMap stores the prometheus metric description which a given column will
@ -172,109 +181,111 @@ func dumpMaps() {
} }
} }
for column, details := range cmap { for column, details := range cmap.columnMappings {
fmt.Printf(" %-40s %v\n", column, details) fmt.Printf(" %-40s %v\n", column, details)
} }
fmt.Println() fmt.Println()
} }
} }
var builtinMetricMaps = map[string]map[string]ColumnMapping{ var builtinMetricMaps = map[string]intermediateMetricMap{
"pg_stat_bgwriter": {
"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},
},
"pg_stat_database": { "pg_stat_database": {
"datid": {LABEL, "OID of a database", nil, nil}, map[string]ColumnMapping{
"datname": {LABEL, "Name of this database", nil, nil}, "datid": {LABEL, "OID of a 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}, "datname": {LABEL, "Name of this database", nil, nil},
"xact_commit": {COUNTER, "Number of transactions in this database that have been committed", 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_rollback": {COUNTER, "Number of transactions in this database that have been rolled back", nil, nil}, "xact_commit": {COUNTER, "Number of transactions in this database that have been committed", nil, nil},
"blks_read": {COUNTER, "Number of disk blocks read in this database", nil, nil}, "xact_rollback": {COUNTER, "Number of transactions in this database that have been rolled back", 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}, "blks_read": {COUNTER, "Number of disk blocks read in this database", nil, nil},
"tup_returned": {COUNTER, "Number of rows returned by queries 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_fetched": {COUNTER, "Number of rows fetched by queries in this database", nil, nil}, "tup_returned": {COUNTER, "Number of rows returned by queries in this database", nil, nil},
"tup_inserted": {COUNTER, "Number of rows inserted by queries in this database", nil, nil}, "tup_fetched": {COUNTER, "Number of rows fetched by queries in this database", nil, nil},
"tup_updated": {COUNTER, "Number of rows updated by queries in this database", nil, nil}, "tup_inserted": {COUNTER, "Number of rows inserted by queries in this database", nil, nil},
"tup_deleted": {COUNTER, "Number of rows deleted by queries in this database", nil, nil}, "tup_updated": {COUNTER, "Number of rows updated 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}, "tup_deleted": {COUNTER, "Number of rows deleted by queries in this database", 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}, "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_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}, "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},
"deadlocks": {COUNTER, "Number of deadlocks detected in this database", 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},
"blk_read_time": {COUNTER, "Time spent reading data file blocks by backends in this database, in milliseconds", nil, nil}, "deadlocks": {COUNTER, "Number of deadlocks detected in this database", nil, nil},
"blk_write_time": {COUNTER, "Time spent writing data file blocks by backends in this database, in milliseconds", nil, nil}, "blk_read_time": {COUNTER, "Time spent reading 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}, "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},
},
0,
}, },
"pg_stat_database_conflicts": { "pg_stat_database_conflicts": {
"datid": {LABEL, "OID of a database", nil, nil}, map[string]ColumnMapping{
"datname": {LABEL, "Name of this database", nil, nil}, "datid": {LABEL, "OID of a database", nil, nil},
"confl_tablespace": {COUNTER, "Number of queries in this database that have been canceled due to dropped tablespaces", nil, nil}, "datname": {LABEL, "Name of this database", nil, nil},
"confl_lock": {COUNTER, "Number of queries in this database that have been canceled due to lock timeouts", nil, nil}, "confl_tablespace": {COUNTER, "Number of queries in this database that have been canceled due to dropped tablespaces", nil, nil},
"confl_snapshot": {COUNTER, "Number of queries in this database that have been canceled due to old snapshots", nil, nil}, "confl_lock": {COUNTER, "Number of queries in this database that have been canceled due to lock timeouts", nil, nil},
"confl_bufferpin": {COUNTER, "Number of queries in this database that have been canceled due to pinned buffers", nil, nil}, "confl_snapshot": {COUNTER, "Number of queries in this database that have been canceled due to old snapshots", nil, nil},
"confl_deadlock": {COUNTER, "Number of queries in this database that have been canceled due to deadlocks", 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},
},
0,
}, },
"pg_locks": { "pg_locks": {
"datname": {LABEL, "Name of this database", nil, nil}, map[string]ColumnMapping{
"mode": {LABEL, "Type of Lock", nil, nil}, "datname": {LABEL, "Name of this database", nil, nil},
"count": {GAUGE, "Number of locks", nil, nil}, "mode": {LABEL, "Type of Lock", nil, nil},
"count": {GAUGE, "Number of locks", nil, nil},
},
0,
}, },
"pg_stat_replication": { "pg_stat_replication": {
"procpid": {DISCARD, "Process ID of a WAL sender process", nil, semver.MustParseRange("<9.2.0")}, map[string]ColumnMapping{
"pid": {DISCARD, "Process ID of a WAL sender process", nil, semver.MustParseRange(">=9.2.0")}, "procpid": {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}, "pid": {DISCARD, "Process ID of a WAL sender process", nil, semver.MustParseRange(">=9.2.0")},
"usename": {DISCARD, "Name of the user logged into this WAL sender process", nil, nil}, "usesysid": {DISCARD, "OID 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}, "usename": {DISCARD, "Name of the user logged into this WAL sender process", 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}, "application_name": {LABEL, "Name of the application that is connected to this WAL sender", 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_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_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}, "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},
"backend_start": {DISCARD, "with time zone Time when this process was started, i.e., when the client connected to this WAL sender", 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_xmin": {DISCARD, "The current backend's xmin horizon.", 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},
"state": {LABEL, "Current WAL sender state", nil, nil}, "backend_xmin": {DISCARD, "The current backend's xmin horizon.", nil, nil},
"sent_location": {DISCARD, "Last transaction log position sent on this connection", nil, semver.MustParseRange("<10.0.0")}, "state": {LABEL, "Current WAL sender state", nil, nil},
"write_location": {DISCARD, "Last transaction log position written to disk by this standby server", nil, semver.MustParseRange("<10.0.0")}, "sent_location": {DISCARD, "Last transaction log position sent on this connection", 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")}, "write_location": {DISCARD, "Last transaction log position written 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")}, "flush_location": {DISCARD, "Last transaction log position flushed to disk by 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")}, "replay_location": {DISCARD, "Last transaction log position replayed into the database on this standby server", 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")}, "sent_lsn": {DISCARD, "Last transaction log position sent on this connection", 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")}, "write_lsn": {DISCARD, "Last transaction log position written 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")}, "flush_lsn": {DISCARD, "Last transaction log position flushed to disk by 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}, "replay_lsn": {DISCARD, "Last transaction log position replayed into the database on this standby server", nil, semver.MustParseRange(">=10.0.0")},
"sync_state": {DISCARD, "Synchronous state of this standby server", nil, nil}, "sync_priority": {DISCARD, "Priority of this standby server for being chosen as the synchronous standby", nil, nil},
"slot_name": {LABEL, "A unique, cluster-wide identifier for the replication slot", nil, semver.MustParseRange(">=9.2.0")}, "sync_state": {DISCARD, "Synchronous state of this standby server", nil, nil},
"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_name": {LABEL, "A unique, cluster-wide identifier for the replication slot", nil, semver.MustParseRange(">=9.2.0")},
"slot_type": {DISCARD, "The slot type - physical or logical", nil, nil}, "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},
"datoid": {DISCARD, "The OID of the database this slot is associated with, or null. Only logical slots have an associated database", nil, nil}, "slot_type": {DISCARD, "The slot type - physical or logical", 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}, "datoid": {DISCARD, "The OID 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}, "database": {DISCARD, "The name of the database this slot is associated with, or null. Only logical slots have an associated database", nil, nil},
"active_pid": {DISCARD, "Process ID of a WAL sender process", nil, nil}, "active": {DISCARD, "True if this slot is currently actively being used", 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}, "active_pid": {DISCARD, "Process ID of a WAL sender process", 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}, "xmin": {DISCARD, "The oldest transaction that this slot needs the database to retain. VACUUM cannot remove 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}, "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},
"pg_current_xlog_location": {DISCARD, "pg_current_xlog_location", 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_wal_lsn": {DISCARD, "pg_current_xlog_location", nil, semver.MustParseRange(">=10.0.0")}, "pg_current_xlog_location": {DISCARD, "pg_current_xlog_location", nil, nil},
"pg_current_wal_lsn_bytes": {GAUGE, "WAL position in bytes", nil, semver.MustParseRange(">=10.0.0")}, "pg_current_wal_lsn": {DISCARD, "pg_current_xlog_location", 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_current_wal_lsn_bytes": {GAUGE, "WAL position in bytes", nil, semver.MustParseRange(">=10.0.0")},
"pg_wal_lsn_diff": {GAUGE, "Lag in bytes between master and slave", 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")},
"confirmed_flush_lsn": {DISCARD, "LSN position a consumer of a slot has confirmed flushing the data received", nil, nil}, "pg_wal_lsn_diff": {GAUGE, "Lag in bytes between master and slave", nil, semver.MustParseRange(">=10.0.0")},
"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")}, "confirmed_flush_lsn": {DISCARD, "LSN position a consumer of a slot has confirmed flushing the data received", nil, nil},
"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")}, "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")},
"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")}, "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")},
},
0,
}, },
"pg_stat_activity": { "pg_stat_activity": {
"datname": {LABEL, "Name of this database", nil, nil}, map[string]ColumnMapping{
"state": {LABEL, "connection state", nil, semver.MustParseRange(">=9.2.0")}, "datname": {LABEL, "Name of this database", nil, nil},
"count": {GAUGE, "number of connections in this state", nil, nil}, "state": {LABEL, "connection state", nil, semver.MustParseRange(">=9.2.0")},
"max_tx_duration": {GAUGE, "max duration in seconds any active transaction has been running", nil, nil}, "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},
},
0,
}, },
} }
@ -412,7 +423,7 @@ func makeQueryOverrideMap(pgVersion semver.Version, queryOverrides map[string][]
return resultMap return resultMap
} }
func parseUserQueries(content []byte) (map[string]map[string]ColumnMapping, map[string]string, error) { func parseUserQueries(content []byte) (map[string]intermediateMetricMap, map[string]string, error) {
var userQueries UserQueries var userQueries UserQueries
err := yaml.Unmarshal(content, &userQueries) err := yaml.Unmarshal(content, &userQueries)
@ -421,16 +432,20 @@ func parseUserQueries(content []byte) (map[string]map[string]ColumnMapping, map[
} }
// Stores the loaded map representation // Stores the loaded map representation
metricMaps := make(map[string]map[string]ColumnMapping) metricMaps := make(map[string]intermediateMetricMap)
newQueryOverrides := make(map[string]string) newQueryOverrides := make(map[string]string)
for metric, specs := range userQueries { for metric, specs := range userQueries {
log.Debugln("New user metric namespace from YAML:", metric) log.Debugln("New user metric namespace from YAML:", metric, "Will cache results for:", specs.CacheSeconds)
newQueryOverrides[metric] = specs.Query newQueryOverrides[metric] = specs.Query
metricMap, ok := metricMaps[metric] metricMap, ok := metricMaps[metric]
if !ok { if !ok {
// Namespace for metric not found - add it. // Namespace for metric not found - add it.
metricMap = make(map[string]ColumnMapping) newMetricMap := make(map[string]ColumnMapping)
metricMap = intermediateMetricMap{
columnMappings: newMetricMap,
cacheSeconds: specs.CacheSeconds,
}
metricMaps[metric] = metricMap metricMaps[metric] = metricMap
} }
for _, metric := range specs.Metrics { for _, metric := range specs.Metrics {
@ -444,7 +459,8 @@ func parseUserQueries(content []byte) (map[string]map[string]ColumnMapping, map[
columnMapping.mapping = nil columnMapping.mapping = nil
// Should we support this for users? // Should we support this for users?
columnMapping.supportedVersions = nil columnMapping.supportedVersions = nil
metricMap[name] = columnMapping
metricMap.columnMappings[name] = columnMapping
} }
} }
} }
@ -492,21 +508,21 @@ func addQueries(content []byte, pgVersion semver.Version, server *Server) error
} }
// Turn the MetricMap column mapping into a prometheus descriptor mapping. // Turn the MetricMap column mapping into a prometheus descriptor mapping.
func makeDescMap(pgVersion semver.Version, serverLabels prometheus.Labels, metricMaps map[string]map[string]ColumnMapping) map[string]MetricMapNamespace { func makeDescMap(pgVersion semver.Version, serverLabels prometheus.Labels, metricMaps map[string]intermediateMetricMap) map[string]MetricMapNamespace {
var metricMap = make(map[string]MetricMapNamespace) var metricMap = make(map[string]MetricMapNamespace)
for namespace, mappings := range metricMaps { for namespace, intermediateMappings := range metricMaps {
thisMap := make(map[string]MetricMap) thisMap := make(map[string]MetricMap)
// Get the constant labels // Get the constant labels
var variableLabels []string var variableLabels []string
for columnName, columnMapping := range mappings { for columnName, columnMapping := range intermediateMappings.columnMappings {
if columnMapping.usage == LABEL { if columnMapping.usage == LABEL {
variableLabels = append(variableLabels, columnName) variableLabels = append(variableLabels, columnName)
} }
} }
for columnName, columnMapping := range mappings { for columnName, columnMapping := range intermediateMappings.columnMappings {
// Check column version compatibility for the current map // Check column version compatibility for the current map
// Force to discard if not compatible. // Force to discard if not compatible.
if columnMapping.supportedVersions != nil { if columnMapping.supportedVersions != nil {
@ -598,7 +614,7 @@ func makeDescMap(pgVersion semver.Version, serverLabels prometheus.Labels, metri
} }
} }
metricMap[namespace] = MetricMapNamespace{variableLabels, thisMap} metricMap[namespace] = MetricMapNamespace{variableLabels, thisMap, intermediateMappings.cacheSeconds}
} }
return metricMap return metricMap
@ -744,6 +760,11 @@ func loggableDSN(dsn string) string {
return pDSN.String() return pDSN.String()
} }
type cachedMetrics struct {
metrics []prometheus.Metric
lastScrape time.Time
}
// Server describes a connection to Postgres. // Server describes a connection to Postgres.
// Also it contains metrics map and query overrides. // Also it contains metrics map and query overrides.
type Server struct { type Server struct {
@ -759,6 +780,9 @@ type Server struct {
// Currently active query overrides // Currently active query overrides
queryOverrides map[string]string queryOverrides map[string]string
mappingMtx sync.RWMutex mappingMtx sync.RWMutex
// Currently cached metrics
metricCache map[string]cachedMetrics
cacheMtx sync.Mutex
} }
// ServerOpt configures a server. // ServerOpt configures a server.
@ -795,6 +819,7 @@ func NewServer(dsn string, opts ...ServerOpt) (*Server, error) {
labels: prometheus.Labels{ labels: prometheus.Labels{
serverLabelName: fingerprint, serverLabelName: fingerprint,
}, },
metricCache: make(map[string]cachedMetrics),
} }
for _, opt := range opts { for _, opt := range opts {
@ -908,7 +933,7 @@ func (s *Servers) Close() {
type Exporter struct { type Exporter struct {
// Holds a reference to the build in column mappings. Currently this is for testing purposes // Holds a reference to the build in column mappings. Currently this is for testing purposes
// only, since it just points to the global. // only, since it just points to the global.
builtinMetricMaps map[string]map[string]ColumnMapping builtinMetricMaps map[string]intermediateMetricMap
disableDefaultMetrics, disableSettingsMetrics, autoDiscoverDatabases bool disableDefaultMetrics, disableSettingsMetrics, autoDiscoverDatabases bool
@ -1123,7 +1148,7 @@ func queryDatabases(server *Server) ([]string, error) {
// Query within a namespace mapping and emit metrics. Returns fatal errors if // 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. // the scrape fails, and a slice of errors if they were non-fatal.
func queryNamespaceMapping(ch chan<- prometheus.Metric, server *Server, namespace string, mapping MetricMapNamespace) ([]error, error) { func queryNamespaceMapping(server *Server, namespace string, mapping MetricMapNamespace) ([]prometheus.Metric, []error, error) {
// Check for a query override for this namespace // Check for a query override for this namespace
query, found := server.queryOverrides[namespace] query, found := server.queryOverrides[namespace]
@ -1131,7 +1156,7 @@ func queryNamespaceMapping(ch chan<- prometheus.Metric, server *Server, namespac
// version of PostgreSQL? // version of PostgreSQL?
if query == "" && found { if query == "" && found {
// Return success (no pertinent data) // Return success (no pertinent data)
return []error{}, nil return []prometheus.Metric{}, []error{}, nil
} }
// Don't fail on a bad scrape of one metric // Don't fail on a bad scrape of one metric
@ -1146,14 +1171,14 @@ func queryNamespaceMapping(ch chan<- prometheus.Metric, server *Server, namespac
rows, err = server.db.Query(query) // nolint: safesql rows, err = server.db.Query(query) // nolint: safesql
} }
if err != nil { if err != nil {
return []error{}, fmt.Errorf("Error running query on database %q: %s %v", server, namespace, err) return []prometheus.Metric{}, []error{}, fmt.Errorf("Error running query on database %q: %s %v", server, namespace, err)
} }
defer rows.Close() // nolint: errcheck defer rows.Close() // nolint: errcheck
var columnNames []string var columnNames []string
columnNames, err = rows.Columns() columnNames, err = rows.Columns()
if err != nil { if err != nil {
return []error{}, errors.New(fmt.Sprintln("Error retrieving column list for: ", namespace, err)) return []prometheus.Metric{}, []error{}, errors.New(fmt.Sprintln("Error retrieving column list for: ", namespace, err))
} }
// Make a lookup map for the column indices // Make a lookup map for the column indices
@ -1170,10 +1195,12 @@ func queryNamespaceMapping(ch chan<- prometheus.Metric, server *Server, namespac
nonfatalErrors := []error{} nonfatalErrors := []error{}
metrics := make([]prometheus.Metric, 0)
for rows.Next() { for rows.Next() {
err = rows.Scan(scanArgs...) err = rows.Scan(scanArgs...)
if err != nil { if err != nil {
return []error{}, errors.New(fmt.Sprintln("Error retrieving rows:", namespace, err)) return []prometheus.Metric{}, []error{}, errors.New(fmt.Sprintln("Error retrieving rows:", namespace, err))
} }
// Get the label values for this row. // Get the label values for this row.
@ -1186,6 +1213,7 @@ func queryNamespaceMapping(ch chan<- prometheus.Metric, server *Server, namespac
// will be filled with an untyped metric number *if* they can be // will be filled with an untyped metric number *if* they can be
// converted to float64s. NULLs are allowed and treated as NaN. // converted to float64s. NULLs are allowed and treated as NaN.
for idx, columnName := range columnNames { for idx, columnName := range columnNames {
var metric prometheus.Metric
if metricMapping, ok := mapping.columnMappings[columnName]; ok { if metricMapping, ok := mapping.columnMappings[columnName]; ok {
// Is this a metricy metric? // Is this a metricy metric?
if metricMapping.discard { if metricMapping.discard {
@ -1197,9 +1225,8 @@ func queryNamespaceMapping(ch chan<- prometheus.Metric, server *Server, namespac
nonfatalErrors = append(nonfatalErrors, errors.New(fmt.Sprintln("Unexpected error parsing column: ", namespace, columnName, columnData[idx]))) nonfatalErrors = append(nonfatalErrors, errors.New(fmt.Sprintln("Unexpected error parsing column: ", namespace, columnName, columnData[idx])))
continue continue
} }
// Generate the metric // Generate the metric
ch <- prometheus.MustNewConstMetric(metricMapping.desc, metricMapping.vtype, value, labels...) metric = prometheus.MustNewConstMetric(metricMapping.desc, metricMapping.vtype, value, labels...)
} else { } else {
// Unknown metric. Report as untyped if scan to float64 works, else note an error too. // Unknown metric. Report as untyped if scan to float64 works, else note an error too.
metricLabel := fmt.Sprintf("%s_%s", namespace, columnName) metricLabel := fmt.Sprintf("%s_%s", namespace, columnName)
@ -1212,11 +1239,12 @@ func queryNamespaceMapping(ch chan<- prometheus.Metric, server *Server, namespac
nonfatalErrors = append(nonfatalErrors, errors.New(fmt.Sprintln("Unparseable column type - discarding: ", namespace, columnName, err))) nonfatalErrors = append(nonfatalErrors, errors.New(fmt.Sprintln("Unparseable column type - discarding: ", namespace, columnName, err)))
continue continue
} }
ch <- prometheus.MustNewConstMetric(desc, prometheus.UntypedValue, value, labels...) metric = prometheus.MustNewConstMetric(desc, prometheus.UntypedValue, value, labels...)
} }
metrics = append(metrics, metric)
} }
} }
return nonfatalErrors, nil return metrics, nonfatalErrors, nil
} }
// Iterate through all the namespace mappings in the exporter and run their // Iterate through all the namespace mappings in the exporter and run their
@ -1225,9 +1253,33 @@ func queryNamespaceMappings(ch chan<- prometheus.Metric, server *Server) map[str
// Return a map of namespace -> errors // Return a map of namespace -> errors
namespaceErrors := make(map[string]error) namespaceErrors := make(map[string]error)
scrapeStart := time.Now()
for namespace, mapping := range server.metricMap { for namespace, mapping := range server.metricMap {
log.Debugln("Querying namespace: ", namespace) log.Debugln("Querying namespace: ", namespace)
nonFatalErrors, err := queryNamespaceMapping(ch, server, namespace, mapping) 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 // Serious error - a namespace disappeared
if err != nil { if err != nil {
namespaceErrors[namespace] = err namespaceErrors[namespace] = err
@ -1239,6 +1291,23 @@ func queryNamespaceMappings(ch chan<- prometheus.Metric, server *Server) map[str
log.Infoln(err.Error()) 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 return namespaceErrors
@ -1399,7 +1468,7 @@ func (e *Exporter) discoverDatabaseDSNs() []string {
func (e *Exporter) scrapeDSN(ch chan<- prometheus.Metric, dsn string) error { func (e *Exporter) scrapeDSN(ch chan<- prometheus.Metric, dsn string) error {
server, err := e.servers.GetServer(dsn) server, err := e.servers.GetServer(dsn)
if err != nil { if err != nil {
return &ErrorConnectToServer{fmt.Sprintf("Error opening connection to database (%s): %s", loggableDSN(dsn), err)} return &ErrorConnectToServer{fmt.Sprintf("Error opening connection to database (%s): %s", loggableDSN(dsn), err.Error())}
} }
// Check if map versions need to be updated // Check if map versions need to be updated

View File

@ -113,9 +113,12 @@ func (s *IntegrationSuite) TestUnknownMetricParsingDoesntCrash(c *C) {
c.Assert(exporter, NotNil) c.Assert(exporter, NotNil)
// Convert the default maps into a list of empty maps. // Convert the default maps into a list of empty maps.
emptyMaps := make(map[string]map[string]ColumnMapping, 0) emptyMaps := make(map[string]intermediateMetricMap, 0)
for k := range exporter.builtinMetricMaps { for k := range exporter.builtinMetricMaps {
emptyMaps[k] = map[string]ColumnMapping{} emptyMaps[k] = intermediateMetricMap{
map[string]ColumnMapping{},
0,
}
} }
exporter.builtinMetricMaps = emptyMaps exporter.builtinMetricMaps = emptyMaps

View File

@ -26,10 +26,13 @@ func (s *FunctionalSuite) SetUpSuite(c *C) {
} }
func (s *FunctionalSuite) TestSemanticVersionColumnDiscard(c *C) { func (s *FunctionalSuite) TestSemanticVersionColumnDiscard(c *C) {
testMetricMap := map[string]map[string]ColumnMapping{ testMetricMap := map[string]intermediateMetricMap{
"test_namespace": { "test_namespace": {
"metric_which_stays": {COUNTER, "This metric should not be eliminated", nil, nil}, map[string]ColumnMapping{
"metric_which_discards": {COUNTER, "This metric should be forced to DISCARD", nil, nil}, "metric_which_stays": {COUNTER, "This metric should not be eliminated", nil, nil},
"metric_which_discards": {COUNTER, "This metric should be forced to DISCARD", nil, nil},
},
0,
}, },
} }
@ -51,9 +54,9 @@ func (s *FunctionalSuite) TestSemanticVersionColumnDiscard(c *C) {
// nolint: dupl // nolint: dupl
{ {
// Update the map so the discard metric should be eliminated // Update the map so the discard metric should be eliminated
discardableMetric := testMetricMap["test_namespace"]["metric_which_discards"] discardableMetric := testMetricMap["test_namespace"].columnMappings["metric_which_discards"]
discardableMetric.supportedVersions = semver.MustParseRange(">0.0.1") discardableMetric.supportedVersions = semver.MustParseRange(">0.0.1")
testMetricMap["test_namespace"]["metric_which_discards"] = discardableMetric testMetricMap["test_namespace"].columnMappings["metric_which_discards"] = discardableMetric
// Discard metric should be discarded // Discard metric should be discarded
resultMap := makeDescMap(semver.MustParse("0.0.1"), prometheus.Labels{}, testMetricMap) resultMap := makeDescMap(semver.MustParse("0.0.1"), prometheus.Labels{}, testMetricMap)
@ -72,9 +75,9 @@ func (s *FunctionalSuite) TestSemanticVersionColumnDiscard(c *C) {
// nolint: dupl // nolint: dupl
{ {
// Update the map so the discard metric should be kept but has a version // Update the map so the discard metric should be kept but has a version
discardableMetric := testMetricMap["test_namespace"]["metric_which_discards"] discardableMetric := testMetricMap["test_namespace"].columnMappings["metric_which_discards"]
discardableMetric.supportedVersions = semver.MustParseRange(">0.0.1") discardableMetric.supportedVersions = semver.MustParseRange(">0.0.1")
testMetricMap["test_namespace"]["metric_which_discards"] = discardableMetric testMetricMap["test_namespace"].columnMappings["metric_which_discards"] = discardableMetric
// Discard metric should be discarded // Discard metric should be discarded
resultMap := makeDescMap(semver.MustParse("0.0.2"), prometheus.Labels{}, testMetricMap) resultMap := makeDescMap(semver.MustParse("0.0.2"), prometheus.Labels{}, testMetricMap)

View File

@ -114,7 +114,8 @@ pg_statio_user_tables:
description: "Number of buffer hits in this table's TOAST table indexes (if any)" description: "Number of buffer hits in this table's TOAST table indexes (if any)"
pg_database: pg_database:
query: " SELECT pg_database.datname, pg_database_size(pg_database.datname) as size FROM pg_database" query: "SELECT pg_database.datname, pg_database_size(pg_database.datname) as size FROM pg_database"
cache_seconds: 30
metrics: metrics:
- datname: - datname:
usage: "LABEL" usage: "LABEL"