-
Notifications
You must be signed in to change notification settings - Fork 1
/
metrics.go
100 lines (87 loc) · 2.39 KB
/
metrics.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
95
96
97
98
99
100
package metrics
import (
"log/slog"
"net/http"
"os"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Metrics contains the collected metrics
type Metrics struct {
totalBackups prometheus.Counter
backupSuccess prometheus.Gauge
backupSize prometheus.Gauge
totalErrors *prometheus.CounterVec
}
// New generates new metrics
func New() *Metrics {
backupSuccess := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "backup_success",
Help: "is 0 when the last backup was successful, otherwise 1",
},
)
totalBackups := prometheus.NewCounter(prometheus.CounterOpts{
Name: "backup_total_backups",
Help: "total number of successful backups",
},
)
totalErrors := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "backup_errors",
Help: "total number of errors during backups",
},
[]string{"operation"},
)
backupSize := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "backup_size",
Help: "size of last backup in bytes",
},
)
return &Metrics{
totalBackups: totalBackups,
backupSuccess: backupSuccess,
totalErrors: totalErrors,
backupSize: backupSize,
}
}
// Start starts the metrics server
func (m *Metrics) Start(log *slog.Logger) {
log.Info("starting metrics server")
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte(`<html>
<head><title>backup-restore metrics</title></head>
<body>
<h1>backup-restore metrics</h1>
<p><a href='/metrics'>Metrics</a></p </body </html>`))
if err != nil {
log.Error("error handling metrics root endpoint", "error", err)
}
})
prometheus.MustRegister(m.backupSuccess)
prometheus.MustRegister(m.totalBackups)
prometheus.MustRegister(m.totalErrors)
prometheus.MustRegister(m.backupSize)
go func() {
server := http.Server{
Addr: ":2112",
ReadHeaderTimeout: 1 * time.Minute,
}
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}()
}
// CountBackup updates metrics counter
func (m *Metrics) CountBackup(backupFile string) {
s, _ := os.Stat(backupFile)
m.totalBackups.Inc()
m.backupSuccess.Set(1)
m.backupSize.Set(float64(s.Size()))
}
// CountError increases error counter for the given operation
func (m *Metrics) CountError(op string) {
m.totalErrors.With(prometheus.Labels{"operation": op}).Inc()
m.backupSuccess.Set(0)
}