or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

assets.mdconfig.mdexpfmt.mdhelpers-templates.mdindex.mdmodel.mdpromslog-flag.mdpromslog.mdroute.mdserver.mdversion.md
tile.json

model.mddocs/

Model Package

The model package provides common data structures shared across Prometheus components and libraries. It includes types for metrics, labels, time handling, values, alerts, and silences.

Import

import "github.com/prometheus/common/model"

Overview

This package defines the core data structures used throughout the Prometheus ecosystem for representing metrics, labels, timestamps, and alert information. It provides standardized types with validation, serialization, and manipulation methods.

Constants

Label Constants

const (
    AlertNameLabel      = "alertname"
    ExportedLabelPrefix = "exported_"
    MetricNameLabel     = "__name__"
    MetricTypeLabel     = "__type__"
    MetricUnitLabel     = "__unit__"
    SchemeLabel         = "__scheme__"
    AddressLabel        = "__address__"
    MetricsPathLabel    = "__metrics_path__"
    ScrapeIntervalLabel = "__scrape_interval__"
    ScrapeTimeoutLabel  = "__scrape_timeout__"
    ReservedLabelPrefix = "__"
    MetaLabelPrefix     = "__meta_"
    TmpLabelPrefix      = "__tmp_"
    ParamLabelPrefix    = "__param_"
    JobLabel            = "job"
    InstanceLabel       = "instance"
    BucketLabel         = "le"
    QuantileLabel       = "quantile"
)

Standard label names used in Prometheus.

Time Constants

const (
    Earliest = Time(math.MinInt64)
    Latest   = Time(math.MaxInt64)
)

Special time values representing the earliest and latest possible times.

Escaping Constants

const (
    EscapingKey       = "escaping"
    AllowUTF8         = "allow-utf-8"
    EscapeUnderscores = "underscores"
    EscapeDots        = "dots"
    EscapeValues      = "values"
)

Constants for metric name escaping schemes.

Signature Constants

const SeparatorByte byte = 255

Byte used to separate label name-value pairs when computing signatures.

Variables

var LabelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")

Regular expression for validating legacy label names.

var MetricNameRE = regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`)

Regular expression for validating legacy metric names.

var NameValidationScheme = UTF8Validation

Global default validation scheme for metric and label names.

var NameEscapingScheme = UnderscoreEscaping

Global default escaping scheme for metric and label names.

var ZeroSample = Sample{Timestamp: Earliest}

Zero value for Sample type.

var ZeroSamplePair = SamplePair{Timestamp: Earliest}

Zero value for SamplePair type.

Time Types

Time

type Time int64

Represents time as the number of milliseconds since the Unix epoch (January 1, 1970 UTC).

Methods

func (t Time) Equal(o Time) bool

Returns true if t and o represent the same time.

func (t Time) Before(o Time) bool

Returns true if t is before o.

func (t Time) After(o Time) bool

Returns true if t is after o.

func (t Time) Add(d time.Duration) Time

Returns the time t + d.

func (t Time) Sub(o Time) time.Duration

Returns the duration t - o.

func (t Time) Time() time.Time

Converts to standard Go time.Time.

func (t Time) Unix() int64

Returns t as Unix time in seconds.

func (t Time) UnixNano() int64

Returns t as Unix time in nanoseconds.

func (t Time) String() string

Returns string representation of the time.

func (t Time) MarshalJSON() ([]byte, error)

Marshals time as JSON number (Unix timestamp in seconds with millisecond precision).

func (t *Time) UnmarshalJSON(b []byte) error

Unmarshals time from JSON.

Interval

type Interval struct {
    Start Time
    End   Time
}

Represents a time interval with start and end times.

Duration

type Duration time.Duration

Duration with custom marshaling supporting y/w/d/h/m/s/ms units.

Methods

func (d *Duration) Set(s string) error

Parses and sets the duration from string.

func (d Duration) Type() string

Returns the type name "duration".

func (d Duration) String() string

Returns string representation with units.

func (d Duration) MarshalJSON() ([]byte, error)

Marshals as JSON string.

func (d *Duration) UnmarshalJSON(bytes []byte) error

Unmarshals from JSON.

func (d Duration) MarshalText() ([]byte, error)

Marshals as text.

func (d *Duration) UnmarshalText(text []byte) error

Unmarshals from text.

func (d Duration) MarshalYAML() (interface{}, error)

Marshals as YAML.

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error

Unmarshals from YAML.

Label Types

LabelName

type LabelName string

Represents the name of a label.

Methods

func (ln LabelName) IsValid() bool

Returns true if label name matches current validation scheme. Deprecated: use ValidationScheme.IsValidLabelName instead.

func (ln LabelName) IsValidLegacy() bool

Returns true if label name matches legacy validation pattern. Deprecated: use ValidationScheme.IsValidLabelName instead.

func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error

Unmarshals from YAML.

func (ln *LabelName) UnmarshalJSON(b []byte) error

Unmarshals from JSON.

LabelValue

type LabelValue string

Represents the value of a label.

Methods

func (lv LabelValue) IsValid() bool

Returns true if the value is valid UTF-8.

LabelNames

type LabelNames []LabelName

Sortable slice of label names.

Methods

func (l LabelNames) Len() int

Returns the number of label names.

func (l LabelNames) Less(i, j int) bool

Compares two label names for sorting.

func (l LabelNames) Swap(i, j int)

Swaps two label names.

func (l LabelNames) String() string

Returns string representation.

LabelValues

type LabelValues []LabelValue

Sortable slice of label values.

Methods

func (l LabelValues) Len() int
func (l LabelValues) Less(i, j int) bool
func (l LabelValues) Swap(i, j int)

LabelPair

type LabelPair struct {
    Name  LabelName
    Value LabelValue
}

Represents a name-value pair for a label.

LabelPairs

type LabelPairs []*LabelPair

Sortable slice of label pairs.

Methods

func (l LabelPairs) Len() int
func (l LabelPairs) Less(i, j int) bool
func (l LabelPairs) Swap(i, j int)

LabelSet

type LabelSet map[LabelName]LabelValue

Collection of label name-value pairs.

Methods

func (ls LabelSet) Validate() error

Checks if all label names and values are valid.

func (ls LabelSet) Equal(o LabelSet) bool

Returns true if ls and o contain exactly the same key-value pairs.

func (ls LabelSet) Before(o LabelSet) bool

Compares label sets lexicographically.

func (ls LabelSet) Clone() LabelSet

Returns a copy of the label set.

func (ls LabelSet) Merge(other LabelSet) LabelSet

Returns a new label set with labels from both ls and other. Values from other take precedence.

func (ls LabelSet) Fingerprint() Fingerprint

Returns a fingerprint for the label set.

func (ls LabelSet) FastFingerprint() Fingerprint

Returns a fingerprint using a faster algorithm (may have more collisions).

func (ls *LabelSet) UnmarshalJSON(b []byte) error

Unmarshals from JSON.

func (ls LabelSet) String() string

Returns string representation in format {foo="bar", more="less"}.

Metric Types

Metric

type Metric LabelSet

Metric is a LabelSet with additional metric-specific methods. The metric name is stored in the special __name__ label.

Methods

func (m Metric) Equal(o Metric) bool

Returns true if metrics have identical label sets.

func (m Metric) Before(o Metric) bool

Compares metrics lexicographically.

func (m Metric) Clone() Metric

Returns a copy of the metric.

func (m Metric) String() string

Returns string representation.

func (m Metric) Fingerprint() Fingerprint

Returns a fingerprint for the metric.

func (m Metric) FastFingerprint() Fingerprint

Returns a fingerprint using a faster algorithm.

MetricType

type MetricType string

Represents the type of a metric.

const (
    MetricTypeCounter        = MetricType("counter")
    MetricTypeGauge          = MetricType("gauge")
    MetricTypeHistogram      = MetricType("histogram")
    MetricTypeGaugeHistogram = MetricType("gaugehistogram")
    MetricTypeSummary        = MetricType("summary")
    MetricTypeInfo           = MetricType("info")
    MetricTypeStateset       = MetricType("stateset")
    MetricTypeUnknown        = MetricType("unknown")
)

Fingerprint Types

Fingerprint

type Fingerprint uint64

Unique identifier for metric/label combinations.

Methods

func (f Fingerprint) String() string

Returns fingerprint as hexadecimal string.

Fingerprints

type Fingerprints []Fingerprint

Sortable slice of fingerprints.

Methods

func (f Fingerprints) Len() int
func (f Fingerprints) Less(i, j int) bool
func (f Fingerprints) Swap(i, j int)

FingerprintSet

type FingerprintSet map[Fingerprint]struct{}

Set of unique fingerprints.

Methods

func (s FingerprintSet) Equal(o FingerprintSet) bool

Returns true if both sets contain the same elements.

func (s FingerprintSet) Intersection(o FingerprintSet) FingerprintSet

Returns a new set containing elements in both s and o.

Sample Types

SampleValue

type SampleValue float64

Represents the value of a sample.

Methods

func (v SampleValue) MarshalJSON() ([]byte, error)

Marshals as JSON string.

func (v *SampleValue) UnmarshalJSON(b []byte) error

Unmarshals from JSON.

func (v SampleValue) Equal(o SampleValue) bool

Returns true if values are equal or both are NaN.

func (v SampleValue) String() string

Returns string representation.

SamplePair

type SamplePair struct {
    Timestamp Time
    Value     SampleValue
}

Represents a timestamp and value pair.

Methods

func (s SamplePair) MarshalJSON() ([]byte, error)

Marshals as JSON array [timestamp, value].

func (s *SamplePair) UnmarshalJSON(b []byte) error

Unmarshals from JSON.

func (s *SamplePair) Equal(o *SamplePair) bool

Returns true if pairs are equal.

func (s SamplePair) String() string

Returns string representation.

Sample

type Sample struct {
    Metric    Metric
    Value     SampleValue
    Timestamp Time
    Histogram *SampleHistogram
}

Represents a single sample with metric identifier, value, and timestamp.

Methods

func (s *Sample) Equal(o *Sample) bool

Returns true if samples are equal.

func (s Sample) String() string

Returns string representation.

func (s Sample) MarshalJSON() ([]byte, error)

Marshals as JSON.

func (s *Sample) UnmarshalJSON(b []byte) error

Unmarshals from JSON.

Samples

type Samples []*Sample

Sortable slice of samples.

Methods

func (s Samples) Len() int
func (s Samples) Less(i, j int) bool
func (s Samples) Swap(i, j int)
func (s Samples) Equal(o Samples) bool

Returns true if all samples are equal.

Histogram Types

FloatString

type FloatString float64

Float that marshals as a string for precision.

Methods

func (v FloatString) String() string
func (v FloatString) MarshalJSON() ([]byte, error)
func (v *FloatString) UnmarshalJSON(b []byte) error

HistogramBucket

type HistogramBucket struct {
    Boundaries int32
    Lower      FloatString
    Upper      FloatString
    Count      FloatString
}

Represents a single histogram bucket.

Methods

func (s HistogramBucket) MarshalJSON() ([]byte, error)
func (s *HistogramBucket) UnmarshalJSON(buf []byte) error
func (s *HistogramBucket) Equal(o *HistogramBucket) bool
func (s HistogramBucket) String() string

HistogramBuckets

type HistogramBuckets []*HistogramBucket

Slice of histogram buckets.

Methods

func (s HistogramBuckets) Equal(o HistogramBuckets) bool

SampleHistogram

type SampleHistogram struct {
    Count   FloatString
    Sum     FloatString
    Buckets HistogramBuckets
}

Represents a histogram sample.

Methods

func (s SampleHistogram) String() string
func (s *SampleHistogram) Equal(o *SampleHistogram) bool

SampleHistogramPair

type SampleHistogramPair struct {
    Timestamp Time
    Histogram *SampleHistogram
}

Represents a timestamp and histogram pair.

Methods

func (s SampleHistogramPair) MarshalJSON() ([]byte, error)
func (s *SampleHistogramPair) UnmarshalJSON(buf []byte) error
func (s SampleHistogramPair) String() string
func (s *SampleHistogramPair) Equal(o *SampleHistogramPair) bool

Stream and Query Result Types

SampleStream

type SampleStream struct {
    Metric     Metric
    Values     []SamplePair
    Histograms []SampleHistogramPair
}

Represents a stream of samples for a single metric.

Methods

func (ss SampleStream) String() string
func (ss SampleStream) MarshalJSON() ([]byte, error)
func (ss *SampleStream) UnmarshalJSON(b []byte) error

Scalar

type Scalar struct {
    Value     SampleValue
    Timestamp Time
}

Represents a scalar value with timestamp.

Methods

func (s Scalar) String() string
func (s Scalar) MarshalJSON() ([]byte, error)
func (s *Scalar) UnmarshalJSON(b []byte) error

String

type String struct {
    Value     string
    Timestamp Time
}

Represents a string value with timestamp.

Methods

func (s *String) String() string
func (s String) MarshalJSON() ([]byte, error)
func (s *String) UnmarshalJSON(b []byte) error

Vector

type Vector []*Sample

Sortable vector of samples.

Methods

func (vec Vector) String() string
func (vec Vector) Len() int
func (vec Vector) Swap(i, j int)
func (vec Vector) Less(i, j int) bool
func (vec Vector) Equal(o Vector) bool

Matrix

type Matrix []*SampleStream

Sortable matrix of sample streams.

Methods

func (m Matrix) Len() int
func (m Matrix) Less(i, j int) bool
func (m Matrix) Swap(i, j int)
func (m Matrix) String() string

ValueType

type ValueType int

Represents the type of a query result value.

const (
    ValNone   ValueType = iota
    ValScalar
    ValVector
    ValMatrix
    ValString
)

Methods

func (v ValueType) MarshalJSON() ([]byte, error)
func (v *ValueType) UnmarshalJSON(b []byte) error
func (v ValueType) String() string

Value Interface

type Value interface {
    Type() ValueType
    String() string
}

Interface for query result values. Implemented by Matrix, Vector, Scalar, and String.

Alert Types

AlertStatus

type AlertStatus string

Status of an alert.

const (
    AlertFiring   AlertStatus = "firing"
    AlertResolved AlertStatus = "resolved"
)

Alert

type Alert struct {
    Labels       LabelSet
    Annotations  LabelSet
    StartsAt     time.Time
    EndsAt       time.Time
    GeneratorURL string
}

Represents a Prometheus alert.

Methods

func (a *Alert) Name() string

Returns the alert name from the "alertname" label.

func (a *Alert) Fingerprint() Fingerprint

Returns unique hash for the alert based on its labels.

func (a *Alert) String() string

Returns string representation.

func (a *Alert) Resolved() bool

Returns true if the alert is resolved.

func (a *Alert) ResolvedAt(ts time.Time) bool

Returns true if alert is resolved at the given time.

func (a *Alert) Status() AlertStatus

Returns the current status.

func (a *Alert) StatusAt(ts time.Time) AlertStatus

Returns status at the given time.

func (a *Alert) Validate() error

Validates alert data.

Alerts

type Alerts []*Alert

Slice of alerts with sorting and aggregation methods.

Methods

func (as Alerts) Len() int
func (as Alerts) Swap(i, j int)
func (as Alerts) Less(i, j int) bool
func (as Alerts) HasFiring() bool

Returns true if any alert is not resolved.

func (as Alerts) HasFiringAt(ts time.Time) bool

Returns true if any alert is not resolved at time ts.

func (as Alerts) Status() AlertStatus

Returns StatusFiring if at least one alert is firing.

func (as Alerts) StatusAt(ts time.Time) AlertStatus

Returns status at given time.

Silence Types

Matcher

type Matcher struct {
    Name    LabelName
    Value   string
    IsRegex bool
}

Matcher for label values in silences.

Methods

func (m *Matcher) UnmarshalJSON(b []byte) error
func (m *Matcher) Validate() error

Silence

type Silence struct {
    ID        uint64
    Matchers  []*Matcher
    StartsAt  time.Time
    EndsAt    time.Time
    CreatedAt time.Time
    CreatedBy string
    Comment   string
}

Represents an alert silence.

Methods

func (s *Silence) Validate() error

Validates silence data.

Validation and Escaping Types

ValidationScheme

type ValidationScheme int

Validation scheme for metric and label names.

const (
    UnsetValidation ValidationScheme = iota
    LegacyValidation
    UTF8Validation
)

Methods

func (s ValidationScheme) String() string
func (s ValidationScheme) MarshalYAML() (any, error)
func (s *ValidationScheme) UnmarshalYAML(unmarshal func(any) error) error
func (s ValidationScheme) MarshalJSON() ([]byte, error)
func (s *ValidationScheme) UnmarshalJSON(bytes []byte) error
func (s *ValidationScheme) Set(text string) error
func (s ValidationScheme) IsValidMetricName(metricName string) bool
func (s ValidationScheme) IsValidLabelName(labelName string) bool
func (s ValidationScheme) Type() string

EscapingScheme

type EscapingScheme int

Scheme for escaping metric and label names.

const (
    NoEscaping EscapingScheme = iota
    UnderscoreEscaping
    DotsEscaping
    ValueEncodingEscaping
)

Methods

func (s EscapingScheme) String() string

Functions

Metric Validation Functions (Deprecated)

func IsValidMetricName(n LabelValue) bool

Returns true if the metric name matches the current validation scheme (determined by NameValidationScheme).

Deprecated: This function should not be used and might be removed in the future. Use ValidationScheme.IsValidMetricName instead. This function relies on the global NameValidationScheme variable which is discouraged. For legacy validation, use LegacyValidation.IsValidMetricName. For UTF-8 validation, use UTF8Validation.IsValidMetricName.

func IsValidLegacyMetricName(n string) bool

Returns true if the metric name conforms to the legacy validation scheme (matching the pattern ^[a-zA-Z_:][a-zA-Z0-9_:]*$), regardless of the value of NameValidationScheme. This implementation uses a fast hardcoded check rather than the MetricNameRE regular expression.

Deprecated: This function should not be used and might be removed in the future. Use LegacyValidation.IsValidMetricName instead for explicit legacy validation.

Time Functions

func Now() Time

Returns the current time as model.Time.

func TimeFromUnix(t int64) Time

Creates Time from Unix time in seconds.

func TimeFromUnixNano(t int64) Time

Creates Time from Unix time in nanoseconds.

Duration Functions

func ParseDuration(s string) (Duration, error)

Parses duration string with y/w/d/h/m/s/ms units.

func ParseDurationAllowNegative(s string) (Duration, error)

Parses duration string allowing negative values.

Fingerprint Functions

func FingerprintFromString(s string) (Fingerprint, error)

Transforms string into Fingerprint.

func ParseFingerprint(s string) (Fingerprint, error)

Parses input string into fingerprint.

Escaping Functions

func ToEscapingScheme(s string) (EscapingScheme, error)

Converts string to EscapingScheme.

func EscapeName(name string, scheme EscapingScheme) string

Escapes name according to scheme.

func UnescapeName(name string, scheme EscapingScheme) string

Unescapes name according to scheme.

func EscapeMetricFamily(v *dto.MetricFamily, scheme EscapingScheme) *dto.MetricFamily

Escapes metric family names according to scheme.

Signature Functions

func LabelsToSignature(labels map[string]string) uint64

Creates signature from label map.

func SignatureForLabels(m Metric, labels ...LabelName) uint64

Creates signature for specific labels of a metric.

func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64

Creates signature excluding specific labels.

Usage Examples

Working with Time

package main

import (
    "fmt"
    "time"

    "github.com/prometheus/common/model"
)

func main() {
    // Current time
    now := model.Now()
    fmt.Println("Now:", now)

    // Convert from standard time
    stdTime := time.Now()
    promTime := model.TimeFromUnixNano(stdTime.UnixNano())
    fmt.Println("Prometheus time:", promTime)

    // Time arithmetic
    oneHourLater := now.Add(time.Hour)
    fmt.Println("One hour later:", oneHourLater)

    // Duration between times
    duration := oneHourLater.Sub(now)
    fmt.Println("Duration:", duration)
}

Working with Labels and Metrics

package main

import (
    "fmt"

    "github.com/prometheus/common/model"
)

func main() {
    // Create a metric with labels
    metric := model.Metric{
        model.MetricNameLabel: "http_requests_total",
        "method":              "GET",
        "status":              "200",
    }

    fmt.Println("Metric:", metric)

    // Get fingerprint
    fp := metric.Fingerprint()
    fmt.Printf("Fingerprint: %s\n", fp)

    // Create a label set
    labels := model.LabelSet{
        "instance": "localhost:9090",
        "job":      "prometheus",
    }

    // Merge labels
    allLabels := metric.Merge(model.Metric(labels))
    fmt.Println("Merged:", allLabels)
}

Working with Samples

package main

import (
    "fmt"

    "github.com/prometheus/common/model"
)

func main() {
    // Create a sample
    sample := &model.Sample{
        Metric: model.Metric{
            model.MetricNameLabel: "cpu_usage",
            "cpu":                 "0",
        },
        Value:     75.5,
        Timestamp: model.Now(),
    }

    fmt.Println("Sample:", sample)

    // Create a vector of samples
    vector := model.Vector{
        sample,
        &model.Sample{
            Metric: model.Metric{
                model.MetricNameLabel: "cpu_usage",
                "cpu":                 "1",
            },
            Value:     82.3,
            Timestamp: model.Now(),
        },
    }

    // Sort the vector
    sort.Sort(vector)
}

Working with Durations

package main

import (
    "fmt"

    "github.com/prometheus/common/model"
)

func main() {
    // Parse Prometheus-style duration
    d, err := model.ParseDuration("1h30m")
    if err != nil {
        panic(err)
    }
    fmt.Println("Duration:", d)

    // Convert to standard time.Duration
    stdDuration := time.Duration(d)
    fmt.Println("Standard duration:", stdDuration)

    // More complex duration
    d2, _ := model.ParseDuration("7d")
    fmt.Println("One week:", d2)
}

Working with Alerts

package main

import (
    "fmt"
    "time"

    "github.com/prometheus/common/model"
)

func main() {
    alert := &model.Alert{
        Labels: model.LabelSet{
            model.AlertNameLabel: "HighCPU",
            "instance":           "server1",
            "severity":           "warning",
        },
        Annotations: model.LabelSet{
            "summary":     "High CPU usage detected",
            "description": "CPU usage is above 80%",
        },
        StartsAt:     time.Now().Add(-10 * time.Minute),
        EndsAt:       time.Time{}, // Still firing
        GeneratorURL: "http://prometheus:9090/graph?g0.expr=...",
    }

    fmt.Println("Alert name:", alert.Name())
    fmt.Println("Status:", alert.Status())
    fmt.Println("Firing:", !alert.Resolved())
}

Validation and Escaping

package main

import (
    "fmt"

    "github.com/prometheus/common/model"
)

func main() {
    // Validate metric name
    scheme := model.UTF8Validation
    if scheme.IsValidMetricName("http_requests_total") {
        fmt.Println("Valid metric name")
    }

    // Escape special characters
    escaped := model.EscapeName("metric.with.dots", model.UnderscoreEscaping)
    fmt.Println("Escaped:", escaped) // metric_with_dots

    // Unescape
    original := model.UnescapeName(escaped, model.UnderscoreEscaping)
    fmt.Println("Original:", original)
}