File: postfix_exporter.go

package info (click to toggle)
prometheus-postfix-exporter 0.12.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 348 kB
  • sloc: sh: 78; makefile: 52
file content (733 lines) | stat: -rw-r--r-- 26,205 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
// 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 (
	"context"
	"errors"
	"log"
	"regexp"
	"slices"
	"strconv"
	"strings"
	"sync"

	"github.com/hsn723/postfix_exporter/showq"
	"github.com/prometheus/client_golang/prometheus"
)

var (
	postfixUpDesc = prometheus.NewDesc(
		prometheus.BuildFQName("postfix", "", "up"),
		"Whether scraping Postfix's metrics was successful.",
		[]string{"path"}, nil)

	SystemdNoMoreEntries = errors.New("No more journal entries")
)

// PostfixExporter holds the state that should be preserved by the
// Postfix Prometheus metrics exporter across scrapes.
type PostfixExporter struct {
	qmgrInsertsSize   prometheus.Histogram
	virtualDelivered  prometheus.Counter
	bounceNonDelivery prometheus.Counter

	smtpConnectionTimedOut prometheus.Counter
	// same as smtpProcesses{status=deferred}, kept for compatibility
	smtpStatusDeferred prometheus.Counter
	// should be the same as smtpProcesses{status=deferred}, kept for compatibility, but this doesn't work !
	smtpDeferreds prometheus.Counter

	smtpdSASLAuthenticationFailures prometheus.Counter
	smtpdFCrDNSErrors               prometheus.Counter
	smtpdDisconnects                prometheus.Counter
	smtpdConnects                   prometheus.Counter

	cleanupProcesses   prometheus.Counter
	cleanupRejects     prometheus.Counter
	cleanupNotAccepted prometheus.Counter

	qmgrExpires      prometheus.Counter
	qmgrRemoves      prometheus.Counter
	qmgrInsertsNrcpt prometheus.Histogram

	logSrc LogSource

	smtpdLostConnections *prometheus.CounterVec
	smtpDeferredDSN      *prometheus.CounterVec
	smtpdProcesses       *prometheus.CounterVec
	smtpdRejects         *prometheus.CounterVec
	smtpdTLSConnects     *prometheus.CounterVec

	lmtpDelays *prometheus.HistogramVec
	pipeDelays *prometheus.HistogramVec

	smtpDelays      *prometheus.HistogramVec
	smtpTLSConnects *prometheus.CounterVec
	smtpBouncedDSN  *prometheus.CounterVec
	smtpProcesses   *prometheus.CounterVec

	opendkimSignatureAdded *prometheus.CounterVec

	unsupportedLogEntries *prometheus.CounterVec

	showq     *showq.Showq
	showqPath string

	bounceLabels  []string
	cleanupLabels []string
	smtpLabels    []string
	smtpdLabels   []string
	virtualLabels []string
	qmgrLabels    []string
	pipeLabels    []string
	lmtpLabels    []string

	once sync.Once

	logUnsupportedLines bool
}

// ServiceLabel is a function to apply user-defined service labels to PostfixExporter.
type ServiceLabel func(*PostfixExporter)

// A LogSource is an interface to read log lines.
type LogSource interface {
	// Path returns a representation of the log location.
	Path() string

	// Read returns the next log line. Returns `io.EOF` at the end of
	// the log.
	Read(context.Context) (string, error)
}

// Patterns for parsing log messages.
var (
	logLine                             = regexp.MustCompile(` ?(postfix|opendkim)(/([\w_\.+/-]+))?\[\d+\]: ((?:(warning|error|fatal|panic): )?.*)`)
	lmtpPipeSMTPLine                    = regexp.MustCompile(`, relay=(\S+), .*, delays=([0-9\.]+)/([0-9\.]+)/([0-9\.]+)/([0-9\.]+), `)
	qmgrInsertLine                      = regexp.MustCompile(`:.*, size=(\d+), nrcpt=(\d+) `)
	qmgrExpiredLine                     = regexp.MustCompile(`:.*, status=(expired|force-expired), returned to sender`)
	smtpStatusLine                      = regexp.MustCompile(`, status=(\w+) `)
	smtpDSNLine                         = regexp.MustCompile(`, dsn=(\d\.\d+\.\d+)`)
	smtpTLSLine                         = regexp.MustCompile(`^(\S+) TLS connection established to \S+: (\S+) with cipher (\S+) \((\d+)/(\d+) bits\)`)
	smtpConnectionTimedOut              = regexp.MustCompile(`^connect\s+to\s+(.*)\[(.*)\]:(\d+):\s+(Connection timed out)$`)
	smtpdFCrDNSErrorsLine               = regexp.MustCompile(`^warning: hostname \S+ does not resolve to address `)
	smtpdProcessesSASLLine              = regexp.MustCompile(`: client=.*, sasl_method=(\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\)`)
	opendkimSignatureAdded              = regexp.MustCompile(`^[\w\d]+: DKIM-Signature field added \(s=(\w+), d=(.*)\)$`)
	bounceNonDeliveryLine               = regexp.MustCompile(`: sender non-delivery notification: `)
)

func (e *PostfixExporter) collectFromPostfixLogLine(line, subprocess, level, remainder string) {
	switch {
	case slices.Contains(e.cleanupLabels, subprocess):
		e.collectCleanupLog(line, remainder, level)
	case slices.Contains(e.lmtpLabels, subprocess):
		e.collectLMTPLog(line, remainder, level)
	case slices.Contains(e.pipeLabels, subprocess):
		e.collectPipeLog(line, remainder, level)
	case slices.Contains(e.qmgrLabels, subprocess):
		e.collectQmgrLog(line, remainder, level)
	case slices.Contains(e.smtpLabels, subprocess):
		e.collectSMTPLog(line, remainder, level)
	case slices.Contains(e.smtpdLabels, subprocess):
		e.collectSMTPdLog(line, remainder, level)
	case slices.Contains(e.bounceLabels, subprocess):
		e.collectBounceLog(line, remainder, level)
	case slices.Contains(e.virtualLabels, subprocess):
		e.collectVirtualLog(line, remainder, level)
	default:
		e.addToUnsupportedLine(line, subprocess, level)
	}
}

func (e *PostfixExporter) collectCleanupLog(line, remainder, level string) {
	switch {
	case strings.Contains(remainder, ": message-id=<"):
		e.cleanupProcesses.Inc()
	case strings.Contains(remainder, ": reject: "):
		e.cleanupRejects.Inc()
	default:
		e.addToUnsupportedLine(line, "cleanup", level)
	}
}

func (e *PostfixExporter) collectLMTPLog(line, remainder, level string) {
	lmtpMatches := lmtpPipeSMTPLine.FindStringSubmatch(remainder)
	if lmtpMatches == nil {
		e.addToUnsupportedLine(line, "lmtp", level)
		return
	}
	addToHistogramVec(e.lmtpDelays, lmtpMatches[2], "LMTP pdelay", "before_queue_manager")
	addToHistogramVec(e.lmtpDelays, lmtpMatches[3], "LMTP adelay", "queue_manager")
	addToHistogramVec(e.lmtpDelays, lmtpMatches[4], "LMTP sdelay", "connection_setup")
	addToHistogramVec(e.lmtpDelays, lmtpMatches[5], "LMTP xdelay", "transmission")
}

func (e *PostfixExporter) collectPipeLog(line, remainder, level string) {
	pipeMatches := lmtpPipeSMTPLine.FindStringSubmatch(remainder)
	if pipeMatches == nil {
		e.addToUnsupportedLine(line, "pipe", level)
		return
	}
	addToHistogramVec(e.pipeDelays, pipeMatches[2], "PIPE pdelay", pipeMatches[1], "before_queue_manager")
	addToHistogramVec(e.pipeDelays, pipeMatches[3], "PIPE adelay", pipeMatches[1], "queue_manager")
	addToHistogramVec(e.pipeDelays, pipeMatches[4], "PIPE sdelay", pipeMatches[1], "connection_setup")
	addToHistogramVec(e.pipeDelays, pipeMatches[5], "PIPE xdelay", pipeMatches[1], "transmission")
}

func (e *PostfixExporter) collectQmgrLog(line, remainder, level string) {
	qmgrInsertMatches := qmgrInsertLine.FindStringSubmatch(remainder)
	switch {
	case qmgrInsertMatches != nil:
		addToHistogram(e.qmgrInsertsSize, qmgrInsertMatches[1], "QMGR size")
		addToHistogram(e.qmgrInsertsNrcpt, qmgrInsertMatches[2], "QMGR nrcpt")
	case strings.HasSuffix(remainder, ": removed"):
		e.qmgrRemoves.Inc()
	case qmgrExpiredLine.MatchString(remainder):
		e.qmgrExpires.Inc()
	default:
		e.addToUnsupportedLine(line, "qmgr", level)
	}
}

func (e *PostfixExporter) collectSMTPLog(line, remainder, level string) {
	if smtpMatches := lmtpPipeSMTPLine.FindStringSubmatch(remainder); smtpMatches != nil {
		addToHistogramVec(e.smtpDelays, smtpMatches[2], "before_queue_manager", "")
		addToHistogramVec(e.smtpDelays, smtpMatches[3], "queue_manager", "")
		addToHistogramVec(e.smtpDelays, smtpMatches[4], "connection_setup", "")
		addToHistogramVec(e.smtpDelays, smtpMatches[5], "transmission", "")
		e.collectSMTPStatusLog(remainder)
	} else if smtpTLSMatches := smtpTLSLine.FindStringSubmatch(remainder); smtpTLSMatches != nil {
		e.smtpTLSConnects.WithLabelValues(smtpTLSMatches[1:]...).Inc()
	} else if connectionTimedOutMatches := smtpConnectionTimedOut.FindStringSubmatch(remainder); connectionTimedOutMatches != nil {
		e.smtpConnectionTimedOut.Inc()
	} else {
		e.addToUnsupportedLine(line, "smtp", level)
	}
}

func (e *PostfixExporter) collectSMTPStatusLog(remainder string) {
	smtpStatusMatches := smtpStatusLine.FindStringSubmatch(remainder)
	if smtpStatusMatches == nil {
		return
	}
	e.smtpProcesses.WithLabelValues(smtpStatusMatches[1]).Inc()
	dsnMatches := smtpDSNLine.FindStringSubmatch(remainder)
	switch smtpStatusMatches[1] {
	case "deferred":
		e.smtpStatusDeferred.Inc()
		if dsnMatches != nil {
			e.smtpDeferredDSN.WithLabelValues(dsnMatches[1]).Inc()
		}
	case "bounced":
		if dsnMatches != nil {
			e.smtpBouncedDSN.WithLabelValues(dsnMatches[1]).Inc()
		}
	}
}

func (e *PostfixExporter) collectSMTPdLog(line, remainder, level string) {
	if strings.HasPrefix(remainder, "connect from ") {
		e.smtpdConnects.Inc()
	} else if strings.HasPrefix(remainder, "disconnect from ") {
		e.smtpdDisconnects.Inc()
	} else if smtpdFCrDNSErrorsLine.MatchString(remainder) {
		e.smtpdFCrDNSErrors.Inc()
	} else if smtpdLostConnectionMatches := smtpdLostConnectionLine.FindStringSubmatch(remainder); smtpdLostConnectionMatches != nil {
		e.smtpdLostConnections.WithLabelValues(smtpdLostConnectionMatches[1]).Inc()
	} else if smtpdProcessesSASLMatches := smtpdProcessesSASLLine.FindStringSubmatch(remainder); smtpdProcessesSASLMatches != nil {
		e.smtpdProcesses.WithLabelValues(strings.ReplaceAll(smtpdProcessesSASLMatches[1], ",", "")).Inc()
	} else if strings.Contains(remainder, ": client=") {
		e.smtpdProcesses.WithLabelValues("NONE").Inc()
	} else if smtpdRejectsMatches := smtpdRejectsLine.FindStringSubmatch(remainder); smtpdRejectsMatches != nil {
		e.smtpdRejects.WithLabelValues(smtpdRejectsMatches[1]).Inc()
	} else if smtpdSASLAuthenticationFailuresLine.MatchString(remainder) {
		e.smtpdSASLAuthenticationFailures.Inc()
	} else if smtpdTLSMatches := smtpdTLSLine.FindStringSubmatch(remainder); smtpdTLSMatches != nil {
		e.smtpdTLSConnects.WithLabelValues(smtpdTLSMatches[1:]...).Inc()
	} else {
		e.addToUnsupportedLine(line, "smtpd", level)
	}
}

func (e *PostfixExporter) collectBounceLog(line, remainder, level string) {
	bounceMatches := bounceNonDeliveryLine.FindStringSubmatch(remainder)
	if bounceMatches == nil {
		e.addToUnsupportedLine(line, "postfix", level)
		return
	}
	e.bounceNonDelivery.Inc()
}

func (e *PostfixExporter) collectVirtualLog(line, remainder, level string) {
	if strings.HasSuffix(remainder, ", status=sent (delivered to maildir)") {
		e.virtualDelivered.Inc()
	} else {
		e.addToUnsupportedLine(line, "postfix", level)
	}
}

// CollectFromLogline collects metrict from a Postfix log line.
func (e *PostfixExporter) CollectFromLogLine(line string) {
	if line == "" {
		return
	}
	// Strip off timestamp, hostname, etc.
	logMatches := logLine.FindStringSubmatch(line)

	if logMatches == nil {
		// Unknown log entry format.
		e.addToUnsupportedLine(line, "", "")
		return
	}
	process := logMatches[1]
	level := logMatches[5]
	remainder := logMatches[4]
	switch process {
	case "postfix":
		subprocess := logMatches[3]
		e.collectFromPostfixLogLine(line, subprocess, level, remainder)
	case "opendkim":
		if opendkimMatches := opendkimSignatureAdded.FindStringSubmatch(remainder); opendkimMatches != nil {
			e.opendkimSignatureAdded.WithLabelValues(opendkimMatches[1], opendkimMatches[2]).Inc()
		} else {
			e.addToUnsupportedLine(line, process, level)
		}
	default:
		// Unknown log entry format.
		e.addToUnsupportedLine(line, process, level)
	}
}

func (e *PostfixExporter) addToUnsupportedLine(line string, subprocess string, level string) {
	if e.logUnsupportedLines {
		log.Printf("Unsupported Line: %v", line)
	}
	e.unsupportedLogEntries.WithLabelValues(subprocess, level).Inc()
}

func addToHistogram(h prometheus.Histogram, value, fieldName string) {
	float, err := strconv.ParseFloat(value, 64)
	if err != nil {
		log.Printf("Couldn't convert value '%s' for %v: %v", value, fieldName, err)
	}
	h.Observe(float)
}
func addToHistogramVec(h *prometheus.HistogramVec, value, fieldName string, labels ...string) {
	float, err := strconv.ParseFloat(value, 64)
	if err != nil {
		log.Printf("Couldn't convert value '%s' for %v: %v", value, fieldName, err)
	}
	h.WithLabelValues(labels...).Observe(float)
}

var (
	defaultCleanupLabels = []string{"cleanup"}
	defaultLmtpLabels    = []string{"lmtp"}
	defaultPipeLabels    = []string{"pipe"}
	defaultQmgrLabels    = []string{"qmgr"}
	defaultSmtpLabels    = []string{"smtp"}
	defaultSmtpdLabels   = []string{"smtpd"}
	defaultBounceLabels  = []string{"bounce"}
	defaultVirtualLabels = []string{"virtual"}
)

// WithCleanupLabels is a function to apply user-defined service labels to PostfixExporter.
func WithCleanupLabels(labels []string) ServiceLabel {
	return func(e *PostfixExporter) {
		e.cleanupLabels = labels
	}
}

// WithCleanupLabels is a function to apply user-defined service labels to PostfixExporter.
func WithLmtpLabels(labels []string) ServiceLabel {
	return func(e *PostfixExporter) {
		e.lmtpLabels = labels
	}
}

// WithCleanupLabels is a function to apply user-defined service labels to PostfixExporter.
func WithPipeLabels(labels []string) ServiceLabel {
	return func(e *PostfixExporter) {
		e.pipeLabels = labels
	}
}

// WithCleanupLabels is a function to apply user-defined service labels to PostfixExporter.
func WithQmgrLabels(labels []string) ServiceLabel {
	return func(e *PostfixExporter) {
		e.qmgrLabels = labels
	}
}

// WithCleanupLabels is a function to apply user-defined service labels to PostfixExporter.
func WithSmtpLabels(labels []string) ServiceLabel {
	return func(e *PostfixExporter) {
		e.smtpLabels = labels
	}
}

// WithCleanupLabels is a function to apply user-defined service labels to PostfixExporter.
func WithSmtpdLabels(labels []string) ServiceLabel {
	return func(e *PostfixExporter) {
		e.smtpdLabels = labels
	}
}

// WithCleanupLabels is a function to apply user-defined service labels to PostfixExporter.
func WithBounceLabels(labels []string) ServiceLabel {
	return func(e *PostfixExporter) {
		e.bounceLabels = labels
	}
}

// WithCleanupLabels is a function to apply user-defined service labels to PostfixExporter.
func WithVirtualLabels(labels []string) ServiceLabel {
	return func(e *PostfixExporter) {
		e.virtualLabels = labels
	}
}

func (e *PostfixExporter) init() {
	timeBuckets := []float64{1e-3, 1e-2, 1e-1, 1.0, 10, 1 * 60, 1 * 60 * 60, 24 * 60 * 60, 2 * 24 * 60 * 60}

	e.once.Do(func() {
		e.cleanupProcesses = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "cleanup_messages_processed_total",
			Help:      "Total number of messages processed by cleanup.",
		})
		e.cleanupRejects = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "cleanup_messages_rejected_total",
			Help:      "Total number of messages rejected by cleanup.",
		})
		e.cleanupNotAccepted = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "cleanup_messages_not_accepted_total",
			Help:      "Total number of messages not accepted by cleanup.",
		})
		e.lmtpDelays = prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: "postfix",
				Name:      "lmtp_delivery_delay_seconds",
				Help:      "LMTP message processing time in seconds.",
				Buckets:   timeBuckets,
			},
			[]string{"stage"})
		e.pipeDelays = prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: "postfix",
				Name:      "pipe_delivery_delay_seconds",
				Help:      "Pipe message processing time in seconds.",
				Buckets:   timeBuckets,
			},
			[]string{"relay", "stage"})
		e.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},
		})
		e.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},
		})
		e.qmgrRemoves = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "qmgr_messages_removed_total",
			Help:      "Total number of messages removed from mail queues.",
		})
		e.qmgrExpires = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "qmgr_messages_expired_total",
			Help:      "Total number of messages expired from mail queues.",
		})
		e.smtpDelays = prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: "postfix",
				Name:      "smtp_delivery_delay_seconds",
				Help:      "SMTP message processing time in seconds.",
				Buckets:   timeBuckets,
			},
			[]string{"stage"})
		e.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"})
		e.smtpDeferreds = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "smtp_deferred_messages_total",
			Help:      "Total number of messages that have been deferred on SMTP.",
		})
		e.smtpProcesses = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "postfix",
				Name:      "smtp_messages_processed_total",
				Help:      "Total number of messages that have been processed by the smtp process.",
			},
			[]string{"status"})
		e.smtpDeferredDSN = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "postfix",
				Name:      "smtp_deferred_messages_by_dsn_total",
				Help:      "Total number of messages that have been deferred on SMTP by DSN.",
			},
			[]string{"dsn"})
		e.smtpBouncedDSN = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "postfix",
				Name:      "smtp_bounced_messages_by_dsn_total",
				Help:      "Total number of messages that have been bounced on SMTP by DSN.",
			},
			[]string{"dsn"})
		e.smtpConnectionTimedOut = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "smtp_connection_timed_out_total",
			Help:      "Total number of messages that have been deferred on SMTP.",
		})
		e.smtpdConnects = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "smtpd_connects_total",
			Help:      "Total number of incoming connections.",
		})
		e.smtpdDisconnects = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "smtpd_disconnects_total",
			Help:      "Total number of incoming disconnections.",
		})
		e.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.",
		})
		e.smtpdLostConnections = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "postfix",
				Name:      "smtpd_connections_lost_total",
				Help:      "Total number of connections lost.",
			},
			[]string{"after_stage"})
		e.smtpdProcesses = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "postfix",
				Name:      "smtpd_messages_processed_total",
				Help:      "Total number of messages processed.",
			},
			[]string{"sasl_method"})
		e.smtpdRejects = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "postfix",
				Name:      "smtpd_messages_rejected_total",
				Help:      "Total number of NOQUEUE rejects.",
			},
			[]string{"code"})
		e.smtpdSASLAuthenticationFailures = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "smtpd_sasl_authentication_failures_total",
			Help:      "Total number of SASL authentication failures.",
		})
		e.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"})
		e.unsupportedLogEntries = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "postfix",
				Name:      "unsupported_log_entries_total",
				Help:      "Log entries that could not be processed.",
			},
			[]string{"service", "level"})
		e.smtpStatusDeferred = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "smtp_status_deferred",
			Help:      "Total number of messages deferred.",
		})
		e.opendkimSignatureAdded = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "opendkim",
				Name:      "signatures_added_total",
				Help:      "Total number of messages signed.",
			},
			[]string{"subject", "domain"},
		)
		e.bounceNonDelivery = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "bounce_non_delivery_notification_total",
			Help:      "Total number of non delivery notification sent by bounce.",
		})
		e.virtualDelivered = prometheus.NewCounter(prometheus.CounterOpts{
			Namespace: "postfix",
			Name:      "virtual_delivered_total",
			Help:      "Total number of mail delivered to a virtual mailbox.",
		})
	})
}

// NewPostfixExporter creates a new Postfix exporter instance.
func NewPostfixExporter(showqPath string, logSrc LogSource, logUnsupportedLines bool, serviceLabels ...ServiceLabel) *PostfixExporter {
	postfixExporter := &PostfixExporter{
		cleanupLabels:       defaultCleanupLabels,
		lmtpLabels:          defaultLmtpLabels,
		pipeLabels:          defaultPipeLabels,
		qmgrLabels:          defaultQmgrLabels,
		smtpLabels:          defaultSmtpLabels,
		smtpdLabels:         defaultSmtpdLabels,
		bounceLabels:        defaultBounceLabels,
		virtualLabels:       defaultVirtualLabels,
		logUnsupportedLines: logUnsupportedLines,
		showq:               showq.NewShowq(showqPath),
		showqPath:           showqPath,
		logSrc:              logSrc,
	}

	for _, serviceLabel := range serviceLabels {
		serviceLabel(postfixExporter)
	}

	postfixExporter.init()

	return postfixExporter
}

// Describe the Prometheus metrics that are going to be exported.
func (e *PostfixExporter) Describe(ch chan<- *prometheus.Desc) {
	ch <- postfixUpDesc

	if e.logSrc == nil {
		return
	}
	ch <- e.cleanupProcesses.Desc()
	ch <- e.cleanupRejects.Desc()
	ch <- e.cleanupNotAccepted.Desc()
	e.lmtpDelays.Describe(ch)
	e.pipeDelays.Describe(ch)
	ch <- e.qmgrInsertsNrcpt.Desc()
	ch <- e.qmgrInsertsSize.Desc()
	ch <- e.qmgrRemoves.Desc()
	ch <- e.qmgrExpires.Desc()
	e.smtpDelays.Describe(ch)
	e.smtpTLSConnects.Describe(ch)
	ch <- e.smtpDeferreds.Desc()
	e.smtpProcesses.Describe(ch)
	e.smtpDeferredDSN.Describe(ch)
	e.smtpBouncedDSN.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)
	ch <- e.smtpStatusDeferred.Desc()
	e.unsupportedLogEntries.Describe(ch)
	e.smtpConnectionTimedOut.Describe(ch)
	e.opendkimSignatureAdded.Describe(ch)
	ch <- e.bounceNonDelivery.Desc()
	ch <- e.virtualDelivered.Desc()
}

func (e *PostfixExporter) StartMetricCollection(ctx context.Context) {
	if e.logSrc == nil {
		return
	}

	gaugeVec := prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Namespace: "postfix",
			Subsystem: "",
			Name:      "up",
			Help:      "Whether scraping Postfix's metrics was successful.",
		},
		[]string{"path"})
	gauge := gaugeVec.WithLabelValues(e.logSrc.Path())
	defer gauge.Set(0)

	for {
		line, err := e.logSrc.Read(ctx)
		if err != nil {
			if err != SystemdNoMoreEntries {
				log.Printf("Couldn't read journal: %v", err)
				return
			}
		}
		e.CollectFromLogLine(line)
		gauge.Set(1)
	}
}

// Collect metrics from Postfix's showq socket and its log file.
func (e *PostfixExporter) Collect(ch chan<- prometheus.Metric) {
	err := e.showq.Collect(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)
	}

	if e.logSrc == nil {
		return
	}
	ch <- e.cleanupProcesses
	ch <- e.cleanupRejects
	ch <- e.cleanupNotAccepted
	e.lmtpDelays.Collect(ch)
	e.pipeDelays.Collect(ch)
	ch <- e.qmgrInsertsNrcpt
	ch <- e.qmgrInsertsSize
	ch <- e.qmgrRemoves
	ch <- e.qmgrExpires
	e.smtpDelays.Collect(ch)
	e.smtpTLSConnects.Collect(ch)
	ch <- e.smtpDeferreds
	e.smtpProcesses.Collect(ch)
	ch <- e.smtpdConnects
	ch <- e.smtpdDisconnects
	ch <- e.smtpdFCrDNSErrors
	e.smtpdLostConnections.Collect(ch)
	e.smtpdProcesses.Collect(ch)
	e.smtpDeferredDSN.Collect(ch)
	e.smtpBouncedDSN.Collect(ch)
	e.smtpdRejects.Collect(ch)
	ch <- e.smtpdSASLAuthenticationFailures
	e.smtpdTLSConnects.Collect(ch)
	ch <- e.smtpStatusDeferred
	e.unsupportedLogEntries.Collect(ch)
	ch <- e.smtpConnectionTimedOut
	e.opendkimSignatureAdded.Collect(ch)
	ch <- e.bounceNonDelivery
	ch <- e.virtualDelivered
}