package metrics
import "github.com/Diarkis/diarkis/metrics"
Package metrics ▷
Package metrics provides a flexible framework for defining, registering, and exporting application‑level metrics within the Diarkis mesh network. It enables the remote scraping of both built‑in and custom metrics. All functions and methods are thread-safe.
At its core, metrics exports (3) primary metric types:
- Counter: a monotonically increasing uint64.
- Gauge: an int64 that can go up or down.
- Histogram: a sample of observations sorted into buckets with a total, and cumulative sum.
Each of these metrics have a corresponding vector type for which a collection of basic metric types is partitioned by a set of arbitrary labels. This follows the OpenMetrics specification for LabelSet.
Furthermore, each metric implements the Metric interface, which includes private methods for serialization, and may be output in either in Prometheus format which may scraped via the '/metrics/prometheus' endpoint, format or custom JSON format 'metrics/json'.
To use this package correctly:
- Call Setup before diarkis.Start and after mesh.Setup.
- Avoid duplicate metric names (registration will panic on collision).
Usage pattern:
- At startup, call Setup to initialize the metrics subsystem and hook into the underlying mesh update callbacks.
- Define static metrics with NewCounter, NewGauge, NewHistogram, etc.
- In your code, call Counter.Inc, Gauge.Set, Histogram.Observe, etc. to atomically the update metric values.
- Any request to a metrics endpoint returns the registered metrics of all nodes in the Diarkis cluster.
Export helpers:
- [GetPrometheusMetrics]: Gathers all node metrics and returns a Prometheus‑format string across all node types.
- [GetJSONMetrics]: Gathers all node metrics and returns a JSON array string.
Under the hood, metrics are stored within a global registry (protected by a mutex) and dispatched to the Diarkis mesh via internal RPC. Atomic metrics implementations ensure thread‑safe updates.
Index
- Variables
- func DefineMetricsValue(name string, cb ValueUpdate) error deprecated
- func DefineMetricsValueWithLabel(name string, cb ValueLabelUpdate) error deprecated
- func GetCCUByNodeAddress(addr string) int deprecated
- func GetRoomNumbersByNodeAddress(addr string) int deprecated
- func JSONMetrics() (string, error)
- func PrometheusMetrics() (string, error)
- func Setup(path string)
- type Counter
- type CounterOpts
-
type CounterVec
- func NewCounterVec(opts CounterVecOpts) *CounterVec
- func (cv *CounterVec) GetMetricWithLabelValues(labels ...string) (*Counter, error)
- func (cv *CounterVec) MarshalJSON() ([]byte, error)
- func (cv *CounterVec) UnmarshalJSON(data []byte) error
- func (cv *CounterVec) WithLabelValues(labels ...string) *Counter
- type CounterVecOpts
- type Gauge
- type GaugeOpts
- type GaugeVec
- type GaugeVecOpts
- type Histogram
- type HistogramOpts
-
type HistogramVec
- func NewHistogramVec(opts HistogramVecOpts) *HistogramVec
- func (hv *HistogramVec) GetMetricWithLabelValues(labels ...string) (*Histogram, error)
- func (hv *HistogramVec) MarshalJSON() ([]byte, error)
- func (hv *HistogramVec) UnmarshalJSON(data []byte) error
- func (hv *HistogramVec) WithLabelValues(labels ...string) *Histogram
- type HistogramVecOpts
- type Item deprecated
- type LabelValue deprecated
- type Metric
- type ValueLabelUpdate deprecated
- type ValueUpdate deprecated
Variables
var DefaultBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, math.Inf(+1)}
DefaultBuckets are the default Histogram buckets. General one-size-fits-all for network service response times (in seconds). We highly recommend you to use a customized set of buckets.
The default will be applied if no buckets are provided in the HistogramOpts upon creation.
var ErrUninitializedMetric = errors.New("metric is uninitialized")
ErrUninitializedMetric the provided metric receiver type is uninitialized
Functions
func DefineMetricsValue deprecated
func DefineMetricsValue(name string, cb ValueUpdate) error
DefineMetricsValue defines the value update operation of the metrics name given.
[IMPORTANT] MUST invoke this function BEFORE calling diarkis.Start() [IMPORTANT] MUST invoke this function AFTER calling mesh.Setup(...)
Error Cases:
┌────────────────────────────────────────────────┬──────────────────────────────────────────────────────────────────────────────┐ │ Error │ Reason │ ╞════════════════════════════════════════════════╪══════════════════════════════════════════════════════════════════════════════╡ │ Setup must invoked at the start of the process │ Invoking this function without calling Setup() is not allowed. │ ├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────┤ │ Must be invoked BEFORE the start of Diarkis │ Invoking this function after the start of Diarkis is not allowed. │ ├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────┤ │ Metrics name must be configured │ All metrics names must be configured in the configuration file. │ ├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────┤ │ Metrics value update function already assigned │ Assigning multiple value update functions for a metrics name is not allowed. │ └────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────────────────────┘
The name must be configured in a configuration file.
Deprecated: please use CounterVec or GaugeVec for a metric group with custom labels.
func DefineMetricsValueWithLabel deprecated
func DefineMetricsValueWithLabel(name string, cb ValueLabelUpdate) error
DefineMetricsValueWithLabel defines the value update operation of the metrics name and label given. Currently it only works for Prometheus metrics. See the documentation for DefineMetricsValue for more information
Deprecated: please use CounterVec or GaugeVec for a metric group with custom labels.
func GetCCUByNodeAddress deprecated
func GetCCUByNodeAddress(addr string) int
GetCCUByNodeAddress returns CCU of a remote node by its mesh address
Deprecated: Please curl at the Diarkis metrics endpoint to get node metrics.
func GetRoomNumbersByNodeAddress deprecated
func GetRoomNumbersByNodeAddress(addr string) int
GetRoomNumbersByNodeAddress returns the number of rooms on a remote node by its mesh address
Deprecated: Please curl at the Diarkis metrics endpoint to get node metrics.
func JSONMetrics
func JSONMetrics() (string, error)
JSONMetrics collects the metrics of all the nodes in the Diarkis mesh and returns them in JSON format
func PrometheusMetrics
func PrometheusMetrics() (string, error)
PrometheusMetrics collects the metrics of all the nodes in the Diarkis mesh and returns them in Prometheus metric format
func Setup
func Setup(path string)
Setup must be invoked at the start of the process in order to use metrics.
[IMPORTANT] Must invoke this function BEFORE calling diarkis.Start() [IMPORTANT] MUST invoke this function AFTER calling mesh.Setup(...)
Types
type Counter
type Counter struct { }
Counter represents a Diarkis Metric type which holds a single uint64 value.
func NewCounter
func NewCounter(opts CounterOpts) *Counter
NewCounter returns a Counter configured according to options. See CounterOpts for details.
func (*Counter) Add
func (c *Counter) Add(delta uint64)
Add adds the given delta to the Counter.
func (*Counter) Inc
func (c *Counter) Inc()
Inc increments the Counter by 1. Use Add to increment it by arbitrary non-negative values.
func (*Counter) MarshalJSON
func (c *Counter) MarshalJSON() ([]byte, error)
MarshalJSON serializes the Counter metric into JSON format.
func (*Counter) UnmarshalJSON
func (c *Counter) UnmarshalJSON(data []byte) error
UnmarshalJSON deserializes the JSON-encoded data into the Counter metric.
type CounterOpts
type CounterOpts struct { // Name of the Counter metric to be created. Must NOT be empty. All names MUST be unique. Name string // Help description of the Counter metric to be created. Help string // NodeRoles for which the metric will active on within the cluster. // For example: If a metric is to be gathered on a UDP node, // UDP must be a member of the slice of Diarkis NodeRoles. NodeRoles []diarkis.NodeRole }
CounterOpts defines options for creating a Counter metric type.
type CounterVec
type CounterVec struct { }
CounterVec manages multiple labeled counters.
func NewCounterVec
func NewCounterVec(opts CounterVecOpts) *CounterVec
NewCounterVec returns a CounterVec configured according to options. See CounterVecOpts for details.
func (*CounterVec) GetMetricWithLabelValues
func (cv *CounterVec) GetMetricWithLabelValues(labels ...string) (*Counter, error)
GetMetricWithLabelValues returns (and creates if necessary) the Counter identified by the supplied label values.
func (*CounterVec) MarshalJSON
func (cv *CounterVec) MarshalJSON() ([]byte, error)
MarshalJSON serializes the CounterVec metric into JSON format.
func (*CounterVec) UnmarshalJSON
func (cv *CounterVec) UnmarshalJSON(data []byte) error
UnmarshalJSON deserializes the JSON-encoded data into the CounterVec metric.
func (*CounterVec) WithLabelValues
func (cv *CounterVec) WithLabelValues(labels ...string) *Counter
WithLabelValues returns the Counter associated with the given label value set, creating it on first use.
This is the "fast-path" helper: it panics if the number of values does not match cv.LabelNames or if the CounterVec is nil. Use CounterVec.GetMetricWithLabelValues when you prefer an error instead of a panic.
type CounterVecOpts
type CounterVecOpts struct { // LabelNames are the label keys that differentiate the individual // counters inside the vector. Every update must specify a value for // each label key listed here. // // Example: // // // One counter per unique (method, route, status) tuple to track // // the number of HTTP requests served. // CounterVecOpts{ // CounterOpts: CounterOpts{ // Name: "http_requests_total", // Help: "Total number of HTTP requests processed.", // }, // LabelNames: []string{"method", "route", "status"}, // } LabelNames []string CounterOpts }
CounterVecOpts defines options for creating a CounterVec metric type.
type Gauge
type Gauge struct { }
Gauge represents a Diarkis Metric type which holds a single int64 value.
func NewGauge
func NewGauge(opts GaugeOpts) *Gauge
NewGauge returns a Gauge configured according to options. See GaugeOpts for details.
func (*Gauge) Add
func (g *Gauge) Add(delta int64)
Add adds the given delta to the Gauge. (The delta can be negative, which will decrease the Gauge.)
func (*Gauge) Dec
func (g *Gauge) Dec()
Dec decrements the Gauge by 1. Use Sub to decrease it by an arbitrary delta.
func (*Gauge) Inc
func (g *Gauge) Inc()
Inc increments the Gauge by 1. Use Add to increase it by an arbitrary delta.
func (*Gauge) MarshalJSON
func (g *Gauge) MarshalJSON() ([]byte, error)
MarshalJSON serializes the Gauge metric into JSON format.
func (*Gauge) Set
func (g *Gauge) Set(val int64)
Set sets the Gauge to an arbitrary value.
func (*Gauge) Sub
func (g *Gauge) Sub(delta int64)
Sub subtracts the given delta from the Gauge. (The delta can be negative, which will increase the Gauge.)
func (*Gauge) UnmarshalJSON
func (g *Gauge) UnmarshalJSON(data []byte) error
UnmarshalJSON deserializes the JSON-encoded data into the Gauge metric.
type GaugeOpts
type GaugeOpts struct { // Name of the Gauge metric to be created. Must NOT be empty. All names MUST be unique. Name string // Help description of the Gauge metric to be created. Help string // NodeRoles for which the metric will active on within the cluster. // For example: If a metric is to be gathered on a UDP node, // UDP must be a member of the slice of Diarkis NodeRoles. NodeRoles []diarkis.NodeRole }
GaugeOpts defines options for creating a Gauge metric type.
type GaugeVec
type GaugeVec struct { }
GaugeVec manages multiple labeled gauges.
func NewGaugeVec
func NewGaugeVec(opts GaugeVecOpts) *GaugeVec
NewGaugeVec returns a GaugeVec configured according to options. See GaugeVecOpts for details.
func (*GaugeVec) GetMetricWithLabelValues
func (gv *GaugeVec) GetMetricWithLabelValues(labels ...string) (*Gauge, error)
GetMetricWithLabelValues returns (and creates if necessary) the Gauge identified by the supplied label values.
func (*GaugeVec) MarshalJSON
func (gv *GaugeVec) MarshalJSON() ([]byte, error)
MarshalJSON serializes the GaugeVec metric into JSON format.
func (*GaugeVec) UnmarshalJSON
func (gv *GaugeVec) UnmarshalJSON(data []byte) error
UnmarshalJSON deserializes the JSON-encoded data into the GaugeVec metric.
func (*GaugeVec) WithLabelValues
func (gv *GaugeVec) WithLabelValues(labels ...string) *Gauge
WithLabelValues returns the Gauge associated with the given label value set, creating it on first use.
This is the "fast-path" helper: it panics if the number of values does not match cv.LabelNames or if the GaugeVec is nil. Use GaugeVec.GetMetricWithLabelValues when you prefer an error instead of a panic.
type GaugeVecOpts
type GaugeVecOpts struct { // LabelNames are the label keys that differentiate the individual // gauges inside the vector. Every update must specify a value for // each label key listed here. // // Example: // // // One gauge per (type, region) combination tracking open sessions. // GaugeVecOpts{ // GaugeOpts: GaugeOpts{ // Name: "current_sessions", // Help: "Number of active user sessions by type.", // }, // LabelNames: []string{"type", "region"}, // } LabelNames []string GaugeOpts }
GaugeVecOpts defines options for creating a GaugeVec metric type.
type Histogram
type Histogram struct { }
Histogram represents a Diarkis Metric type that samples observations (typically latencies or durations) and counts them in configurable buckets together with the total number of samples, and the cumulative sum for average calculations.
func NewHistogram
func NewHistogram(opts HistogramOpts) *Histogram
NewHistogram returns a Histogram configured according to options. If opts.Buckets is empty, DefaultBuckets are used and a final +Inf bucket is added automatically. See HistogramOpts for details.
func (*Histogram) MarshalJSON
func (h *Histogram) MarshalJSON() ([]byte, error)
MarshalJSON serializes the Histogram into JSON format.
func (*Histogram) Observe
func (h *Histogram) Observe(value float64)
Observe records a value in the Histogram.
func (*Histogram) UnmarshalJSON
func (h *Histogram) UnmarshalJSON(data []byte) error
UnmarshalJSON deserializes the JSON-encoded data into the Histogram.
type HistogramOpts
type HistogramOpts struct { // Name of the Histogram metric to be created. Must NOT be empty. All names MUST be unique. Name string // Help description of the Histogram metric to be created. Help string // NodeRoles for which the metric will active on within the cluster. // For example: If a metric is to be gathered on a UDP node, // UDP must be a member of the slice of Diarkis NodeRoles. NodeRoles []diarkis.NodeRole // Buckets lists the upper-boundaries of the histogram's buckets. // Each value must be in strictly ascending order; an observation is // placed into the first bucket whose bound is ≥ the observed value. // If nil or empty, the collector falls back to the Diarkis default // bucket set. Buckets []float64 }
HistogramOpts defines options for creating a Histogram metric type.
type HistogramVec
type HistogramVec struct { }
HistogramVec manages multiple labeled Histogram metrics.
func NewHistogramVec
func NewHistogramVec(opts HistogramVecOpts) *HistogramVec
NewHistogramVec returns a HistogramVec configured according to options. If opts.Buckets is empty, DefaultBuckets are used and a final +Inf bucket is added automatically. See HistogramVecOpts for details.
func (*HistogramVec) GetMetricWithLabelValues
func (hv *HistogramVec) GetMetricWithLabelValues(labels ...string) (*Histogram, error)
GetMetricWithLabelValues returns (and creates if necessary) the Histogram identified by the supplied label values.
func (*HistogramVec) MarshalJSON
func (hv *HistogramVec) MarshalJSON() ([]byte, error)
MarshalJSON serializes the HistogramVec metric into JSON format.
func (*HistogramVec) UnmarshalJSON
func (hv *HistogramVec) UnmarshalJSON(data []byte) error
UnmarshalJSON deserializes the JSON-encoded data into the Histogram.
func (*HistogramVec) WithLabelValues
func (hv *HistogramVec) WithLabelValues(labels ...string) *Histogram
WithLabelValues returns the Histogram associated with the given label value set, creating it on first use.
This is the "fast-path" helper: it panics if the number of values does not match cv.LabelNames or if the HistogramVec is nil. Use CounterVec.GetMetricWithLabelValues when you prefer an error instead of a panic.
type HistogramVecOpts
type HistogramVecOpts struct { // LabelNames are the keys of labels that distinguish the individual // histograms inside the vector. Each observation must supply a value // for every label listed here. // // Example: // // // One histogram per unique (method, route, status) tuple. // HistogramVecOpts{ // HistogramOpts: HistogramOpts{ // Name: "http_request_duration_seconds", // Help: "Histogram of HTTP request latencies.", // Buckets: metrics.DefaultBuckets, // }, // LabelNames: []string{"method", "route", "status"}, // } LabelNames []string HistogramOpts }
HistogramVecOpts defines options for creating a HistogramVec metric type.
type Item deprecated
type Item struct { Addr string Value interface{} Type string Labels map[string]string }
Item [INTERNAL USE ONLY] represents a metrics value
Deprecated: to be removed for v2.0
type LabelValue deprecated
type LabelValue struct { Value interface{} `json:"v"` Labels map[string]string `json:"l"` }
LabelValue is deprecated.
Deprecated: please use CounterVec or GaugeVec for a metric group with custom labels.
type Metric
type Metric interface { // MarshalJSON serializes the metric into its JSON representation. MarshalJSON() ([]byte, error) // UnmarshalJSON deserializes JSON-encoded data. UnmarshalJSON([]byte) error }
Metric provides an interface for a Diarkis metric type.
func LocalMetrics
func LocalMetrics() ([]Metric, error)
LocalMetrics returns a deep copy slice of all currently registered local Diarkis Metric values.
func RemoteMetrics
func RemoteMetrics(nodeAddr string) ([]Metric, error)
RemoteMetrics fetches the metrics from the Diarkis node at the given address.
type ValueLabelUpdate deprecated
type ValueLabelUpdate func() (value []*LabelValue)
ValueLabelUpdate is a function that updates the associated metrics value by using the returned value as its associated metrics label and value.
Deprecated: please use the new GaugeVec for a metric with labels.
type ValueUpdate deprecated
type ValueUpdate func() (value int)
ValueUpdate is a function that updates the associated metrics value by using the returned value as its associated metrics value.
Deprecated: please use CounterVec or GaugeVec for a metric group with custom labels.