metrics

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: BSD-3-Clause Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package metrics holds the counters, gauges and histograms of SPEC D60 and writes them in the Prometheus text format (version 0.0.4), by hand, with no client library.

A Registry owns the metrics and writes all of them, sorted by name and then by label values. A metric is made with a fixed list of label names. A label that has an allowed list folds every other value into "other", so that its values stay a closed set; a label with no list takes the value as it comes and is only for values the caller bounds (the route pattern of the http.ServeMux). No label carries a user, an ID, a path with an ID, an address or a token (SPEC D60).

Nothing here is global: serve makes one Registry and one Set and passes them to what reports into them. A nil Counter, Gauge, Histogram or vec accepts every call and does nothing, so a package that was given no metrics reports into nothing at no cost.

Index

Constants

View Source
const (
	NameHTTPRequests     = "clowder_http_requests_total"
	NameHTTPDuration     = "clowder_http_request_duration_seconds"
	NameSSEStreams       = "clowder_sse_streams_open"
	NameWebSockets       = "clowder_websockets_open"
	NameHubDropped       = "clowder_hub_dropped_total"
	NameLogins           = "clowder_logins_total"
	NameSSHCodes         = "clowder_ssh_codes_issued_total"
	NameLimitsRefused    = "clowder_limits_refused_total"
	NameCallsActive      = "clowder_calls_active"
	NameCallsTotal       = "clowder_calls_total"
	NameDBConnections    = "clowder_db_connections"
	NameDBWait           = "clowder_db_wait_total"
	NameDBWaitSeconds    = "clowder_db_wait_seconds_total"
	NameRedisReconnects  = "clowder_redis_reconnects_total"
	NameRedisPublished   = "clowder_redis_bridge_published_total"
	NameRedisReceived    = "clowder_redis_bridge_received_total"
	NameBuildInfo        = "clowder_build_info"
	NameGoroutines       = "go_goroutines"
	NameHeapAlloc        = "go_memstats_heap_alloc_bytes"
	NameHeapSys          = "go_memstats_heap_sys_bytes"
	NameGCCycles         = "go_gc_cycles_total"
	NameProcessStartTime = "process_start_time_seconds"
)

The names of the metrics of SPEC D60 and of step 23.2. They are the contract with the people who scrape and alert on them.

View Source
const (
	// WebSocketKindAPI is the kind of the user's WebSocket of the API and of
	// the call socket of the API.
	WebSocketKindAPI = "api"
	// WebSocketKindCall is the kind of the signalling socket of a call.
	WebSocketKindCall = "call"
	// LoginOK is a login that started a session.
	LoginOK = "ok"
	// LoginWrong is a wrong username or password.
	LoginWrong = "wrong"
	// LoginLimited is a login the limiter refused.
	LoginLimited = "limited"
	// LoginSSHCodeRequired is a right password of a user who must now give an
	// SSH sign-in code.
	LoginSSHCodeRequired = "ssh_code_required"
	// LoginSSHCodeWrong is a wrong SSH sign-in code.
	LoginSSHCodeWrong = "ssh_code_wrong"
	// LimitConnections is a stream or a WebSocket refused because the user
	// had the most live connections of the process (SPEC D62).
	LimitConnections = "connections"
	// LimitStaged is an upload refused because the user had the most staged
	// bytes (SPEC D62).
	LimitStaged = "staged"
	// LimitSignUp is a sign-up refused because the address had failed too
	// often, with an invitation token or a password (SPEC D62).
	LimitSignUp = "signup"
	// DropOverflow is a subscription closed because its buffer was full.
	DropOverflow = "overflow"
	// DropReconnect is a subscription closed because the bridge to Redis came
	// back after a break.
	DropReconnect = "reconnect"
	// PatternNone is the route pattern of a request no route matched.
	PatternNone = "none"
)

The values of the closed labels that the reporting packages use.

View Source
const ContentType = "text/plain; version=0.0.4; charset=utf-8"

ContentType is the media type of the Prometheus text format, version 0.0.4.

View Source
const Path = "/metrics"

Path is the path the metrics are served at.

Variables

View Source
var DurationBuckets = []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}

DurationBuckets are the upper bounds, in seconds, of the histogram of the duration of requests.

Functions

This section is empty.

Types

type Counter

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

Counter is a value that only goes up. Every method accepts a nil Counter and does nothing. It is safe for concurrent use.

func (*Counter) Add

func (c *Counter) Add(n uint64)

Add adds n.

func (*Counter) Inc

func (c *Counter) Inc()

Inc adds one.

func (*Counter) Value

func (c *Counter) Value() uint64

Value returns the count; 0 for a nil Counter.

type CounterVec

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

CounterVec is a counter with labels: one Counter for each combination of label values. Every method accepts a nil CounterVec.

func (*CounterVec) Preload

func (cv *CounterVec) Preload()

Preload makes the series of every combination of allowed values, so that they are written as 0 before they are used. It does nothing for a metric with an open label.

func (*CounterVec) With

func (cv *CounterVec) With(values ...string) *Counter

With returns the Counter of the label values, in the order of the labels. A value outside the allowed list of its label is counted as "other". With the wrong number of values it returns nil, which counts nothing.

type Gauge

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

Gauge is a whole number that goes up and down. Every method accepts a nil Gauge and does nothing. It is safe for concurrent use.

func (*Gauge) Add

func (g *Gauge) Add(n int64)

Add adds n, which may be negative.

func (*Gauge) Dec

func (g *Gauge) Dec()

Dec subtracts one.

func (*Gauge) Inc

func (g *Gauge) Inc()

Inc adds one.

func (*Gauge) Set

func (g *Gauge) Set(n int64)

Set sets the value.

func (*Gauge) Value

func (g *Gauge) Value() int64

Value returns the value; 0 for a nil Gauge.

type GaugeVec

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

GaugeVec is a gauge with labels. Every method accepts a nil GaugeVec.

func (*GaugeVec) Preload

func (gv *GaugeVec) Preload()

Preload makes the series of every combination of allowed values; see CounterVec.Preload.

func (*GaugeVec) With

func (gv *GaugeVec) With(values ...string) *Gauge

With returns the Gauge of the label values; see CounterVec.With.

type Histogram

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

Histogram counts observations in buckets. Every method accepts a nil Histogram and does nothing. It is safe for concurrent use.

func (*Histogram) Observe

func (h *Histogram) Observe(v float64)

Observe records one value. A NaN is ignored.

func (*Histogram) ObserveDuration

func (h *Histogram) ObserveDuration(d time.Duration)

ObserveDuration records a duration in seconds.

type HistogramVec

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

HistogramVec is a histogram with labels. Every method accepts a nil HistogramVec.

func (*HistogramVec) With

func (hv *HistogramVec) With(values ...string) *Histogram

With returns the Histogram of the label values; see CounterVec.With.

type Kind

type Kind string

Kind says how a metric behaves, as the TYPE line of the text format.

const (
	// KindCounter is a value that only goes up.
	KindCounter Kind = "counter"
	// KindGauge is a value that goes up and down.
	KindGauge Kind = "gauge"
	// KindHistogram is a distribution in buckets.
	KindHistogram Kind = "histogram"
)

The kinds of metric.

type Label

type Label struct {
	// Name is the label name: letters, digits and underscores, not starting
	// with a digit or with "__".
	Name string
	// Allowed is the closed set of values; empty means any value.
	Allowed []string
}

Label is the name of a label of a metric and, for a closed set of values, the values it may take. A value outside Allowed is written as "other". With no Allowed the value is taken as it is, so only a caller that bounds its values (the route pattern of the mux) uses that.

func L

func L(name string, allowed ...string) Label

L makes a Label. With allowed values it is a closed set; without, it is open.

type Registry

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

Registry owns the metrics and writes them. Make it with NewRegistry. It is safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry makes an empty registry.

func (*Registry) Handler

func (r *Registry) Handler(logger *slog.Logger) http.Handler

Handler serves the registry at GET Path and nothing else: any other path is 404 and any other method 405. The answer has the content type of the text format and Cache-Control: no-store. It asks for no login: the listener it belongs to is for a private network (SPEC D60). A nil logger discards the log.

func (*Registry) NewCounter

func (r *Registry) NewCounter(name, help string) (*Counter, error)

NewCounter makes a counter with no labels and adds it to the registry.

func (*Registry) NewCounterFunc

func (r *Registry) NewCounterFunc(name, help string, fn func() float64) error

NewCounterFunc adds a counter with no labels whose value is read when scraped.

func (*Registry) NewCounterVec

func (r *Registry) NewCounterVec(name, help string, labels ...Label) (*CounterVec, error)

NewCounterVec makes a counter with labels and adds it to the registry. By the conventions of Prometheus its name ends in _total. It fails with tagMetricNameInvalid, tagMetricLabelInvalid or tagMetricDuplicate.

func (*Registry) NewFunc

func (r *Registry) NewFunc(kind Kind, name, help string, labelNames []string, fn func() []Sample) error

NewFunc adds a counter or gauge whose samples fn returns each time the registry is written. labelNames name the labels of its samples (no allowed lists: the function is the program's own). A sample with the wrong number of label values is left out. It fails with tagMetricKindInvalid for any kind but KindCounter and KindGauge, and like NewCounterVec.

func (*Registry) NewGauge

func (r *Registry) NewGauge(name, help string) (*Gauge, error)

NewGauge makes a gauge with no labels and adds it to the registry.

func (*Registry) NewGaugeFunc

func (r *Registry) NewGaugeFunc(name, help string, fn func() float64) error

NewGaugeFunc adds a gauge with no labels whose value is read when scraped.

func (*Registry) NewGaugeVec

func (r *Registry) NewGaugeVec(name, help string, labels ...Label) (*GaugeVec, error)

NewGaugeVec makes a gauge with labels and adds it to the registry. It fails like NewCounterVec.

func (*Registry) NewHistogramVec

func (r *Registry) NewHistogramVec(name, help string, buckets []float64, labels ...Label) (*HistogramVec, error)

NewHistogramVec makes a histogram with labels and adds it to the registry. buckets are the upper bounds in seconds (or whatever the unit is), strictly increasing and finite; the +Inf bucket is added. It fails with tagBucketsInvalid for other bounds, and like NewCounterVec.

func (*Registry) WriteTo

func (r *Registry) WriteTo(w io.Writer) (int64, error)

WriteTo writes every metric in the Prometheus text format, sorted by metric name and then by label values. Metrics that are read when scraped run their functions here, outside the lock of the registry. It fails with tagWriteFailed when w does.

type Sample

type Sample struct {
	// Labels are the label values.
	Labels []string
	// Value is the value.
	Value float64
}

Sample is one value of a metric that is read when it is scraped, with its label values in the order of the labels of the metric.

type Set

type Set struct {
	// Registry holds all the metrics and writes them.
	Registry *Registry
	// HTTPRequests counts the requests that ended, by route pattern, method
	// and status class. Event streams and WebSockets are counted when they
	// end.
	HTTPRequests *CounterVec
	// HTTPDuration is the duration of the requests that are not streams or
	// WebSockets, by route pattern and method.
	HTTPDuration *HistogramVec
	// SSEStreams is the number of open event streams of the pages.
	SSEStreams *Gauge
	// WebSockets is the number of open WebSockets by kind: api (the user's
	// socket and the call socket of the API) is WebSocketKindAPI and the
	// signalling socket of a call is WebSocketKindCall.
	WebSockets *GaugeVec
	// HubDropped counts the subscriptions of the hub that it closed, by
	// reason: DropOverflow or DropReconnect.
	HubDropped *CounterVec
	// Logins counts the logins by result: LoginOK and the others.
	Logins *CounterVec
	// SSHCodes counts the sign-in codes the SSH server issued.
	SSHCodes *Counter
	// LimitsRefused counts the requests a per-user limit of SPEC D62 refused,
	// by limit: LimitConnections, LimitStaged or LimitSignUp.
	LimitsRefused *CounterVec
	// CallsTotal counts the calls whose media this process held, by how they
	// ended.
	CallsTotal *CounterVec
	// RedisReconnects, RedisPublished and RedisReceived are the counters of
	// the bridge to Redis. They are nil when Redis is not configured.
	RedisReconnects *Counter
	RedisPublished  *Counter
	RedisReceived   *Counter
}

Set is every metric Clowder reports, made in one Registry. serve makes it and passes it, or the metric a package reports into, to that package. A nil *Set is not valid, but every field is nil-safe: a package that was given no Set reports into nothing.

func NewSet

func NewSet(opts SetOptions) (*Set, error)

NewSet makes a Registry with the metrics of SPEC D60: the ones services report into, and the ones read when scraped (the Go runtime, the process start time and the build information). The pool of the database and the calls of the media server are added with RegisterPool and RegisterCalls, once they exist.

func (*Set) RegisterCalls

func (s *Set) RegisterCalls(active func() int) error

RegisterCalls adds clowder_calls_active, the calls whose home is this process, read from active when scraped.

func (*Set) RegisterPool

func (s *Set) RegisterPool(stats func() sql.DBStats) error

RegisterPool adds the metrics of the database pool, read from sql.DBStats when scraped: the connections by state (open, in_use, idle) and the number of waits for a connection and the seconds spent waiting.

type SetOptions

type SetOptions struct {
	// Version is the version shown by clowder_build_info; empty is "unknown".
	Version string
	// GoVersion is the Go version shown by clowder_build_info; empty is
	// runtime.Version().
	GoVersion string
	// Start is the start time of the process for process_start_time_seconds;
	// the zero time is now.
	Start time.Time
	// Redis makes the metrics of the bridge to Redis.
	Redis bool
}

SetOptions are the settings of NewSet.

Jump to

Keyboard shortcuts

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