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 "github.com/prometheus/common/model"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.
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.
const (
Earliest = Time(math.MinInt64)
Latest = Time(math.MaxInt64)
)Special time values representing the earliest and latest possible times.
const (
EscapingKey = "escaping"
AllowUTF8 = "allow-utf-8"
EscapeUnderscores = "underscores"
EscapeDots = "dots"
EscapeValues = "values"
)Constants for metric name escaping schemes.
const SeparatorByte byte = 255Byte used to separate label name-value pairs when computing signatures.
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 = UTF8ValidationGlobal default validation scheme for metric and label names.
var NameEscapingScheme = UnderscoreEscapingGlobal 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.
type Time int64Represents time as the number of milliseconds since the Unix epoch (January 1, 1970 UTC).
func (t Time) Equal(o Time) boolReturns true if t and o represent the same time.
func (t Time) Before(o Time) boolReturns true if t is before o.
func (t Time) After(o Time) boolReturns true if t is after o.
func (t Time) Add(d time.Duration) TimeReturns the time t + d.
func (t Time) Sub(o Time) time.DurationReturns the duration t - o.
func (t Time) Time() time.TimeConverts to standard Go time.Time.
func (t Time) Unix() int64Returns t as Unix time in seconds.
func (t Time) UnixNano() int64Returns t as Unix time in nanoseconds.
func (t Time) String() stringReturns 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) errorUnmarshals time from JSON.
type Interval struct {
Start Time
End Time
}Represents a time interval with start and end times.
type Duration time.DurationDuration with custom marshaling supporting y/w/d/h/m/s/ms units.
func (d *Duration) Set(s string) errorParses and sets the duration from string.
func (d Duration) Type() stringReturns the type name "duration".
func (d Duration) String() stringReturns string representation with units.
func (d Duration) MarshalJSON() ([]byte, error)Marshals as JSON string.
func (d *Duration) UnmarshalJSON(bytes []byte) errorUnmarshals from JSON.
func (d Duration) MarshalText() ([]byte, error)Marshals as text.
func (d *Duration) UnmarshalText(text []byte) errorUnmarshals from text.
func (d Duration) MarshalYAML() (interface{}, error)Marshals as YAML.
func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) errorUnmarshals from YAML.
type LabelName stringRepresents the name of a label.
func (ln LabelName) IsValid() boolReturns true if label name matches current validation scheme. Deprecated: use ValidationScheme.IsValidLabelName instead.
func (ln LabelName) IsValidLegacy() boolReturns true if label name matches legacy validation pattern. Deprecated: use ValidationScheme.IsValidLabelName instead.
func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) errorUnmarshals from YAML.
func (ln *LabelName) UnmarshalJSON(b []byte) errorUnmarshals from JSON.
type LabelValue stringRepresents the value of a label.
func (lv LabelValue) IsValid() boolReturns true if the value is valid UTF-8.
type LabelNames []LabelNameSortable slice of label names.
func (l LabelNames) Len() intReturns the number of label names.
func (l LabelNames) Less(i, j int) boolCompares two label names for sorting.
func (l LabelNames) Swap(i, j int)Swaps two label names.
func (l LabelNames) String() stringReturns string representation.
type LabelValues []LabelValueSortable slice of label values.
func (l LabelValues) Len() intfunc (l LabelValues) Less(i, j int) boolfunc (l LabelValues) Swap(i, j int)type LabelPair struct {
Name LabelName
Value LabelValue
}Represents a name-value pair for a label.
type LabelPairs []*LabelPairSortable slice of label pairs.
func (l LabelPairs) Len() intfunc (l LabelPairs) Less(i, j int) boolfunc (l LabelPairs) Swap(i, j int)type LabelSet map[LabelName]LabelValueCollection of label name-value pairs.
func (ls LabelSet) Validate() errorChecks if all label names and values are valid.
func (ls LabelSet) Equal(o LabelSet) boolReturns true if ls and o contain exactly the same key-value pairs.
func (ls LabelSet) Before(o LabelSet) boolCompares label sets lexicographically.
func (ls LabelSet) Clone() LabelSetReturns a copy of the label set.
func (ls LabelSet) Merge(other LabelSet) LabelSetReturns a new label set with labels from both ls and other. Values from other take precedence.
func (ls LabelSet) Fingerprint() FingerprintReturns a fingerprint for the label set.
func (ls LabelSet) FastFingerprint() FingerprintReturns a fingerprint using a faster algorithm (may have more collisions).
func (ls *LabelSet) UnmarshalJSON(b []byte) errorUnmarshals from JSON.
func (ls LabelSet) String() stringReturns string representation in format {foo="bar", more="less"}.
type Metric LabelSetMetric is a LabelSet with additional metric-specific methods. The metric name is stored in the special __name__ label.
func (m Metric) Equal(o Metric) boolReturns true if metrics have identical label sets.
func (m Metric) Before(o Metric) boolCompares metrics lexicographically.
func (m Metric) Clone() MetricReturns a copy of the metric.
func (m Metric) String() stringReturns string representation.
func (m Metric) Fingerprint() FingerprintReturns a fingerprint for the metric.
func (m Metric) FastFingerprint() FingerprintReturns a fingerprint using a faster algorithm.
type MetricType stringRepresents 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")
)type Fingerprint uint64Unique identifier for metric/label combinations.
func (f Fingerprint) String() stringReturns fingerprint as hexadecimal string.
type Fingerprints []FingerprintSortable slice of fingerprints.
func (f Fingerprints) Len() intfunc (f Fingerprints) Less(i, j int) boolfunc (f Fingerprints) Swap(i, j int)type FingerprintSet map[Fingerprint]struct{}Set of unique fingerprints.
func (s FingerprintSet) Equal(o FingerprintSet) boolReturns true if both sets contain the same elements.
func (s FingerprintSet) Intersection(o FingerprintSet) FingerprintSetReturns a new set containing elements in both s and o.
type SampleValue float64Represents the value of a sample.
func (v SampleValue) MarshalJSON() ([]byte, error)Marshals as JSON string.
func (v *SampleValue) UnmarshalJSON(b []byte) errorUnmarshals from JSON.
func (v SampleValue) Equal(o SampleValue) boolReturns true if values are equal or both are NaN.
func (v SampleValue) String() stringReturns string representation.
type SamplePair struct {
Timestamp Time
Value SampleValue
}Represents a timestamp and value pair.
func (s SamplePair) MarshalJSON() ([]byte, error)Marshals as JSON array [timestamp, value].
func (s *SamplePair) UnmarshalJSON(b []byte) errorUnmarshals from JSON.
func (s *SamplePair) Equal(o *SamplePair) boolReturns true if pairs are equal.
func (s SamplePair) String() stringReturns string representation.
type Sample struct {
Metric Metric
Value SampleValue
Timestamp Time
Histogram *SampleHistogram
}Represents a single sample with metric identifier, value, and timestamp.
func (s *Sample) Equal(o *Sample) boolReturns true if samples are equal.
func (s Sample) String() stringReturns string representation.
func (s Sample) MarshalJSON() ([]byte, error)Marshals as JSON.
func (s *Sample) UnmarshalJSON(b []byte) errorUnmarshals from JSON.
type Samples []*SampleSortable slice of samples.
func (s Samples) Len() intfunc (s Samples) Less(i, j int) boolfunc (s Samples) Swap(i, j int)func (s Samples) Equal(o Samples) boolReturns true if all samples are equal.
type FloatString float64Float that marshals as a string for precision.
func (v FloatString) String() stringfunc (v FloatString) MarshalJSON() ([]byte, error)func (v *FloatString) UnmarshalJSON(b []byte) errortype HistogramBucket struct {
Boundaries int32
Lower FloatString
Upper FloatString
Count FloatString
}Represents a single histogram bucket.
func (s HistogramBucket) MarshalJSON() ([]byte, error)func (s *HistogramBucket) UnmarshalJSON(buf []byte) errorfunc (s *HistogramBucket) Equal(o *HistogramBucket) boolfunc (s HistogramBucket) String() stringtype HistogramBuckets []*HistogramBucketSlice of histogram buckets.
func (s HistogramBuckets) Equal(o HistogramBuckets) booltype SampleHistogram struct {
Count FloatString
Sum FloatString
Buckets HistogramBuckets
}Represents a histogram sample.
func (s SampleHistogram) String() stringfunc (s *SampleHistogram) Equal(o *SampleHistogram) booltype SampleHistogramPair struct {
Timestamp Time
Histogram *SampleHistogram
}Represents a timestamp and histogram pair.
func (s SampleHistogramPair) MarshalJSON() ([]byte, error)func (s *SampleHistogramPair) UnmarshalJSON(buf []byte) errorfunc (s SampleHistogramPair) String() stringfunc (s *SampleHistogramPair) Equal(o *SampleHistogramPair) booltype SampleStream struct {
Metric Metric
Values []SamplePair
Histograms []SampleHistogramPair
}Represents a stream of samples for a single metric.
func (ss SampleStream) String() stringfunc (ss SampleStream) MarshalJSON() ([]byte, error)func (ss *SampleStream) UnmarshalJSON(b []byte) errortype Scalar struct {
Value SampleValue
Timestamp Time
}Represents a scalar value with timestamp.
func (s Scalar) String() stringfunc (s Scalar) MarshalJSON() ([]byte, error)func (s *Scalar) UnmarshalJSON(b []byte) errortype String struct {
Value string
Timestamp Time
}Represents a string value with timestamp.
func (s *String) String() stringfunc (s String) MarshalJSON() ([]byte, error)func (s *String) UnmarshalJSON(b []byte) errortype Vector []*SampleSortable vector of samples.
func (vec Vector) String() stringfunc (vec Vector) Len() intfunc (vec Vector) Swap(i, j int)func (vec Vector) Less(i, j int) boolfunc (vec Vector) Equal(o Vector) booltype Matrix []*SampleStreamSortable matrix of sample streams.
func (m Matrix) Len() intfunc (m Matrix) Less(i, j int) boolfunc (m Matrix) Swap(i, j int)func (m Matrix) String() stringtype ValueType intRepresents the type of a query result value.
const (
ValNone ValueType = iota
ValScalar
ValVector
ValMatrix
ValString
)func (v ValueType) MarshalJSON() ([]byte, error)func (v *ValueType) UnmarshalJSON(b []byte) errorfunc (v ValueType) String() stringtype Value interface {
Type() ValueType
String() string
}Interface for query result values. Implemented by Matrix, Vector, Scalar, and String.
type AlertStatus stringStatus of an alert.
const (
AlertFiring AlertStatus = "firing"
AlertResolved AlertStatus = "resolved"
)type Alert struct {
Labels LabelSet
Annotations LabelSet
StartsAt time.Time
EndsAt time.Time
GeneratorURL string
}Represents a Prometheus alert.
func (a *Alert) Name() stringReturns the alert name from the "alertname" label.
func (a *Alert) Fingerprint() FingerprintReturns unique hash for the alert based on its labels.
func (a *Alert) String() stringReturns string representation.
func (a *Alert) Resolved() boolReturns true if the alert is resolved.
func (a *Alert) ResolvedAt(ts time.Time) boolReturns true if alert is resolved at the given time.
func (a *Alert) Status() AlertStatusReturns the current status.
func (a *Alert) StatusAt(ts time.Time) AlertStatusReturns status at the given time.
func (a *Alert) Validate() errorValidates alert data.
type Alerts []*AlertSlice of alerts with sorting and aggregation methods.
func (as Alerts) Len() intfunc (as Alerts) Swap(i, j int)func (as Alerts) Less(i, j int) boolfunc (as Alerts) HasFiring() boolReturns true if any alert is not resolved.
func (as Alerts) HasFiringAt(ts time.Time) boolReturns true if any alert is not resolved at time ts.
func (as Alerts) Status() AlertStatusReturns StatusFiring if at least one alert is firing.
func (as Alerts) StatusAt(ts time.Time) AlertStatusReturns status at given time.
type Matcher struct {
Name LabelName
Value string
IsRegex bool
}Matcher for label values in silences.
func (m *Matcher) UnmarshalJSON(b []byte) errorfunc (m *Matcher) Validate() errortype Silence struct {
ID uint64
Matchers []*Matcher
StartsAt time.Time
EndsAt time.Time
CreatedAt time.Time
CreatedBy string
Comment string
}Represents an alert silence.
func (s *Silence) Validate() errorValidates silence data.
type ValidationScheme intValidation scheme for metric and label names.
const (
UnsetValidation ValidationScheme = iota
LegacyValidation
UTF8Validation
)func (s ValidationScheme) String() stringfunc (s ValidationScheme) MarshalYAML() (any, error)func (s *ValidationScheme) UnmarshalYAML(unmarshal func(any) error) errorfunc (s ValidationScheme) MarshalJSON() ([]byte, error)func (s *ValidationScheme) UnmarshalJSON(bytes []byte) errorfunc (s *ValidationScheme) Set(text string) errorfunc (s ValidationScheme) IsValidMetricName(metricName string) boolfunc (s ValidationScheme) IsValidLabelName(labelName string) boolfunc (s ValidationScheme) Type() stringtype EscapingScheme intScheme for escaping metric and label names.
const (
NoEscaping EscapingScheme = iota
UnderscoreEscaping
DotsEscaping
ValueEncodingEscaping
)func (s EscapingScheme) String() stringfunc IsValidMetricName(n LabelValue) boolReturns 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) boolReturns 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.
func Now() TimeReturns the current time as model.Time.
func TimeFromUnix(t int64) TimeCreates Time from Unix time in seconds.
func TimeFromUnixNano(t int64) TimeCreates Time from Unix time in nanoseconds.
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.
func FingerprintFromString(s string) (Fingerprint, error)Transforms string into Fingerprint.
func ParseFingerprint(s string) (Fingerprint, error)Parses input string into fingerprint.
func ToEscapingScheme(s string) (EscapingScheme, error)Converts string to EscapingScheme.
func EscapeName(name string, scheme EscapingScheme) stringEscapes name according to scheme.
func UnescapeName(name string, scheme EscapingScheme) stringUnescapes name according to scheme.
func EscapeMetricFamily(v *dto.MetricFamily, scheme EscapingScheme) *dto.MetricFamilyEscapes metric family names according to scheme.
func LabelsToSignature(labels map[string]string) uint64Creates signature from label map.
func SignatureForLabels(m Metric, labels ...LabelName) uint64Creates signature for specific labels of a metric.
func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64Creates signature excluding specific labels.
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)
}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)
}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)
}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)
}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())
}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)
}