github.com/koko1123/flow-go-1@v0.29.6/module/metrics/mempool.go (about) 1 package metrics 2 3 import ( 4 "fmt" 5 "time" 6 7 "github.com/prometheus/client_golang/prometheus" 8 "github.com/prometheus/client_golang/prometheus/promauto" 9 10 "github.com/koko1123/flow-go-1/engine" 11 "github.com/koko1123/flow-go-1/module" 12 ) 13 14 type MempoolCollector struct { 15 unit *engine.Unit 16 entries *prometheus.GaugeVec 17 interval time.Duration 18 delay time.Duration 19 entriesFuncs map[string]module.EntriesFunc // keeps map of registered EntriesFunc of mempools 20 } 21 22 func NewMempoolCollector(interval time.Duration) *MempoolCollector { 23 24 mc := &MempoolCollector{ 25 unit: engine.NewUnit(), 26 interval: interval, 27 delay: 0, 28 entriesFuncs: make(map[string]module.EntriesFunc), 29 30 entries: promauto.NewGaugeVec(prometheus.GaugeOpts{ 31 Name: "entries_total", 32 Namespace: namespaceStorage, 33 Subsystem: subsystemMempool, 34 Help: "the number of entries in the mempool", 35 }, []string{LabelResource}), 36 } 37 38 return mc 39 } 40 41 func (mc *MempoolCollector) MempoolEntries(resource string, entries uint) { 42 mc.entries.With(prometheus.Labels{LabelResource: resource}).Set(float64(entries)) 43 } 44 45 // Register registers entriesFunc for a resource 46 func (mc *MempoolCollector) Register(resource string, entriesFunc module.EntriesFunc) error { 47 mc.unit.Lock() 48 defer mc.unit.Unlock() 49 50 if _, ok := mc.entriesFuncs[resource]; ok { 51 return fmt.Errorf("cannot register resource, already exists: %s", resource) 52 } 53 54 mc.entriesFuncs[resource] = entriesFunc 55 56 return nil 57 } 58 59 func (mc *MempoolCollector) Ready() <-chan struct{} { 60 mc.unit.LaunchPeriodically(mc.gaugeEntries, mc.interval, mc.delay) 61 return mc.unit.Ready() 62 } 63 64 func (mc *MempoolCollector) Done() <-chan struct{} { 65 66 return mc.unit.Done() 67 } 68 69 // gaugeEntries iterates over the registered entries functions 70 // and calls MempoolEntries on them to capture the size of registered mempools 71 func (mc *MempoolCollector) gaugeEntries() { 72 for r, f := range mc.entriesFuncs { 73 mc.MempoolEntries(r, f()) 74 } 75 }