-
Notifications
You must be signed in to change notification settings - Fork 0
/
mempool.go
119 lines (106 loc) · 2.48 KB
/
mempool.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"context"
"encoding/json"
"errors"
"time"
tz "github.com/ecadlabs/gotez/v2"
client "github.com/ecadlabs/gotez/v2/clientv2"
"github.com/ecadlabs/gotez/v2/clientv2/mempool"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
)
type MempoolMonitorConfig struct {
Client *client.Client
ChainID *tz.ChainID
Timeout time.Duration
ReconnectDelay time.Duration
Reg prometheus.Registerer
NextProtocolFunc func() *tz.ProtocolHash
}
func (c *MempoolMonitorConfig) New() *MempoolMonitor {
m := &MempoolMonitor{
cfg: *c,
metric: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "tezos",
Subsystem: "node",
Name: "mempool_operations_total",
Help: "The total number of mempool operations. Resets on reconnection.",
}, []string{"kind", "proto"}),
}
if c.Reg != nil {
c.Reg.MustRegister(m.metric)
}
return m
}
type MempoolMonitor struct {
cfg MempoolMonitorConfig
cancel context.CancelFunc
done chan struct{}
metric *prometheus.CounterVec
}
func (h *MempoolMonitor) Start() {
ctx, cancel := context.WithCancel(context.Background())
h.cancel = cancel
h.done = make(chan struct{})
go h.serve(ctx)
}
func (h *MempoolMonitor) Stop(ctx context.Context) error {
h.cancel()
select {
case <-h.done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (h *MempoolMonitor) serve(ctx context.Context) {
defer close(h.done)
var err error
for {
if err != nil {
log.Error(err)
t := time.After(h.cfg.ReconnectDelay)
select {
case <-t:
case <-ctx.Done():
return
}
}
h.metric.Reset()
var (
stream <-chan *mempool.MonitorResponse
errCh <-chan error
)
stream, errCh, err = mempool.Monitor(ctx, h.cfg.Client, h.cfg.ChainID)
if err != nil {
if errors.Is(err, context.Canceled) {
return
}
continue
}
Recv:
for {
select {
case err = <-errCh:
if errors.Is(err, context.Canceled) {
return
}
break Recv
case resp := <-stream:
counter := h.metric.MustCurryWith(prometheus.Labels{"proto": h.cfg.NextProtocolFunc().String()})
if log.GetLevel() >= log.DebugLevel {
buf, _ := json.MarshalIndent(resp.Contents, "", " ")
log.Debug(string(buf))
}
for _, list := range resp.Contents {
for _, grp := range list.Contents {
for _, op := range grp.Operations() {
counter.With(prometheus.Labels{"kind": op.OperationKind()}).Inc()
}
}
}
}
}
}
}