metrics

package
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 7, 2024 License: Apache-2.0 Imports: 14 Imported by: 0

README

ContainerSSH Metrics Library

This library provides centralized metrics collection across modules. It also provides a Prometheus / OpenMetrics compatible HTTP server exposing the collected metrics.

Collecting metrics

The core component of the metrics is the metrics.Collector interface. You can create a new instance of this interface by calling metrics.New() with a GeoIP lookup provider from the geoip library as a parameter. You can then dynamically create metrics:

m := metrics.New(geoip)
testCounter, err := m.CreateCounter(
    "test", // Name of the metric
    "MB", // Unit of the metric
    "This is a test", // Help text of the metric
)

You can then increment the counter:

testCounter.Increment()
testCounter.IncrementBy(5)

Alternatively, you can also create a CounterGeo to make a label automatically based on GeoIP lookup:

testCounter, err := m.CreateCounterGeo(
    "test", // Name of the metric
    "MB", // Unit of the metric
    "This is a test", // Help text of the metric
)
testCounter.Increment(net.ParseIP("127.0.0.1"))

If you need a metric that can be decremented or set directly you can use the Gauge type instead. Each Create* method also has a counterpart named MustCreate*, which panics instead of returning an error.

Custom labels

Each of the metric methods allow adding extra labels:

testCounter.Increment(
    net.ParseIP("127.0.0.1"),
    metrics.Label("foo", "bar"),
    metrics.Label("somelabel","somevalue")
)

The following rules apply and will cause a panic if violated:

  • Label names and values cannot be empty.
  • The country label name is reserved for GeoIP usage.

The metrics also have a WithLabels() method that allow for creating a copy of a metric already primed with a set of labels. This can be used when passing metrics to other modules that need to be scoped.

Using the metrics server

The metrics server exposes the collected metrics on an HTTP webserver in the Prometheus / OpenMetrics format. It requires the service library and a logger from the log library to work properly:

server := metrics.NewServer(
    metrics.Config{
        ServerConfiguration: http.ServerConfiguration{
            Listen:       "127.0.0.1:8080",
        },
        Enable:              true,
        Path:                "/metrics",
    },
    metricsCollector,
    logger,
)

lifecycle := service.NewLifecycle(server)
go func() {
    if err := lifecycle.Run(); err != nil {
        // Handle crash
    } 	
}()

//Later:
lifecycle.Stop(context.Background())

Alternatively, you can skip the full HTTP server and request a handler that you can embed in any Go HTTP server:

handler := metrics.NewHandler(
    "/metrics",
    metricsCollector
)
http.ListenAndServe("0.0.0.0:8080", handler)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CounterCannotBeIncrementedByNegative = errors.New("a counter cannot be incremented by a negative number")

CounterCannotBeIncrementedByNegative is an error returned by counters when they are incremented with a negative

number.
View Source
var MetricAlreadyExists = errors.New("the specified metric already exists")

MetricAlreadyExists is an error that is returned from the Create functions when the metric already exists.

Functions

func NewHandler

func NewHandler(
	path string,
	collector Collector,
) http.Handler

NewHandler creates a new HTTP handler that outputs the collected metrics to the requesting client in the

Prometheus/OpenMetrics format.

func NewServer

func NewServer(cfg config.MetricsConfig, collector Collector, logger log.Logger) (http2.Server, error)

NewServer creates a new metrics server based on the configuration. It MAY return nil if the server is disabled.

Types

type Collector

type Collector interface {
	// CreateCounter creates a monotonic (increasing) counter with the specified name and help text.
	CreateCounter(name string, unit string, help string) (Counter, error)

	// MustCreateCounter creates a monotonic (increasing) counter with the specified name and help text. Panics if an
	// error occurs.
	MustCreateCounter(name string, unit string, help string) Counter

	// CreateCounterGeo creates a monotonic (increasing) counter that is labeled with the country from the GeoIP lookup
	// with the specified name and help text.
	CreateCounterGeo(name string, unit string, help string) (GeoCounter, error)

	// MustCreateCounterGeo creates a monotonic (increasing) counter that is labeled with the country from the GeoIP
	// lookup with the specified name and help text. Panics if an error occurs.
	MustCreateCounterGeo(name string, unit string, help string) GeoCounter

	// CreateGauge creates a freely modifiable numeric gauge with the specified name and help text.
	CreateGauge(name string, unit string, help string) (Gauge, error)

	// MustCreateGauge creates a freely modifiable numeric gauge with the specified name and help text. Panics if an
	// error occurs.
	MustCreateGauge(name string, unit string, help string) Gauge

	// CreateGaugeGeo creates a freely modifiable numeric gauge that is labeled with the country from the GeoIP lookup
	// with the specified name and help text.
	CreateGaugeGeo(name string, unit string, help string) (GeoGauge, error)

	// MustCreateGaugeGeo creates a freely modifiable numeric gauge that is labeled with the country from the GeoIP
	// lookup with the specified name and help text. Panics if an error occurs.
	MustCreateGaugeGeo(name string, unit string, help string) GeoGauge

	// ListMetrics returns a list of metrics metadata stored in the collector.
	ListMetrics() []Metric

	// GetMetric returns a set of values with labels for a specified metric name.
	GetMetric(name string) []MetricValue

	// String returns a Prometheus/OpenMetrics-compatible document with all metrics.
	String() string
}

Collector is the main interface for interacting with the metrics collector.

func New

func New(geoIpLookupProvider geoipprovider.LookupProvider) Collector

New creates the metric collector.

type Counter

type Counter interface {
	SimpleCounter

	// WithLabels adds labels to the counter
	WithLabels(labels ...MetricLabel) Counter
}

Counter extends the SimpleCounter interface by adding a WithLabels function to create a copy of the counter that is primed with a set of labels.

type Gauge

type Gauge interface {
	SimpleGauge

	// WithLabels adds labels to the counter
	WithLabels(labels ...MetricLabel) Gauge
}

Gauge extends the SimpleGauge interface by adding a WithLabels function to create a copy of the counter that is primed with a set of labels.

type GeoCounter

type GeoCounter interface {
	SimpleGeoCounter

	// WithLabels adds labels to the counter
	WithLabels(labels ...MetricLabel) GeoCounter
}

GeoCounter extends the SimpleGeoCounter interface by adding a WithLabels function to create a copy of the counter that is primed with a set of labels.

type GeoGauge

type GeoGauge interface {
	SimpleGeoGauge

	// WithLabels adds labels to the counter
	WithLabels(labels ...MetricLabel) GeoGauge
}

GeoGauge extends the SimpleGeoGauge interface by adding a WithLabels function to create a copy of the counter that is primed with a set of labels.

type Metric

type Metric struct {
	// Name is the name for the metric.
	Name string

	// Help is the help text for this metric.
	Help string

	// Unit describes the unit of the metric.
	Unit string

	// Created describes the time the metric was created. This is important for counters.
	Created time.Time

	// Type describes how the metric behaves.
	Type MetricType
}

Metric is a descriptor for metrics.

func (Metric) String

func (metric Metric) String() string

String formats a metric as the OpenMetrics metadata

type MetricLabel

type MetricLabel struct {
	// contains filtered or unexported fields
}

MetricLabel is a struct that can be used with the metrics to pass additional labels. Create it using the Label function.

func Label

func Label(name string, value string) MetricLabel

Label creates a MetricLabel for use with the metric functions. Panics if name or value are empty. The name "country" is reserved.

func (MetricLabel) Name

func (m MetricLabel) Name() string

Name returns the name of the label.

func (MetricLabel) Value

func (m MetricLabel) Value() string

Value returns the value of the label.

type MetricType

type MetricType string

MetricType is the enum for tye types of metrics supported

const (
	// MetricTypeCounter is a testdata type that contains ever increasing numbers from the start of the server.
	MetricTypeCounter MetricType = "counter"

	// MetricTypeGauge is a metric type that can increase or decrease depending on the current value.
	MetricTypeGauge MetricType = "gauge"
)

type MetricValue

type MetricValue struct {
	// Name contains the name of the value.
	Name string

	// Labels contains a key-value map of labels to which the Value is specific.
	Labels map[string]string

	// Value contains the specific value stored.
	Value float64
}

MetricValue is a structure that contains a value for a specific metric name and set of values.

func (MetricValue) CombinedName

func (metricValue MetricValue) CombinedName() string

CombinedName returns the name and labels combined.

func (MetricValue) String

func (metricValue MetricValue) String() string

String creates a string out of the name, labels, and value.

type SimpleCounter

type SimpleCounter interface {
	// Increment increments the counter by 1
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	Increment(labels ...MetricLabel)

	// IncrementBy increments the counter by the specified number. Only returns an error if the passed by parameter is
	//             negative.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	IncrementBy(by float64, labels ...MetricLabel) error
}

SimpleCounter is a simple counter that can only be incremented.

type SimpleGauge

type SimpleGauge interface {
	// Increment increments the counter by 1.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	Increment(labels ...MetricLabel)

	// IncrementBy increments the counter by the specified number.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	IncrementBy(by float64, labels ...MetricLabel)

	// Decrement decreases the metric by 1.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	Decrement(labels ...MetricLabel)

	// DecrementBy decreases the metric by the specified value.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	DecrementBy(by float64, labels ...MetricLabel)

	// Set sets the value of the metric to an exact value.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	Set(value float64, labels ...MetricLabel)
}

SimpleGauge is a metric that can be incremented and decremented.

type SimpleGeoCounter

type SimpleGeoCounter interface {
	// Increment increments the counter for the country from the specified ip by 1.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	Increment(ip net.IP, labels ...MetricLabel)

	// IncrementBy increments the counter for the country from the specified ip by the specified value.
	//             Only returns an error if the passed by parameter is negative.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	IncrementBy(ip net.IP, by float64, labels ...MetricLabel) error
}

SimpleGeoCounter is a simple counter that can only be incremented and is labeled with the country from a GeoIP

lookup.

type SimpleGeoGauge

type SimpleGeoGauge interface {
	// Increment increments the counter for the country from the specified ip by 1.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	Increment(ip net.IP, labels ...MetricLabel)

	// IncrementBy increments the counter for the country from the specified ip by the specified value.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	IncrementBy(ip net.IP, by float64, labels ...MetricLabel)

	// Decrement decreases the value for the country looked up from the specified IP by 1.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	Decrement(ip net.IP, labels ...MetricLabel)

	// DecrementBy decreases the value for the country looked up from the specified IP by the specified value.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	DecrementBy(ip net.IP, by float64, labels ...MetricLabel)

	// Set sets the value of the metric for the country looked up from the specified IP.
	//
	// - labels is a set of labels to apply. Can be created using the Label function.
	Set(ip net.IP, value float64, labels ...MetricLabel)
}

SimpleGeoGauge is a metric that can be incremented and decremented and is labeled by the country from a GeoIP lookup.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL