pax_global_header00006660000000000000000000000064134315225500014512gustar00rootroot0000000000000052 comment=af6943b1bc8da0b8c645f4fed63559bba24f114c prometheus-postfix-exporter-0.2.0/000077500000000000000000000000001343152255000172445ustar00rootroot00000000000000prometheus-postfix-exporter-0.2.0/.gitignore000066400000000000000000000001461343152255000212350ustar00rootroot00000000000000# Editor files *~ -.idea/ # Test binary, build with `go test -c` *.test # Binaries postfix_exporter prometheus-postfix-exporter-0.2.0/CHANGELOG.md000066400000000000000000000003251343152255000210550ustar00rootroot00000000000000## 0.1.2 / 2018-05-04 * [ENHANCEMENT] Build tag for systemd ## 0.1.1 / 2018-04-19 * [BUGFIX] Non-updating metrics from systemd-journal fix ## 0.1.0 / 2018-02-23 * [ENHANCEMENT] Initial release, add changelog prometheus-postfix-exporter-0.2.0/Dockerfile000066400000000000000000000006021343152255000212340ustar00rootroot00000000000000FROM golang:1.8 ADD . /go/src/github.com/kumina/postfix_exporter WORKDIR /go/src/github.com/kumina/postfix_exporter RUN apt-get update -qq && apt-get install -qqy \ build-essential \ libsystemd-dev RUN go get -v ./... RUN go build FROM debian:latest EXPOSE 9154 WORKDIR / COPY --from=0 /go/src/github.com/kumina/postfix_exporter/postfix_exporter . ENTRYPOINT ["/postfix_exporter"] prometheus-postfix-exporter-0.2.0/LICENSE000066400000000000000000000261351343152255000202600ustar00rootroot00000000000000 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. prometheus-postfix-exporter-0.2.0/README.md000066400000000000000000000026771343152255000205370ustar00rootroot00000000000000# Prometheus Postfix exporter This repository provides code for a Prometheus metrics exporter for [the Postfix mail server](http://www.postfix.org/). This exporter provides histogram metrics for the size and age of messages stored in the mail queue. It extracts these metrics from Postfix by connecting to a UNIX socket under `/var/spool`. In addition to that, it counts events by parsing Postfix's log entries, using regular expression matching. The log entries are retrieved from the systemd journal or from a log file. Please refer to this utility's `main()` function for a list of supported command line flags. ## Events from log file The log file is tailed when processed. Rotating the log files while the exporter is running is OK. The path to the log file is specified with the `--postfix.logfile_path` flag. ## Events from systemd Retrieval from the systemd journal is enabled with the `--systemd.enable` flag. This overrides the log file setting. It is possible to specify the unit (with `--systemd.unit`) or slice (with `--systemd.slice`). Additionally, it is possible to read the journal from a directory with the `--systemd.journal_path` flag. ## Build options Default the exporter is build with systemd journal functionality (but it is disabled at default). Because the systemd headers are required for building with systemd, there is an option to build the exporter without systemd. Use the build tag `nosystemd`. ``` go build -tags nosystemd ``` prometheus-postfix-exporter-0.2.0/build_static.sh000077500000000000000000000005261343152255000222540ustar00rootroot00000000000000#!/bin/sh docker run -i -v `pwd`:/postfix_exporter ubuntu:16.04 /bin/sh << 'EOF' set -ex # Install prerequisites for the build process. apt-get update -q apt-get install -yq git golang-go libsystemd-dev mkdir /go export GOPATH=/go cd /postfix_exporter go get -d ./... go build --ldflags '-extldflags "-static"' strip postfix_exporter EOF prometheus-postfix-exporter-0.2.0/nosystemd.go000066400000000000000000000006661343152255000216300ustar00rootroot00000000000000// +build nosystemd // This file contains stubs to support non-systemd use package main import( "io" "github.com/alecthomas/kingpin" ) type Journal struct { io.Closer Path string } func systemdFlags(enable *bool, unit, slice, path *string, app *kingpin.Application) {} func NewJournal(unit, slice, path string) (*Journal, error) { return nil, nil } func (e *PostfixExporter) CollectLogfileFromJournal() error { return nil } prometheus-postfix-exporter-0.2.0/postfix_exporter.go000066400000000000000000000620301343152255000232200ustar00rootroot00000000000000// Copyright 2017 Kumina, https://kumina.nl/ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "bufio" "bytes" "errors" "fmt" "github.com/alecthomas/kingpin" "io" "log" "net" "net/http" "os" "regexp" "strconv" "strings" "time" "github.com/hpcloud/tail" "github.com/prometheus/client_golang/prometheus" ) var ( postfixUpDesc = prometheus.NewDesc( prometheus.BuildFQName("postfix", "", "up"), "Whether scraping Postfix's metrics was successful.", []string{"path"}, nil) ) // PostfixExporter holds the state that should be preserved by the // Postfix Prometheus metrics exporter across scrapes. type PostfixExporter struct { showqPath string journal *Journal tailer *tail.Tail // Metrics that should persist after refreshes, based on logs. cleanupProcesses prometheus.Counter cleanupRejects prometheus.Counter lmtpDelays *prometheus.HistogramVec pipeDelays *prometheus.HistogramVec qmgrInsertsNrcpt prometheus.Histogram qmgrInsertsSize prometheus.Histogram qmgrRemoves prometheus.Counter smtpDelays *prometheus.HistogramVec smtpTLSConnects *prometheus.CounterVec smtpdConnects prometheus.Counter smtpdDisconnects prometheus.Counter smtpdFCrDNSErrors prometheus.Counter smtpdLostConnections *prometheus.CounterVec smtpdProcesses *prometheus.CounterVec smtpdRejects *prometheus.CounterVec smtpdSASLAuthenticationFailures prometheus.Counter smtpdTLSConnects *prometheus.CounterVec unsupportedLogEntries *prometheus.CounterVec } // CollectShowqFromReader parses the output of Postfix's 'showq' command // and turns it into metrics. // // The output format of this command depends on the version of Postfix // used. Postfix 2.x uses a textual format, identical to the output of // the 'mailq' command. Postfix 3.x uses a binary format, where entries // are terminated using null bytes. Auto-detect the format by scanning // for null bytes in the first 128 bytes of output. func CollectShowqFromReader(file io.Reader, ch chan<- prometheus.Metric) error { reader := bufio.NewReader(file) buf, err := reader.Peek(128) if err != nil && err != io.EOF { log.Printf("Could not read postfix output, %v", err) } if bytes.IndexByte(buf, 0) >= 0 { return CollectBinaryShowqFromReader(reader, ch) } return CollectTextualShowqFromReader(reader, ch) } // CollectTextualShowqFromReader parses Postfix's textual showq output. func CollectTextualShowqFromReader(file io.Reader, ch chan<- prometheus.Metric) error { scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) // Regular expression for matching postqueue's output. Example: // "A07A81514 5156 Tue Feb 14 13:13:54 MAILER-DAEMON" messageLine := regexp.MustCompile(`^[0-9A-F]+([\*!]?) +(\d+) (\w{3} \w{3} +\d+ +\d+:\d{2}:\d{2}) +`) // Histograms tracking the messages by size and age. sizeHistogram := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "postfix", Name: "showq_message_size_bytes", Help: "Size of messages in Postfix's message queue, in bytes", Buckets: []float64{1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9}, }, []string{"queue"}) ageHistogram := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "postfix", Name: "showq_message_age_seconds", Help: "Age of messages in Postfix's message queue, in seconds", Buckets: []float64{1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8}, }, []string{"queue"}) // Initialize all queue buckets to zero. for _, q := range []string{"active", "hold", "other"} { sizeHistogram.WithLabelValues(q) ageHistogram.WithLabelValues(q) } now := time.Now() location, err := time.LoadLocation("Local") if err != nil { log.Println(err) } for scanner.Scan() { matches := messageLine.FindStringSubmatch(scanner.Text()) if matches != nil { // Derive the name of the message queue. queue := "other" if matches[1] == "*" { queue = "active" } else if matches[1] == "!" { queue = "hold" } // Parse the message size. size, err := strconv.ParseFloat(matches[2], 64) if err != nil { return err } // Parse the message date. Unfortunately, the // output contains no year number. Assume it // applies to the last year for which the // message date doesn't exceed time.Now(). date, err := time.ParseInLocation("Mon Jan 2 15:04:05", matches[3], location) if err != nil { return err } date = date.AddDate(now.Year(), 0, 0) if date.After(now) { date = date.AddDate(-1, 0, 0) } sizeHistogram.WithLabelValues(queue).Observe(size) ageHistogram.WithLabelValues(queue).Observe(now.Sub(date).Seconds()) } } sizeHistogram.Collect(ch) ageHistogram.Collect(ch) return scanner.Err() } // ScanNullTerminatedEntries is a splitting function for bufio.Scanner // to split entries by null bytes. func ScanNullTerminatedEntries(data []byte, atEOF bool) (advance int, token []byte, err error) { if i := bytes.IndexByte(data, 0); i >= 0 { // Valid record found. return i + 1, data[0:i], nil } else if atEOF && len(data) != 0 { // Data at the end of the file without a null terminator. return 0, nil, errors.New("Expected null byte terminator") } else { // Request more data. return 0, nil, nil } } // CollectBinaryShowqFromReader parses Postfix's binary showq format. func CollectBinaryShowqFromReader(file io.Reader, ch chan<- prometheus.Metric) error { scanner := bufio.NewScanner(file) scanner.Split(ScanNullTerminatedEntries) // Histograms tracking the messages by size and age. sizeHistogram := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "postfix", Name: "showq_message_size_bytes", Help: "Size of messages in Postfix's message queue, in bytes", Buckets: []float64{1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9}, }, []string{"queue"}) ageHistogram := prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "postfix", Name: "showq_message_age_seconds", Help: "Age of messages in Postfix's message queue, in seconds", Buckets: []float64{1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8}, }, []string{"queue"}) // Initialize all queue buckets to zero. for _, q := range []string{"active", "deferred", "hold", "incoming", "maildrop"} { sizeHistogram.WithLabelValues(q) ageHistogram.WithLabelValues(q) } now := float64(time.Now().UnixNano()) / 1e9 queue := "unknown" for scanner.Scan() { // Parse a key/value entry. key := scanner.Text() if len(key) == 0 { // Empty key means a record separator. queue = "unknown" continue } if !scanner.Scan() { return fmt.Errorf("key %q does not have a value", key) } value := scanner.Text() if key == "queue_name" { // The name of the message queue. queue = value } else if key == "size" { // Message size in bytes. size, err := strconv.ParseFloat(value, 64) if err != nil { return err } sizeHistogram.WithLabelValues(queue).Observe(size) } else if key == "time" { // Message time as a UNIX timestamp. utime, err := strconv.ParseFloat(value, 64) if err != nil { return err } ageHistogram.WithLabelValues(queue).Observe(now - utime) } } sizeHistogram.Collect(ch) ageHistogram.Collect(ch) return scanner.Err() } // CollectShowqFromFile collects Postfix queue statistics from a file. //func CollectShowqFromFile(path string, ch chan<- prometheus.Metric) error { // fd, err := os.Open(path) // if err != nil { // return err // } // defer fd.Close() // return CollectShowqFromReader(fd, ch) //} // CollectShowqFromSocket collects Postfix queue statistics from a socket. func CollectShowqFromSocket(path string, ch chan<- prometheus.Metric) error { fd, err := net.Dial("unix", path) if err != nil { return err } defer fd.Close() return CollectShowqFromReader(fd, ch) } // Patterns for parsing log messages. var ( logLine = regexp.MustCompile(` ?postfix/(\w+)\[\d+\]: (.*)`) lmtpPipeSMTPLine = regexp.MustCompile(`, relay=(\S+), .*, delays=([0-9\.]+)/([0-9\.]+)/([0-9\.]+)/([0-9\.]+), `) qmgrInsertLine = regexp.MustCompile(`:.*, size=(\d+), nrcpt=(\d+) `) smtpTLSLine = regexp.MustCompile(`^(\S+) TLS connection established to \S+: (\S+) with cipher (\S+) \((\d+)/(\d+) bits\)$`) smtpdFCrDNSErrorsLine = regexp.MustCompile(`^warning: hostname \S+ does not resolve to address `) smtpdProcessesSASLLine = regexp.MustCompile(`: client=.*, sasl_username=(\S+)`) smtpdRejectsLine = regexp.MustCompile(`^NOQUEUE: reject: RCPT from \S+: ([0-9]+) `) smtpdLostConnectionLine = regexp.MustCompile(`^lost connection after (\w+) from `) smtpdSASLAuthenticationFailuresLine = regexp.MustCompile(`^warning: \S+: SASL \S+ authentication failed: `) smtpdTLSLine = regexp.MustCompile(`^(\S+) TLS connection established from \S+: (\S+) with cipher (\S+) \((\d+)/(\d+) bits\)$`) ) // CollectFromLogline collects metrict from a Postfix log line. func (e *PostfixExporter) CollectFromLogline(line string) { // Strip off timestamp, hostname, etc. if logMatches := logLine.FindStringSubmatch(line); logMatches != nil { // Group patterns to check by Postfix service. if logMatches[1] == "cleanup" { if strings.Contains(logMatches[2], ": message-id=<") { e.cleanupProcesses.Inc() } else if strings.Contains(logMatches[2], ": reject: ") { e.cleanupRejects.Inc() } else { e.unsupportedLogEntries.WithLabelValues(logMatches[1]).Inc() } } else if logMatches[1] == "lmtp" { if lmtpMatches := lmtpPipeSMTPLine.FindStringSubmatch(logMatches[2]); lmtpMatches != nil { pdelay, err := strconv.ParseFloat(lmtpMatches[2], 64) if err != nil { log.Printf("Couldn't convert LMTP pdelay: %v", err) } e.lmtpDelays.WithLabelValues("before_queue_manager").Observe(pdelay) adelay, err := strconv.ParseFloat(lmtpMatches[3], 64) if err != nil { log.Printf("Couldn't convert LMTP adelay: %v", err) } e.lmtpDelays.WithLabelValues("queue_manager").Observe(adelay) sdelay, err := strconv.ParseFloat(lmtpMatches[4], 64) if err != nil { log.Printf("Couldn't convert LMTP adelay: %v", err) } e.lmtpDelays.WithLabelValues("connection_setup").Observe(sdelay) xdelay, err := strconv.ParseFloat(lmtpMatches[5], 64) if err != nil { log.Printf("Couldn't convert LMTP xdelay: %v", err) } e.lmtpDelays.WithLabelValues("transmission").Observe(xdelay) } else { e.unsupportedLogEntries.WithLabelValues(logMatches[1]).Inc() } } else if logMatches[1] == "pipe" { if pipeMatches := lmtpPipeSMTPLine.FindStringSubmatch(logMatches[2]); pipeMatches != nil { pdelay, err := strconv.ParseFloat(pipeMatches[2], 64) if err != nil { log.Printf("Couldn't convert PIPE pdelay: %v", err) } e.pipeDelays.WithLabelValues(pipeMatches[1], "before_queue_manager").Observe(pdelay) adelay, err := strconv.ParseFloat(pipeMatches[3], 64) if err != nil { log.Printf("Couldn't convert PIPE adelay: %v", err) } e.pipeDelays.WithLabelValues(pipeMatches[1], "queue_manager").Observe(adelay) sdelay, err := strconv.ParseFloat(pipeMatches[4], 64) if err != nil { log.Printf("Couldn't convert PIPE sdelay: %v", err) } e.pipeDelays.WithLabelValues(pipeMatches[1], "connection_setup").Observe(sdelay) xdelay, err := strconv.ParseFloat(pipeMatches[5], 64) if err != nil { log.Printf("Couldn't convert PIPE xdelay: %v", err) } e.pipeDelays.WithLabelValues(pipeMatches[1], "transmission").Observe(xdelay) } else { e.unsupportedLogEntries.WithLabelValues(logMatches[1]).Inc() } } else if logMatches[1] == "qmgr" { if qmgrInsertMatches := qmgrInsertLine.FindStringSubmatch(logMatches[2]); qmgrInsertMatches != nil { size, err := strconv.ParseFloat(qmgrInsertMatches[1], 64) if err != nil { log.Printf("Couldn't convert QMGR size: %v", err) } e.qmgrInsertsSize.Observe(size) nrcpt, err := strconv.ParseFloat(qmgrInsertMatches[2], 64) if err != nil { log.Printf("Couldn't convert QMGR nrcpt: %v", err) } e.qmgrInsertsNrcpt.Observe(nrcpt) } else if strings.HasSuffix(logMatches[2], ": removed") { e.qmgrRemoves.Inc() } else { e.unsupportedLogEntries.WithLabelValues(logMatches[1]).Inc() } } else if logMatches[1] == "smtp" { if smtpMatches := lmtpPipeSMTPLine.FindStringSubmatch(logMatches[2]); smtpMatches != nil { pdelay, err := strconv.ParseFloat(smtpMatches[2], 64) if err != nil { log.Printf("Couldn't convert SMTP pdelay: %v", err) } e.smtpDelays.WithLabelValues("before_queue_manager").Observe(pdelay) adelay, err := strconv.ParseFloat(smtpMatches[3], 64) if err != nil { log.Printf("Couldn't convert SMTP adelay: %v", err) } e.smtpDelays.WithLabelValues("queue_manager").Observe(adelay) sdelay, err := strconv.ParseFloat(smtpMatches[4], 64) if err != nil { log.Printf("Couldn't convert SMTP sdelay: %v", err) } e.smtpDelays.WithLabelValues("connection_setup").Observe(sdelay) xdelay, err := strconv.ParseFloat(smtpMatches[5], 64) if err != nil { log.Printf("Couldn't convert SMTP xdelay: %v", err) } e.smtpDelays.WithLabelValues("transmission").Observe(xdelay) } else if smtpTLSMatches := smtpTLSLine.FindStringSubmatch(logMatches[2]); smtpTLSMatches != nil { e.smtpTLSConnects.WithLabelValues(smtpTLSMatches[1:]...).Inc() } else { e.unsupportedLogEntries.WithLabelValues(logMatches[1]).Inc() } } else if logMatches[1] == "smtpd" { if strings.HasPrefix(logMatches[2], "connect from ") { e.smtpdConnects.Inc() } else if strings.HasPrefix(logMatches[2], "disconnect from ") { e.smtpdDisconnects.Inc() } else if smtpdFCrDNSErrorsLine.MatchString(logMatches[2]) { e.smtpdFCrDNSErrors.Inc() } else if smtpdLostConnectionMatches := smtpdLostConnectionLine.FindStringSubmatch(logMatches[2]); smtpdLostConnectionMatches != nil { e.smtpdLostConnections.WithLabelValues(smtpdLostConnectionMatches[1]).Inc() } else if smtpdProcessesSASLMatches := smtpdProcessesSASLLine.FindStringSubmatch(logMatches[2]); smtpdProcessesSASLMatches != nil { e.smtpdProcesses.WithLabelValues(smtpdProcessesSASLMatches[1]).Inc() } else if strings.Contains(logMatches[2], ": client=") { e.smtpdProcesses.WithLabelValues("").Inc() } else if smtpdRejectsMatches := smtpdRejectsLine.FindStringSubmatch(logMatches[2]); smtpdRejectsMatches != nil { e.smtpdRejects.WithLabelValues(smtpdRejectsMatches[1]).Inc() } else if smtpdSASLAuthenticationFailuresLine.MatchString(logMatches[2]) { e.smtpdSASLAuthenticationFailures.Inc() } else if smtpdTLSMatches := smtpdTLSLine.FindStringSubmatch(logMatches[2]); smtpdTLSMatches != nil { e.smtpdTLSConnects.WithLabelValues(smtpdTLSMatches[1:]...).Inc() } else { e.unsupportedLogEntries.WithLabelValues(logMatches[1]).Inc() } } else { // Unknown Postfix service. e.unsupportedLogEntries.WithLabelValues(logMatches[1]).Inc() } } else { // Unknown log entry format. e.unsupportedLogEntries.WithLabelValues("").Inc() } } // CollectLogfileFromFile tails a Postfix log file and collects entries from it. func (e *PostfixExporter) CollectLogfileFromFile() error { for { select { case line := <-e.tailer.Lines: e.CollectFromLogline(line.Text) default: return nil } } } // NewPostfixExporter creates a new Postfix exporter instance. func NewPostfixExporter(showqPath string, logfilePath string, journal *Journal) (*PostfixExporter, error) { var tailer *tail.Tail if logfilePath != "" { var err error tailer, err = tail.TailFile(logfilePath, tail.Config{ ReOpen: true, // reopen the file if it's rotated MustExist: true, // fail immediately if the file is missing or has incorrect permissions Follow: true, // run in follow mode }) if err != nil { return nil, err } } return &PostfixExporter{ showqPath: showqPath, tailer: tailer, journal: journal, cleanupProcesses: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "postfix", Name: "cleanup_messages_processed_total", Help: "Total number of messages processed by cleanup.", }), cleanupRejects: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "postfix", Name: "cleanup_messages_rejected_total", Help: "Total number of messages rejected by cleanup.", }), lmtpDelays: prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "postfix", Name: "lmtp_delivery_delay_seconds", Help: "LMTP message processing time in seconds.", Buckets: []float64{1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3}, }, []string{"stage"}), pipeDelays: prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "postfix", Name: "pipe_delivery_delay_seconds", Help: "Pipe message processing time in seconds.", Buckets: []float64{1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3}, }, []string{"relay", "stage"}), qmgrInsertsNrcpt: prometheus.NewHistogram(prometheus.HistogramOpts{ Namespace: "postfix", Name: "qmgr_messages_inserted_receipients", Help: "Number of receipients per message inserted into the mail queues.", Buckets: []float64{1, 2, 4, 8, 16, 32, 64, 128}, }), qmgrInsertsSize: prometheus.NewHistogram(prometheus.HistogramOpts{ Namespace: "postfix", Name: "qmgr_messages_inserted_size_bytes", Help: "Size of messages inserted into the mail queues in bytes.", Buckets: []float64{1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9}, }), qmgrRemoves: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "postfix", Name: "qmgr_messages_removed_total", Help: "Total number of messages removed from mail queues.", }), smtpDelays: prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "postfix", Name: "smtp_delivery_delay_seconds", Help: "SMTP message processing time in seconds.", Buckets: []float64{1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3}, }, []string{"stage"}), smtpTLSConnects: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: "postfix", Name: "smtp_tls_connections_total", Help: "Total number of outgoing TLS connections.", }, []string{"trust", "protocol", "cipher", "secret_bits", "algorithm_bits"}), smtpdConnects: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "postfix", Name: "smtpd_connects_total", Help: "Total number of incoming connections.", }), smtpdDisconnects: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "postfix", Name: "smtpd_disconnects_total", Help: "Total number of incoming disconnections.", }), smtpdFCrDNSErrors: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "postfix", Name: "smtpd_forward_confirmed_reverse_dns_errors_total", Help: "Total number of connections for which forward-confirmed DNS cannot be resolved.", }), smtpdLostConnections: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: "postfix", Name: "smtpd_connections_lost_total", Help: "Total number of connections lost.", }, []string{"after_stage"}), smtpdProcesses: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: "postfix", Name: "smtpd_messages_processed_total", Help: "Total number of messages processed.", }, []string{"sasl_username"}), smtpdRejects: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: "postfix", Name: "smtpd_messages_rejected_total", Help: "Total number of NOQUEUE rejects.", }, []string{"code"}), smtpdSASLAuthenticationFailures: prometheus.NewCounter(prometheus.CounterOpts{ Namespace: "postfix", Name: "smtpd_sasl_authentication_failures_total", Help: "Total number of SASL authentication failures.", }), smtpdTLSConnects: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: "postfix", Name: "smtpd_tls_connections_total", Help: "Total number of incoming TLS connections.", }, []string{"trust", "protocol", "cipher", "secret_bits", "algorithm_bits"}), unsupportedLogEntries: prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: "postfix", Name: "unsupported_log_entries_total", Help: "Log entries that could not be processed.", }, []string{"service"}), }, nil } // Describe the Prometheus metrics that are going to be exported. func (e *PostfixExporter) Describe(ch chan<- *prometheus.Desc) { ch <- postfixUpDesc ch <- e.cleanupProcesses.Desc() ch <- e.cleanupRejects.Desc() e.lmtpDelays.Describe(ch) e.pipeDelays.Describe(ch) ch <- e.qmgrInsertsNrcpt.Desc() ch <- e.qmgrInsertsSize.Desc() ch <- e.qmgrRemoves.Desc() e.smtpDelays.Describe(ch) e.smtpTLSConnects.Describe(ch) ch <- e.smtpdConnects.Desc() ch <- e.smtpdDisconnects.Desc() ch <- e.smtpdFCrDNSErrors.Desc() e.smtpdLostConnections.Describe(ch) e.smtpdProcesses.Describe(ch) e.smtpdRejects.Describe(ch) ch <- e.smtpdSASLAuthenticationFailures.Desc() e.smtpdTLSConnects.Describe(ch) e.unsupportedLogEntries.Describe(ch) } // Collect metrics from Postfix's showq socket and its log file. func (e *PostfixExporter) Collect(ch chan<- prometheus.Metric) { err := CollectShowqFromSocket(e.showqPath, ch) if err == nil { ch <- prometheus.MustNewConstMetric( postfixUpDesc, prometheus.GaugeValue, 1.0, e.showqPath) } else { log.Printf("Failed to scrape showq socket: %s", err) ch <- prometheus.MustNewConstMetric( postfixUpDesc, prometheus.GaugeValue, 0.0, e.showqPath) } var src string if e.journal != nil { err = e.CollectLogfileFromJournal() src = e.journal.Path } else { err = e.CollectLogfileFromFile() src = e.tailer.Filename } if err == nil { ch <- prometheus.MustNewConstMetric( postfixUpDesc, prometheus.GaugeValue, 1.0, src) } else { log.Printf("Failed to scrape log: %s", err) ch <- prometheus.MustNewConstMetric( postfixUpDesc, prometheus.GaugeValue, 0.0, src) } ch <- e.cleanupProcesses ch <- e.cleanupRejects e.lmtpDelays.Collect(ch) e.pipeDelays.Collect(ch) ch <- e.qmgrInsertsNrcpt ch <- e.qmgrInsertsSize ch <- e.qmgrRemoves e.smtpDelays.Collect(ch) e.smtpTLSConnects.Collect(ch) ch <- e.smtpdConnects ch <- e.smtpdDisconnects ch <- e.smtpdFCrDNSErrors e.smtpdLostConnections.Collect(ch) e.smtpdProcesses.Collect(ch) e.smtpdRejects.Collect(ch) ch <- e.smtpdSASLAuthenticationFailures e.smtpdTLSConnects.Collect(ch) e.unsupportedLogEntries.Collect(ch) } func main() { var ( app = kingpin.New("postfix_exporter", "Prometheus metrics exporter for postfix") listenAddress = app.Flag("web.listen-address", "Address to listen on for web interface and telemetry.").Default(":9154").String() metricsPath = app.Flag("web.telemetry-path", "Path under which to expose metrics.").Default("/metrics").String() postfixShowqPath = app.Flag("postfix.showq_path", "Path at which Postfix places its showq socket.").Default("/var/spool/postfix/public/showq").String() postfixLogfilePath = app.Flag("postfix.logfile_path", "Path where Postfix writes log entries. This file will be truncated by this exporter.").Default("/var/log/postfix_exporter_input.log").String() systemdEnable bool systemdUnit, systemdSlice, systemdJournalPath string ) systemdFlags(&systemdEnable, &systemdUnit, &systemdSlice, &systemdJournalPath, app) kingpin.MustParse(app.Parse(os.Args[1:])) var journal *Journal if systemdEnable { var err error journal, err = NewJournal(systemdUnit, systemdSlice, systemdJournalPath) if err != nil { log.Fatalf("Error opening systemd journal: %s", err) } defer journal.Close() } exporter, err := NewPostfixExporter( *postfixShowqPath, *postfixLogfilePath, journal, ) if err != nil { log.Fatalf("Failed to create PostfixExporter: %s", err) } prometheus.MustRegister(exporter) http.Handle(*metricsPath, prometheus.Handler()) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, err = w.Write([]byte(` Postfix Exporter

Postfix Exporter

Metrics

`)) if err != nil { panic(err) } }) log.Print("Listening on ", *listenAddress) log.Fatal(http.ListenAndServe(*listenAddress, nil)) } prometheus-postfix-exporter-0.2.0/systemd.go000066400000000000000000000050511343152255000212640ustar00rootroot00000000000000// +build !nosystemd package main import ( "fmt" "log" "sync" "time" "github.com/alecthomas/kingpin" "github.com/coreos/go-systemd/sdjournal" ) // Journal represents a lockable systemd journal. type Journal struct { *sdjournal.Journal sync.Mutex Path string } // NewJournal returns a Journal for reading journal entries. func NewJournal(unit, slice, path string) (j *Journal, err error) { j = new(Journal) if path != "" { j.Journal, err = sdjournal.NewJournalFromDir(path) j.Path = path } else { j.Journal, err = sdjournal.NewJournal() j.Path = "journald" } if err != nil { return } if slice != "" { err = j.AddMatch("_SYSTEMD_SLICE=" + slice) if err != nil { return } } else if unit != "" { err = j.AddMatch("_SYSTEMD_UNIT=" + unit) if err != nil { return } } // Start at end of journal err = j.SeekRealtimeUsec(uint64(time.Now().UnixNano() / 1000)) if err != nil { log.Printf("%v", err) } return } // NextMessage reads the next message from the journal. func (j *Journal) NextMessage() (s string, c uint64, err error) { var e *sdjournal.JournalEntry // Read to next c, err = j.Next() if err != nil { return } // Return when on the end of journal if c == 0 { return } // Get entry e, err = j.GetEntry() if err != nil { return } ts := time.Unix(0, int64(e.RealtimeTimestamp)*int64(time.Microsecond)) // Format entry s = fmt.Sprintf( "%s %s %s[%s]: %s", ts.Format(time.Stamp), e.Fields["_HOSTNAME"], e.Fields["SYSLOG_IDENTIFIER"], e.Fields["_PID"], e.Fields["MESSAGE"], ) return } // systemdFlags sets the flags for use with systemd func systemdFlags(enable *bool, unit, slice, path *string, app *kingpin.Application) { app.Flag("systemd.enable", "Read from the systemd journal instead of log").Default("false").BoolVar(enable) app.Flag("systemd.unit", "Name of the Postfix systemd unit.").Default("postfix.service").StringVar(unit) app.Flag("systemd.slice", "Name of the Postfix systemd slice. Overrides the systemd unit.").Default("").StringVar(slice) app.Flag("systemd.journal_path", "Path to the systemd journal").Default("").StringVar(path) } // CollectLogfileFromJournal Collects entries from the systemd journal. func (e *PostfixExporter) CollectLogfileFromJournal() error { e.journal.Lock() defer e.journal.Unlock() r := e.journal.Wait(time.Duration(1) * time.Second) if r < 0 { log.Print("error while waiting for journal!") } for { m, c, err := e.journal.NextMessage() if err != nil { return err } if c == 0 { break } e.CollectFromLogline(m) } return nil }