github.com/MetalBlockchain/metalgo@v1.11.9/snow/networking/timeout/metrics.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package timeout
     5  
     6  import (
     7  	"errors"
     8  	"sync"
     9  	"time"
    10  
    11  	"github.com/prometheus/client_golang/prometheus"
    12  
    13  	"github.com/MetalBlockchain/metalgo/ids"
    14  	"github.com/MetalBlockchain/metalgo/message"
    15  	"github.com/MetalBlockchain/metalgo/snow"
    16  )
    17  
    18  const (
    19  	chainLabel = "chain"
    20  	opLabel    = "op"
    21  )
    22  
    23  var opLabels = []string{chainLabel, opLabel}
    24  
    25  type timeoutMetrics struct {
    26  	messages         *prometheus.CounterVec // chain + op
    27  	messageLatencies *prometheus.GaugeVec   // chain + op
    28  
    29  	lock           sync.RWMutex
    30  	chainIDToAlias map[ids.ID]string
    31  }
    32  
    33  func newTimeoutMetrics(reg prometheus.Registerer) (*timeoutMetrics, error) {
    34  	m := &timeoutMetrics{
    35  		messages: prometheus.NewCounterVec(
    36  			prometheus.CounterOpts{
    37  				Name: "messages",
    38  				Help: "number of responses",
    39  			},
    40  			opLabels,
    41  		),
    42  		messageLatencies: prometheus.NewGaugeVec(
    43  			prometheus.GaugeOpts{
    44  				Name: "message_latencies",
    45  				Help: "message latencies (ns)",
    46  			},
    47  			opLabels,
    48  		),
    49  		chainIDToAlias: make(map[ids.ID]string),
    50  	}
    51  	return m, errors.Join(
    52  		reg.Register(m.messages),
    53  		reg.Register(m.messageLatencies),
    54  	)
    55  }
    56  
    57  func (m *timeoutMetrics) RegisterChain(ctx *snow.ConsensusContext) error {
    58  	m.lock.Lock()
    59  	defer m.lock.Unlock()
    60  
    61  	m.chainIDToAlias[ctx.ChainID] = ctx.PrimaryAlias
    62  	return nil
    63  }
    64  
    65  // Record that a response of type [op] took [latency]
    66  func (m *timeoutMetrics) Observe(chainID ids.ID, op message.Op, latency time.Duration) {
    67  	m.lock.RLock()
    68  	defer m.lock.RUnlock()
    69  
    70  	labels := prometheus.Labels{
    71  		chainLabel: m.chainIDToAlias[chainID],
    72  		opLabel:    op.String(),
    73  	}
    74  	m.messages.With(labels).Inc()
    75  	m.messageLatencies.With(labels).Add(float64(latency))
    76  }