From 2a08787a90840a27d10ec519005ff92148055cd1 Mon Sep 17 00:00:00 2001 From: Will Rouesnel Date: Tue, 25 Aug 2015 03:27:14 +1000 Subject: [PATCH] Compiling version of the postgres_exporter. This is based on the mysqld_exporter, but drastically changes how metrics are discovered and enumerated since postgres already very closely follows the Prometheus format. --- .gitignore | 7 + Dockerfile | 4 + LICENSE | 202 +++++++++++++++++++++++ Makefile | 17 ++ Makefile.COMMON | 121 ++++++++++++++ README.md | 38 +++++ postgres_exporter.go | 379 +++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 768 insertions(+) create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 Makefile.COMMON create mode 100644 README.md create mode 100644 postgres_exporter.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ec2101ab --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.build +mysqld_exporter +*.tar.gz +*.test +*-stamp +.idea +*.iml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..77128aee --- /dev/null +++ b/Dockerfile @@ -0,0 +1,4 @@ +FROM sdurrheimer/alpine-golang-make-onbuild +MAINTAINER The Prometheus Authors + +EXPOSE 9113 diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..e06d2081 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..91220d6a --- /dev/null +++ b/Makefile @@ -0,0 +1,17 @@ +# Copyright 2015 The Prometheus Authors +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +VERSION := 0.1.0 +TARGET := postgres_exporter + +include Makefile.COMMON diff --git a/Makefile.COMMON b/Makefile.COMMON new file mode 100644 index 00000000..81331606 --- /dev/null +++ b/Makefile.COMMON @@ -0,0 +1,121 @@ +# Copyright 2015 The Prometheus Authors +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# THE AUTHORITATIVE VERSION OF THIS MAKEFILE LIVES IN: +# +# https://github.com/prometheus/utils +# +# PLEASE MAKE ANY CHANGES THERE AND PROPAGATE THEM TO ALL PROMETHEUS +# REPOSITORIES THAT ARE USING THIS MAKEFILE. +# +# This file provides common Makefile infrastructure for several Prometheus +# components. This includes make tasks for downloading Go, setting up a +# self-contained build environment, fetching Go dependencies, building +# binaries, running tests, and doing release management. This file is intended +# to be included from a project's Makefile, which needs to define the following +# variables, at a minimum: +# +# * VERSION - The current version of the project in question. +# * TARGET - The desired name of the built binary. +# +# Many of the variables defined below are defined conditionally (using '?'), +# which allows the project's main Makefile to override any of these settings, if +# needed. See also: +# +# https://www.gnu.org/software/make/manual/html_node/Flavors.html#Flavors. +# +# The including Makefile may define any number of extra targets that are +# specific to that project. + +VERSION ?= $(error VERSION not set in including Makefile) +TARGET ?= $(error TARGET not set in including Makefile) + +SRC ?= $(shell find . -type f -name "*.go" ! -path "./.build/*") +GOOS ?= $(shell uname | tr A-Z a-z) +GOARCH ?= $(subst x86_64,amd64,$(patsubst i%86,386,$(shell uname -m))) + +ifeq ($(GOOS),darwin) + RELEASE_SUFFIX ?= -osx$(shell sw_vers -productVersion) +endif + +GO_VERSION ?= 1.4.2 +GOURL ?= https://golang.org/dl +GOPKG ?= go$(GO_VERSION).$(GOOS)-$(GOARCH)$(RELEASE_SUFFIX).tar.gz +GOPATH := $(CURDIR)/.build/gopath + +# Check for the correct version of go in the path. If we find it, use it. +# Otherwise, prepare to build go locally. +ifeq ($(shell command -v "go" >/dev/null && go version | sed -e 's/^[^0-9.]*\([0-9.]*\).*/\1/'), $(GO_VERSION)) + GOCC ?= $(shell command -v "go") + GOFMT ?= $(shell command -v "gofmt") + GO ?= GOPATH=$(GOPATH) $(GOCC) +else + GOROOT ?= $(CURDIR)/.build/go$(GO_VERSION) + GOCC ?= $(GOROOT)/bin/go + GOFMT ?= $(GOROOT)/bin/gofmt + GO ?= GOROOT=$(GOROOT) GOPATH=$(GOPATH) $(GOCC) +endif + +# Never honor GOBIN, should it be set at all. +unexport GOBIN + +SUFFIX ?= $(GOOS)-$(GOARCH) +BINARY ?= $(TARGET) +ARCHIVE ?= $(TARGET)-$(VERSION).$(SUFFIX).tar.gz +ROOTPKG ?= github.com/prometheus/$(TARGET) +SELFLINK ?= $(GOPATH)/src/$(ROOTPKG) + +default: $(BINARY) + +$(GOCC): + @echo Go version $(GO_VERSION) required but not found in PATH. + @echo About to download and install go$(GO_VERSION) to $(GOROOT) + @echo Abort now if you want to manually install it system-wide instead. + @echo + @sleep 5 + mkdir -p $(GOROOT) + curl -L $(GOURL)/$(GOPKG) | tar -C $(GOROOT) --strip 1 -xz + +$(SELFLINK): + mkdir -p $(dir $@) + ln -s $(CURDIR) $@ + +dependencies-stamp: $(GOCC) $(SRC) | $(SELFLINK) + $(GO) get -d + touch $@ + +$(BINARY): $(GOCC) $(SRC) dependencies-stamp Makefile Makefile.COMMON + $(GO) build $(GOFLAGS) -o $@ + +.PHONY: archive +archive: $(ARCHIVE) + +$(ARCHIVE): $(BINARY) + tar -czf $@ $< + +.PHONY: tag +tag: + git tag $(VERSION) + git push --tags + +.PHONY: test +test: $(GOCC) dependencies-stamp + $(GO) test ./... + +.PHONY: format +format: $(GOCC) + find . -iname '*.go' | egrep -v "^\./\.build|./generated|\./Godeps|\.(l|y)\.go" | xargs -n1 $(GOFMT) -w -s=true + +.PHONY: clean +clean: + rm -rf $(BINARY) $(ARCHIVE) .build *-stamp diff --git a/README.md b/README.md new file mode 100644 index 00000000..7a8215ec --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# PostgresSQL Server Exporter + +Prometheus exporter for PostgresSQL server metrics. +Supported Postgres versions: 9.1 and up. + +## Building and running + + make + export DATA_SOURCE_NAME="login:password@(hostname:port)/dbname" + ./postgres_exporter + +### Flags + +Name | Description +-------------------|------------ +web.listen-address | Address to listen on for web interface and telemetry. +web.telemetry-path | Path under which to expose metrics. + +### Setting the Postgres server's data source name + +The PostgresSQL server's [data source name](http://en.wikipedia.org/wiki/Data_source_name) +must be set via the `DATA_SOURCE_NAME` environment variable. +The format of this variable is described at https://github.com/go-sql-driver/mysql#dsn-data-source-name. + +### Adding new metrics + +The exporter will attempt to dynamically export additional metrics if they are added in the +future, but they will be marked as "untyped". Additional metric maps can be easily created +from Postgres documentation by copying the tables and using the following Python snippet: + +```python +x = """tab separated raw text of a documentation table""" +for l in StringIO(x): + column, ctype, description = l.split('\t') + print """"{0}" : {{ prometheus.CounterValue, prometheus.NewDesc("pg_stat_database_{0}", "{2}", nil, nil) }}, """.format(column.strip(), ctype, description.strip()) +``` +Adjust the value of the resultant prometheus value type appropriately. This helps build +rich self-documenting metrics for the exporter. \ No newline at end of file diff --git a/postgres_exporter.go b/postgres_exporter.go new file mode 100644 index 00000000..b6f0dda3 --- /dev/null +++ b/postgres_exporter.go @@ -0,0 +1,379 @@ +package main + +import ( + //"bytes" + "database/sql" + "flag" + "fmt" + "net/http" + "os" + //"regexp" + //"strconv" + //"strings" + "time" + //"math" + + _ "github.com/lib/pq" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/log" +) + +var ( + listenAddress = flag.String( + "web.listen-address", ":9113", + "Address to listen on for web interface and telemetry.", + ) + metricPath = flag.String( + "web.telemetry-path", "/metrics", + "Path under which to expose metrics.", + ) +) + +// Metric name parts. +const ( + // Namespace for all metrics. + namespace = "pg" + // Subsystems. + exporter = "exporter" + +) + +// landingPage contains the HTML served at '/'. +// TODO: Make this nicer and more informative. +var landingPage = []byte(` +Postgres exporter + +

Postgres exporter

+

Metrics

+ + +`) + +type ColumnUsage int +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 +) + + + +// User-friendly representation of a prometheus descriptor map +type ColumnMapping struct { + usage ColumnUsage + description string + mapping map[string]float64 // Optional column mapping for MAPPEDMETRIC +} + +// 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 +} + +// 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? + vtype prometheus.ValueType // Prometheus valuetype + desc *prometheus.Desc // Prometheus descriptor + mapping map[string]float64 // If not nil, maps text values to float64s +} + +// Metric descriptors for dynamically created metrics. +var metricMaps = map[string]map[string]ColumnMapping { + "pg_stat_bgwriter" : map[string]ColumnMapping { + "checkpoints_timed" : { COUNTER, "Number of scheduled checkpoints that have been performed", nil }, + "checkpoints_req" : { COUNTER, "Number of requested checkpoints that have been performed", 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 }, + "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 }, + "buffers_checkpoint" : { COUNTER, "Number of buffers written during checkpoints", nil }, + "buffers_clean" : { COUNTER, "Number of buffers written by the background writer", nil }, + "maxwritten_clean" : { COUNTER, "Number of times the background writer stopped a cleaning scan because it had written too many buffers", nil }, + "buffers_backend" : { COUNTER, "Number of buffers written directly by a backend", 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 }, + "buffers_alloc" : { COUNTER, "Number of buffers allocated", nil }, + "stats_reset" : { COUNTER, "Time at which these statistics were last reset", nil }, + }, + "pg_stat_database" : map[string]ColumnMapping { + "datid" : { COUNTER, "OID of a database", nil }, + "datname" : { COUNTER, "Name of this database", nil }, + "numbackends" : { COUNTER, "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 }, + "xact_commit" : { COUNTER, "Number of transactions in this database that have been committed", nil }, + "xact_rollback" : { COUNTER, "Number of transactions in this database that have been rolled back", nil }, + "blks_read" : { COUNTER, "Number of disk blocks read in this database", 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 }, + "tup_returned" : { COUNTER, "Number of rows returned by queries in this database", nil }, + "tup_fetched" : { COUNTER, "Number of rows fetched by queries in this database", nil }, + "tup_inserted" : { COUNTER, "Number of rows inserted by queries in this database", nil }, + "tup_updated" : { COUNTER, "Number of rows updated by queries in this database", nil }, + "tup_deleted" : { COUNTER, "Number of rows deleted by queries in this database", 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 }, + "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 }, + "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 }, + "deadlocks" : { COUNTER, "Number of deadlocks detected in this database", nil }, + "blk_read_time" : { COUNTER, "Time spent reading data file blocks by backends in this database, in milliseconds", nil }, + "blk_write_time" : { COUNTER, "Time spent writing data file blocks by backends in this database, in milliseconds", nil }, + "stats_reset" : { COUNTER, "Time at which these statistics were last reset", nil }, + }, + "pg_stat_database_conflicts" : map[string]ColumnMapping { + "datid" : { COUNTER, "OID of a database", nil }, + "datname" : { COUNTER, "Name of this database", nil }, + "confl_tablespace" : { COUNTER, "Number of queries in this database that have been canceled due to dropped tablespaces", nil }, + "confl_lock" : { COUNTER, "Number of queries in this database that have been canceled due to lock timeouts", nil }, + "confl_snapshot" : { COUNTER, "Number of queries in this database that have been canceled due to old snapshots", nil }, + "confl_bufferpin" : { COUNTER, "Number of queries in this database that have been canceled due to pinned buffers", nil }, + "confl_deadlock" : { COUNTER, "Number of queries in this database that have been canceled due to deadlocks", nil }, + }, +} + +// Turn the MetricMap column mapping into a prometheus descriptor mapping. +func makeDescMap(metricMaps map[string]map[string]ColumnMapping) map[string]MetricMapNamespace { + var metricMap = make(map[string]MetricMapNamespace) + + for namespace, mappings := range metricMaps { + thisMap := make(map[string]MetricMap) + + // Get the constant labels + var constLabels []string + for columnName, columnMapping := range mappings { + if columnMapping.usage == LABEL { + constLabels = append(constLabels, columnName) + } + } + + for columnName, columnMapping := range mappings { + switch columnMapping.usage { + case DISCARD, LABEL: + thisMap[columnName] = MetricMap{ + discard : true, + } + case COUNTER: + thisMap[columnName] = MetricMap{ + vtype : prometheus.CounterValue, + desc : prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.description, constLabels, nil), + } + case GAUGE: + thisMap[columnName] = MetricMap{ + vtype : prometheus.GaugeValue, + desc : prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.description, constLabels, nil), + } + case MAPPEDMETRIC: + thisMap[columnName] = MetricMap{ + vtype : prometheus.GaugeValue, + desc : prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), columnMapping.description, constLabels, nil), + mapping: columnMapping.mapping, + } + } + } + + metricMap[namespace] = MetricMapNamespace{ constLabels, thisMap } + } + + return metricMap +} + +// Exporter collects MySQL metrics. It implements prometheus.Collector. +type Exporter struct { + dsn string + duration, error prometheus.Gauge + totalScrapes prometheus.Counter + metricMap map[string]MetricMapNamespace +} + +// NewExporter returns a new MySQL exporter for the provided DSN. +func NewExporter(dsn string) *Exporter { + return &Exporter{ + dsn: dsn, + duration: prometheus.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: exporter, + Name: "last_scrape_duration_seconds", + Help: "Duration of the last scrape of metrics from PostgresSQL.", + }), + totalScrapes: prometheus.NewCounter(prometheus.CounterOpts{ + Namespace: namespace, + Subsystem: exporter, + Name: "scrapes_total", + Help: "Total number of times PostgresSQL was scraped for metrics.", + }), + error: prometheus.NewGauge(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: exporter, + Name: "last_scrape_error", + Help: "Whether the last scrape of metrics from PostgreSQL resulted in an error (1 for error, 0 for success).", + }), + metricMap : makeDescMap(metricMaps), + } +} + +// Describe implements prometheus.Collector. +func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { + // We cannot know in advance what metrics the exporter will generate + // from Postgres. So we use the poor man's describe method: Run a collect + // and send the descriptors of all the collected metrics. The problem + // here is that we need to connect to the Postgres DB. If it is currently + // unavailable, the descriptors will be incomplete. Since this is a + // stand-alone exporter and not used as a library within other code + // implementing additional metrics, the worst that can happen is that we + // don't detect inconsistent metrics created by this exporter + // itself. Also, a change in the monitored Postgres instance may change the + // exported metrics during the runtime of the exporter. + + metricCh := make(chan prometheus.Metric) + doneCh := make(chan struct{}) + + go func() { + for m := range metricCh { + ch <- m.Desc() + } + close(doneCh) + }() + + e.Collect(metricCh) + close(metricCh) + <-doneCh +} + +// Collect implements prometheus.Collector. +func (e *Exporter) Collect(ch chan<- prometheus.Metric) { + e.scrape(ch) + + ch <- e.duration + ch <- e.totalScrapes + ch <- e.error +} + +func newDesc(subsystem, name, help string) *prometheus.Desc { + return prometheus.NewDesc( + prometheus.BuildFQName(namespace, subsystem, name), + help, nil, nil, + ) +} + +func (e *Exporter) scrape(ch chan<- prometheus.Metric) { + defer func(begun time.Time) { + e.duration.Set(time.Since(begun).Seconds()) + }(time.Now()) + + e.error.Set(0) + e.totalScrapes.Inc() + + db, err := sql.Open("postgres", e.dsn) + if err != nil { + log.Println("Error opening connection to database:", err) + e.error.Set(1) + return + } + defer db.Close() + + for namespace, mapping := range e.metricMap { + func () { // Don't fail on a bad scrape of one metric + rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s;", namespace)) + if err != nil { + log.Println("Error running query on database: ", namespace, err) + e.error.Set(1) + return + } + defer rows.Close() + + var columnNames []string + columnNames, err = rows.Columns() + if err != nil { + log.Println("Error retrieving column list for: ", namespace, err) + e.error.Set(1) + return + } + + // 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([]sql.RawBytes, len(columnNames)) + var scanArgs = make([]interface{}, len(columnNames)) + for i := range columnData { + scanArgs[i] = &columnData[i] + } + + for rows.Next() { + err = rows.Scan(scanArgs...) + if err != nil { + log.Println("Error retrieving rows:", namespace, err) + e.error.Set(1) + return + } + + // Get the label values for this row + var labels = make([]string, len(mapping.labels)) + for i, n := range labels { + labels[i] = string(columnData[columnIdx[n]]) + } + + // 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 { + if metricMapping, ok := mapping.columnMappings[columnName]; ok { + // Is this a metricy metric? + if metricMapping.discard { + continue + } + + var value float64 + var nf sql.NullFloat64 + err = nf.Scan(columnData[idx]) + if err != nil { + e.error.Set(1) + log.Errorln("Unexpected error parsing column: ", namespace, columnName, err) + continue + } + value = nf.Float64 + + // Generate the metric + ch <- prometheus.MustNewConstMetric(metricMapping.desc, metricMapping.vtype, value, labels...) + } else { + // Unknown metric. Report as untyped if scan to float64 works, else note an error too. + desc := prometheus.NewDesc(fmt.Sprintf("%s_%s", namespace, columnName), fmt.Sprintf("Unknown metric from %s", namespace), nil, nil) + + // Its not an error to fail here, since the values are + // unexpected anyway. + var value float64 + var nf sql.NullFloat64 + err = nf.Scan(columnData[idx]) + if err != nil { + log.Warnln("Could not parse unknown column to float64: ", namespace, columnName, err) + } + value = nf.Float64 + + ch <- prometheus.MustNewConstMetric(desc, prometheus.UntypedValue, value, labels...) + } + } + + } + }() + } +} + +func main() { + flag.Parse() + + dsn := os.Getenv("DATA_SOURCE_NAME") + if len(dsn) == 0 { + log.Fatal("couldn't find environment variable DATA_SOURCE_NAME") + } + + exporter := NewExporter(dsn) + prometheus.MustRegister(exporter) + + http.Handle(*metricPath, prometheus.Handler()) + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Write(landingPage) + }) + + log.Infof("Starting Server: %s", *listenAddress) + log.Fatal(http.ListenAndServe(*listenAddress, nil)) +}