github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/monitor/histogram.go (about)

     1  // Copyright (c) 2015 Arista Networks, Inc.
     2  // Use of this source code is governed by the Apache License 2.0
     3  // that can be found in the COPYING file.
     4  
     5  package monitor
     6  
     7  import (
     8  	"expvar"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/aristanetworks/goarista/monitor/stats"
    13  )
    14  
    15  // LatencyHistogram contains the data needed to properly export itself to expvar
    16  // and provide a pretty printed version
    17  type LatencyHistogram struct {
    18  	name        string
    19  	histogram   *stats.Histogram
    20  	latencyUnit time.Duration
    21  }
    22  
    23  // NewLatencyHistogram creates a new histogram and registers an HTTP handler for it.
    24  func NewLatencyHistogram(name string, latencyUnit time.Duration, numBuckets int,
    25  	growth float64, smallest float64, minValue int64) *LatencyHistogram {
    26  
    27  	histogramOptions := stats.HistogramOptions{
    28  		NumBuckets:         numBuckets,
    29  		GrowthFactor:       growth,
    30  		SmallestBucketSize: smallest,
    31  		MinValue:           minValue,
    32  	}
    33  	histogram := &LatencyHistogram{
    34  		name:        name,
    35  		histogram:   stats.NewHistogram(histogramOptions),
    36  		latencyUnit: latencyUnit,
    37  	}
    38  	expvar.Publish(name, histogram)
    39  	return histogram
    40  }
    41  
    42  // Print returns the histogram as a chart
    43  func (h *LatencyHistogram) Print() string {
    44  	return h.addUnits(h.histogram.Delta1m().String()) +
    45  		h.addUnits(h.histogram.Delta10m().String()) +
    46  		h.addUnits(h.histogram.Delta1h().String()) +
    47  		h.addUnits(h.histogram.Value().String())
    48  }
    49  
    50  // String returns the histogram as JSON.
    51  func (h *LatencyHistogram) String() string {
    52  	return h.histogram.String()
    53  }
    54  
    55  // UpdateLatencyValues updates the LatencyHistogram's buckets with the new
    56  // datapoint and updates the string associated with the expvar.String
    57  func (h *LatencyHistogram) UpdateLatencyValues(delta time.Duration) {
    58  	h.histogram.Add(int64(delta / h.latencyUnit))
    59  }
    60  
    61  func (h *LatencyHistogram) addUnits(hist string) string {
    62  	i := strings.Index(hist, "\n")
    63  	return hist[:i] + "µs" + hist[i:]
    64  }