-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
mailbox_prom.go
72 lines (60 loc) · 1.48 KB
/
mailbox_prom.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
package utils
import (
"context"
"strconv"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var mailboxLoad = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "mailbox_load_percent",
Help: "Percent of mailbox capacity used",
},
[]string{"appID", "name", "capacity"},
)
const mailboxPromInterval = 5 * time.Second
type MailboxMonitor struct {
StartStopOnce
appID string
mailboxes sync.Map
stop func()
}
func NewMailboxMonitor(appID string) *MailboxMonitor {
return &MailboxMonitor{appID: appID}
}
func (m *MailboxMonitor) Start(context.Context) error {
return m.StartOnce("MailboxMonitor", func() error {
t := time.NewTicker(WithJitter(mailboxPromInterval))
m.stop = t.Stop
go m.monitorLoop(t.C)
return nil
})
}
func (m *MailboxMonitor) Close() error {
return m.StopOnce("MailboxMonitor", func() error {
m.stop()
return nil
})
}
func (m *MailboxMonitor) monitorLoop(c <-chan time.Time) {
for range c {
m.mailboxes.Range(func(k, v any) bool {
name, mb := k.(string), v.(mailbox)
c, p := mb.load()
capacity := strconv.FormatUint(c, 10)
mailboxLoad.WithLabelValues(m.appID, name, capacity).Set(p)
return true
})
}
}
type mailbox interface {
load() (capacity uint64, percent float64)
onClose(func())
}
func (m *MailboxMonitor) Monitor(mb mailbox, name ...string) {
n := strings.Join(name, ".")
m.mailboxes.Store(n, mb)
mb.onClose(func() { m.mailboxes.Delete(n) })
}