master
go 71 lines 1.4 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package postfix
4
5 import (
6 "bufio"
7 "bytes"
8 "errors"
9 "fmt"
10 "strconv"
11 "strings"
12 )
13
14 type postqueueStats struct {
15 sizeKbyte int64
16 requests int64
17 }
18
19 func (c *Collector) collect() (map[string]int64, error) {
20 bs, err := c.exec.list()
21 if err != nil {
22 return nil, err
23 }
24
25 stats, err := parsePostqueueOutput(bs)
26 if err != nil {
27 return nil, err
28 }
29
30 mx := make(map[string]int64)
31
32 mx["emails"] = stats.requests
33 mx["size"] = stats.sizeKbyte
34
35 return mx, nil
36 }
37
38 func parsePostqueueOutput(bs []byte) (*postqueueStats, error) {
39 if len(bs) == 0 {
40 return nil, errors.New("empty postqueue output")
41 }
42
43 var lastLine string
44 sc := bufio.NewScanner(bytes.NewReader(bs))
45 for sc.Scan() {
46 if line := strings.TrimSpace(sc.Text()); line != "" {
47 lastLine = strings.TrimSpace(sc.Text())
48 }
49 }
50
51 if lastLine == "Mail queue is empty" {
52 return &postqueueStats{}, nil
53 }
54
55 // -- 3 Kbytes in 3 Requests.
56 parts := strings.Fields(lastLine)
57 if len(parts) < 5 {
58 return nil, fmt.Errorf("unexpected postqueue output ('%s')", lastLine)
59 }
60
61 size, err := strconv.ParseInt(parts[1], 10, 64)
62 if err != nil {
63 return nil, fmt.Errorf("unexpected postqueue output ('%s')", lastLine)
64 }
65 requests, err := strconv.ParseInt(parts[4], 10, 64)
66 if err != nil {
67 return nil, fmt.Errorf("unexpected postqueue output ('%s')", lastLine)
68 }
69
70 return &postqueueStats{sizeKbyte: size, requests: requests}, nil
71 }