-
Notifications
You must be signed in to change notification settings - Fork 1
/
mysqlbin.go
94 lines (83 loc) · 1.94 KB
/
mysqlbin.go
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
package main
import (
"bufio"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
)
type MySQLBinOptions struct {
Path string `json:"path"`
}
func (opts *MySQLBinOptions) initDefault() {
if opts.Path == "" {
opts.Path = "/var/log/mysql"
}
}
type MySQLBinChecker struct {
opts MySQLBinOptions
promBinlogOk *prometheus.Desc
}
func NewMySQLBinChecker(opts MySQLBinOptions) *MySQLBinChecker {
opts.initDefault()
return &MySQLBinChecker{
opts: opts,
promBinlogOk: prometheus.NewDesc(
"mysql_binlog_ok",
"are all binlog files from the index available?",
[]string{},
nil),
}
}
func (c *MySQLBinChecker) Describe(ch chan<- *prometheus.Desc) {
ch <- c.promBinlogOk
}
func (c *MySQLBinChecker) Collect(ch chan<- prometheus.Metric) {
ok, err := c.checkBinlogs()
if err != nil {
log.Println("invalid binlog files detected:", err)
}
value := 0.0
if ok {
value = 1.0
}
ch <- prometheus.MustNewConstMetric(
c.promBinlogOk,
prometheus.GaugeValue,
value,
)
}
func (c *MySQLBinChecker) checkBinlogs() (bool, error) {
indexFile, err := os.Open(filepath.Join(c.opts.Path, "mysql-bin.index"))
if err != nil {
return false, errors.Wrap(err, "failed to open index file")
}
defer indexFile.Close()
scanner := bufio.NewScanner(indexFile)
for scanner.Scan() {
filename := strings.TrimSpace(scanner.Text())
if filename == "" {
continue
}
if !filepath.IsAbs(filename) {
filename = filepath.Join(c.opts.Path, filename)
}
info, err := os.Stat(filename)
if err != nil {
if os.IsNotExist(err) {
return false, errors.Wrapf(err, "missing file %q", filename)
}
return false, errors.Wrapf(err, "failed to stat file %q", filename)
}
if info.IsDir() {
return false, fmt.Errorf("unexpected directory %q", filename)
}
}
if err := scanner.Err(); err != nil {
return false, errors.Wrap(err, "failed to scan index file")
}
return true, nil
}