v1

package
v0.313.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: Apache-2.0 Imports: 57 Imported by: 235

Documentation

Overview

This file implements OpenAPI 3.2 specification generation for the Prometheus HTTP API. It provides dynamic spec building with optional path filtering.

This file contains example request bodies and response data for OpenAPI documentation. Examples are included in the generated spec to provide realistic usage scenarios for API consumers.

This file defines all API path specifications including parameters, request bodies, and response schemas. Each path definition corresponds to an endpoint registered in api.go.

This file defines all OpenAPI schema definitions for API request and response types. Schemas are organized by functional area: query, labels, series, metadata, targets, rules, alerts, and status endpoints.

Index

Constants

View Source
const (
	ErrorNone errorNum = iota
	ErrorTimeout
	ErrorCanceled
	ErrorExec
	ErrorBadData
	ErrorInternal
	ErrorUnavailable
	ErrorNotFound
	ErrorNotAcceptable
)

Variables

View Source
var (
	// MinTime is the default timestamp used for the start of optional time ranges.
	// Exposed to let downstream projects reference it.
	//
	// Historical note: This should just be time.Unix(math.MinInt64/1000, 0).UTC(),
	// but it was set to a higher value in the past due to a misunderstanding.
	// The value is still low enough for practical purposes, so we don't want
	// to change it now, avoiding confusion for importers of this variable.
	MinTime = time.Unix(math.MinInt64/1000+62135596801, 0).UTC()

	// MaxTime is the default timestamp used for the end of optional time ranges.
	// Exposed to let downstream projects to reference it.
	//
	// Historical note: This should just be time.Unix(math.MaxInt64/1000, 0).UTC(),
	// but it was set to a lower value in the past due to a misunderstanding.
	// The value is still high enough for practical purposes, so we don't want
	// to change it now, avoiding confusion for importers of this variable.
	MaxTime = time.Unix(math.MaxInt64/1000-62135596801, 999999999).UTC()
)
View Source
var LocalhostRepresentations = []string{"127.0.0.1", "localhost", "::1"}

Functions

func DefaultStatsRenderer added in v0.53.0

func DefaultStatsRenderer(_ context.Context, s *stats.Statistics, param string) stats.QueryStats

DefaultStatsRenderer is the default stats renderer for the API.

func FuzzAlgorithms added in v0.313.0

func FuzzAlgorithms() []string

FuzzAlgorithms returns the canonical list of supported fuzzy matching algorithms. The returned slice is a copy and may be modified safely.

Types

type API

type API struct {
	Queryable         storage.SampleAndChunkQueryable
	QueryEngine       promql.QueryEngine
	ExemplarQueryable storage.ExemplarQueryable

	CORSOrigin *regexp.Regexp
	// contains filtered or unexported fields
}

API can register a set of endpoints in a router and handle them using the provided storage and query engine.

func NewAPI

func NewAPI(
	qe promql.QueryEngine,
	q storage.SampleAndChunkQueryable,
	ap storage.Appendable, apV2 storage.AppendableV2,
	eq storage.ExemplarQueryable,
	spsr func(context.Context) ScrapePoolsRetriever,
	tr func(context.Context) TargetRetriever,
	ar func(context.Context) AlertmanagerRetriever,
	configFunc func() config.Config,
	flagsMap map[string]string,
	globalURLOptions GlobalURLOptions,
	readyFunc func(http.HandlerFunc) http.HandlerFunc,
	db TSDBAdminStats,
	dbDir string,
	enableAdmin bool,
	enableSearch bool,
	maxSearchLimit int,
	logger *slog.Logger,
	rr func(context.Context) RulesRetriever,
	remoteReadSampleLimit int,
	remoteReadConcurrencyLimit int,
	remoteReadMaxBytesInFrame int,
	isAgent bool,
	corsOrigin *regexp.Regexp,
	runtimeInfo func() (RuntimeInfo, error),
	buildInfo *PrometheusVersion,
	notificationsGetter func() []notifications.Notification,
	notificationsSub func() (<-chan notifications.Notification, func(), bool),
	gatherer prometheus.Gatherer,
	registerer prometheus.Registerer,
	statsRenderer StatsRenderer,
	rwEnabled bool,
	acceptRemoteWriteProtoMsgs remoteapi.MessageTypes,
	otlpEnabled, otlpDeltaToCumulative, otlpNativeDeltaIngestion bool,
	stZeroIngestionEnabled bool,
	lookbackDelta time.Duration,
	enableTypeAndUnitLabels bool,
	appendMetadata bool,
	overrideErrorCode OverrideErrorCode,
	featureRegistry features.Collector,
	openAPIOptions OpenAPIOptions,
	promqlParser parser.Parser,
) *API

NewAPI returns an initialized API type.

func (*API) ClearCodecs added in v0.46.0

func (api *API) ClearCodecs()

ClearCodecs removes all available codecs from this API, including the default codec installed by NewAPI.

func (*API) InstallCodec added in v0.46.0

func (api *API) InstallCodec(codec Codec)

InstallCodec adds codec to this API's available codecs. Codecs installed first take precedence over codecs installed later when evaluating wildcards in Accept headers. The first installed codec is used as a fallback when the Accept header cannot be satisfied or if there is no Accept header.

func (*API) Register

func (api *API) Register(r *route.Router)

Register the API's endpoints in the given router.

type Alert

type Alert struct {
	Labels          labels.Labels `json:"labels"`
	Annotations     labels.Labels `json:"annotations"`
	State           string        `json:"state"`
	ActiveAt        *time.Time    `json:"activeAt,omitempty"`
	KeepFiringSince *time.Time    `json:"keepFiringSince,omitempty"`
	Value           string        `json:"value"`
}

Alert has info for an alert.

type AlertDiscovery

type AlertDiscovery struct {
	Alerts []*Alert `json:"alerts"`
}

AlertDiscovery has info for all active alerts.

type AlertingRule

type AlertingRule struct {
	// State can be "pending", "firing", "inactive".
	State          string           `json:"state"`
	Name           string           `json:"name"`
	Query          string           `json:"query"`
	Duration       float64          `json:"duration"`
	KeepFiringFor  float64          `json:"keepFiringFor"`
	Labels         labels.Labels    `json:"labels"`
	Annotations    labels.Labels    `json:"annotations"`
	Alerts         []*Alert         `json:"alerts"`
	Health         rules.RuleHealth `json:"health"`
	LastError      string           `json:"lastError,omitempty"`
	EvaluationTime float64          `json:"evaluationTime"`
	LastEvaluation time.Time        `json:"lastEvaluation"`
	// Type of an alertingRule is always "alerting".
	Type string `json:"type"`
}

type AlertmanagerDiscovery

type AlertmanagerDiscovery struct {
	ActiveAlertmanagers  []*AlertmanagerTarget `json:"activeAlertmanagers"`
	DroppedAlertmanagers []*AlertmanagerTarget `json:"droppedAlertmanagers"`
}

AlertmanagerDiscovery has all the active Alertmanagers.

type AlertmanagerRetriever

type AlertmanagerRetriever interface {
	Alertmanagers() []*url.URL
	DroppedAlertmanagers() []*url.URL
}

AlertmanagerRetriever provides a list of all/dropped AlertManager URLs.

type AlertmanagerTarget

type AlertmanagerTarget struct {
	URL string `json:"url"`
}

AlertmanagerTarget has info on one AM.

type ChainFilter added in v0.313.0

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

ChainFilter combines multiple filters with AND logic. Returns true only if all filters accept the value. The returned score is the best (max) score across the filters, so that rankings reflect the strongest matching dimension.

func NewChainFilter added in v0.313.0

func NewChainFilter(filters ...storage.Filter) *ChainFilter

NewChainFilter creates a new ChainFilter.

func (*ChainFilter) Accept added in v0.313.0

func (f *ChainFilter) Accept(value string) (bool, float64)

Accept returns true if all filters accept the value. Returns the maximum score from all filters.

type Codec added in v0.46.0

type Codec interface {
	// ContentType returns the MIME time that this Codec emits.
	ContentType() MIMEType

	// CanEncode determines if this Codec can encode resp.
	CanEncode(resp *Response) bool

	// Encode encodes resp, ready for transmission to an API consumer.
	Encode(resp *Response) ([]byte, error)
}

A Codec performs encoding of API responses.

type DroppedTarget

type DroppedTarget struct {
	// Labels before any processing.
	DiscoveredLabels labels.Labels `json:"discoveredLabels"`
	ScrapePool       string        `json:"scrapePool"`
}

DroppedTarget has the information for one target that was dropped during relabelling.

type FuzzyFilter added in v0.313.0

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

FuzzyFilter implements Jaro-Winkler fuzzy matching against a query.

func NewFuzzyFilter added in v0.313.0

func NewFuzzyFilter(query string, threshold float64) *FuzzyFilter

NewFuzzyFilter creates a new FuzzyFilter. threshold should be in range [0.0, 1.0] where 1.0 requires perfect match.

func (*FuzzyFilter) Accept added in v0.313.0

func (f *FuzzyFilter) Accept(value string) (bool, float64)

Accept returns true if the value matches the fuzzy query above the threshold.

type GlobalURLOptions

type GlobalURLOptions struct {
	ListenAddress string
	Host          string
	Scheme        string
}

GlobalURLOptions contains fields used for deriving the global URL for local targets.

type HeadStats

type HeadStats struct {
	NumSeries     uint64 `json:"numSeries"`
	NumLabelPairs int    `json:"numLabelPairs"`
	ChunkCount    int64  `json:"chunkCount"`
	MinTime       int64  `json:"minTime"`
	MaxTime       int64  `json:"maxTime"`
}

HeadStats has information about the TSDB head.

type JSONCodec added in v0.46.0

type JSONCodec struct{}

JSONCodec is a Codec that encodes API responses as JSON.

func (JSONCodec) CanEncode added in v0.46.0

func (JSONCodec) CanEncode(*Response) bool

func (JSONCodec) ContentType added in v0.46.0

func (JSONCodec) ContentType() MIMEType

func (JSONCodec) Encode added in v0.46.0

func (JSONCodec) Encode(resp *Response) ([]byte, error)

type MIMEType added in v0.46.0

type MIMEType struct {
	Type    string
	SubType string
}

func (MIMEType) Satisfies added in v0.46.0

func (m MIMEType) Satisfies(accept goautoneg.Accept) bool

func (MIMEType) String added in v0.46.0

func (m MIMEType) String() string

type OpenAPIBuilder added in v0.310.0

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

OpenAPIBuilder builds and caches OpenAPI specifications.

func NewOpenAPIBuilder added in v0.310.0

func NewOpenAPIBuilder(opts OpenAPIOptions, logger *slog.Logger) *OpenAPIBuilder

NewOpenAPIBuilder creates a new OpenAPI builder with the given options.

func (*OpenAPIBuilder) ServeOpenAPI added in v0.310.0

func (b *OpenAPIBuilder) ServeOpenAPI(w http.ResponseWriter, r *http.Request)

ServeOpenAPI returns the OpenAPI specification as YAML. By default, serves OpenAPI 3.1.0. Use ?openapi_version=3.2 for OpenAPI 3.2.0.

func (*OpenAPIBuilder) WrapHandler added in v0.310.0

func (*OpenAPIBuilder) WrapHandler(next http.HandlerFunc) http.HandlerFunc

WrapHandler returns the handler unchanged (no validation).

type OpenAPIOptions added in v0.310.0

type OpenAPIOptions struct {
	// IncludePaths filters which paths to include in the spec.
	// If empty, all paths are included.
	// Paths are matched by prefix (e.g., "/query" matches "/query" and "/query_range").
	IncludePaths []string

	// ExternalURL is the external URL of the Prometheus server (e.g., "http://prometheus.example.com:9090").
	ExternalURL string

	// Version is the API version to include in the OpenAPI spec.
	// If empty, defaults to "0.0.1-undefined".
	Version string

	// MaxSearchLimit is the operator-configured cap for the search API "limit" parameter.
	// Zero means no cap is applied.
	MaxSearchLimit int
}

OpenAPIOptions configures the OpenAPI spec builder.

type OverrideErrorCode added in v0.307.0

type OverrideErrorCode func(errorNum, error) (code int, override bool)

OverrideErrorCode can be used to override status code for different error types. Return false to fall back to default status code.

type PrometheusVersion

type PrometheusVersion struct {
	Version   string `json:"version"`
	Revision  string `json:"revision"`
	Branch    string `json:"branch"`
	BuildUser string `json:"buildUser"`
	BuildDate string `json:"buildDate"`
	GoVersion string `json:"goVersion"`
}

PrometheusVersion contains build information about Prometheus.

type QueryData added in v0.46.0

type QueryData struct {
	ResultType parser.ValueType `json:"resultType"`
	Result     parser.Value     `json:"result"`
	Stats      stats.QueryStats `json:"stats,omitempty"`
}

type QueryOpts added in v0.46.0

type QueryOpts interface {
	EnablePerStepStats() bool
	LookbackDelta() time.Duration
}

type RecordingRule

type RecordingRule struct {
	Name           string           `json:"name"`
	Query          string           `json:"query"`
	Labels         labels.Labels    `json:"labels"`
	Health         rules.RuleHealth `json:"health"`
	LastError      string           `json:"lastError,omitempty"`
	EvaluationTime float64          `json:"evaluationTime"`
	LastEvaluation time.Time        `json:"lastEvaluation"`
	// Type of a recordingRule is always "recording".
	Type string `json:"type"`
}

type RelabelStep added in v0.308.0

type RelabelStep struct {
	Rule   *relabel.Config `json:"rule"`
	Output labels.Labels   `json:"output"`
	Keep   bool            `json:"keep"`
}

type RelabelStepsResponse added in v0.308.0

type RelabelStepsResponse struct {
	Steps []RelabelStep `json:"steps"`
}

type Response added in v0.46.0

type Response struct {
	Status    status   `json:"status"`
	Data      any      `json:"data,omitempty"`
	ErrorType string   `json:"errorType,omitempty"`
	Error     string   `json:"error,omitempty"`
	Warnings  []string `json:"warnings,omitempty"`
	Infos     []string `json:"infos,omitempty"`
}

Response contains a response to a HTTP API request.

type Rule

type Rule any

type RuleDiscovery

type RuleDiscovery struct {
	RuleGroups     []*RuleGroup `json:"groups"`
	GroupNextToken string       `json:"groupNextToken,omitempty"`
}

RuleDiscovery has info for all rules.

type RuleGroup

type RuleGroup struct {
	Name string `json:"name"`
	File string `json:"file"`
	// In order to preserve rule ordering, while exposing type (alerting or recording)
	// specific properties, both alerting and recording rules are exposed in the
	// same array.
	Rules          []Rule    `json:"rules"`
	Interval       float64   `json:"interval"`
	Limit          int       `json:"limit"`
	EvaluationTime float64   `json:"evaluationTime"`
	LastEvaluation time.Time `json:"lastEvaluation"`
}

RuleGroup has info for rules which are part of a group.

type RulesRetriever

type RulesRetriever interface {
	RuleGroups() []*rules.Group
	AlertingRules() []*rules.AlertingRule
}

RulesRetriever provides a list of active rules and alerts.

type RuntimeInfo

type RuntimeInfo struct {
	StartTime           time.Time `json:"startTime"`
	CWD                 string    `json:"CWD"`
	Hostname            string    `json:"hostname"`
	ServerTime          time.Time `json:"serverTime"`
	ReloadConfigSuccess bool      `json:"reloadConfigSuccess"`
	LastConfigTime      time.Time `json:"lastConfigTime"`
	CorruptionCount     int64     `json:"corruptionCount"`
	GoroutineCount      int       `json:"goroutineCount"`
	GOMAXPROCS          int       `json:"GOMAXPROCS"`
	GOMEMLIMIT          int64     `json:"GOMEMLIMIT"`
	GOGC                string    `json:"GOGC"`
	GODEBUG             string    `json:"GODEBUG"`
	StorageRetention    string    `json:"storageRetention"`
}

RuntimeInfo contains runtime information about Prometheus.

type ScrapePoolsDiscovery added in v0.42.0

type ScrapePoolsDiscovery struct {
	ScrapePools []string `json:"scrapePools"`
}

type ScrapePoolsRetriever added in v0.42.0

type ScrapePoolsRetriever interface {
	ScrapePools() []string
}

ScrapePoolsRetriever provide the list of all scrape pools.

type StatsRenderer

type StatsRenderer func(context.Context, *stats.Statistics, string) stats.QueryStats

StatsRenderer converts engine statistics into a format suitable for the API.

type SubsequenceFilter added in v0.313.0

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

SubsequenceFilter implements fuzzy matching using a sequential character matching algorithm. It requires all pattern characters to appear in the value in order (subsequence matching), and scores matches by rewarding consecutive character runs and penalizing gaps. The score is normalized to [0.0, 1.0] and compared against a threshold.

func NewSubsequenceFilter added in v0.313.0

func NewSubsequenceFilter(query string, threshold float64) *SubsequenceFilter

NewSubsequenceFilter creates a new SubsequenceFilter. threshold should be in range [0.0, 1.0] where 0.0 accepts any subsequence match.

func (*SubsequenceFilter) Accept added in v0.313.0

func (f *SubsequenceFilter) Accept(value string) (bool, float64)

Accept returns true if the value matches the subsequence query above the threshold. Prefix matches always score 1.0 for consistency with SubstringFilter.

type SubstringFilter added in v0.313.0

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

SubstringFilter implements case-sensitive substring matching with a position-based score. A prefix match scores 1.0; substring matches score in the range [0.1, 1.0) where earlier match positions score higher.

func NewSubstringFilter added in v0.313.0

func NewSubstringFilter(query string) *SubstringFilter

NewSubstringFilter creates a new SubstringFilter. The query is matched against incoming values in their literal case.

func (*SubstringFilter) Accept added in v0.313.0

func (f *SubstringFilter) Accept(value string) (bool, float64)

Accept returns true if the value contains the substring query, with a score that decreases as the match position moves toward the end of the value.

The position component is computed in characters (runes), not bytes, so a match at character offset 1 in a multi-byte string scores the same as a match at byte offset 1 in an ASCII string. An ASCII fast path keeps the common case at byte arithmetic.

type TSDBAdminStats

type TSDBAdminStats interface {
	CleanTombstones() error
	Delete(ctx context.Context, mint, maxt int64, ms ...*labels.Matcher) error
	Snapshot(dir string, withHead bool) error
	Stats(statsByLabelName string, limit int) (*tsdb.Stats, error)
	WALReplayStatus() (tsdb.WALReplayStatus, error)
	BlockMetas() ([]tsdb.BlockMeta, error)
}

TSDBAdminStats defines the tsdb interfaces used by the v1 API for admin operations as well as statistics.

type TSDBStat added in v0.37.0

type TSDBStat struct {
	Name  string `json:"name"`
	Value uint64 `json:"value"`
}

TSDBStat holds the information about individual cardinality.

func TSDBStatsFromIndexStats added in v0.37.0

func TSDBStatsFromIndexStats(stats []index.Stat) []TSDBStat

TSDBStatsFromIndexStats converts a index.Stat slice to a TSDBStat slice.

type TSDBStatus added in v0.37.0

type TSDBStatus struct {
	HeadStats                   HeadStats  `json:"headStats"`
	SeriesCountByMetricName     []TSDBStat `json:"seriesCountByMetricName"`
	LabelValueCountByLabelName  []TSDBStat `json:"labelValueCountByLabelName"`
	MemoryInBytesByLabelName    []TSDBStat `json:"memoryInBytesByLabelName"`
	SeriesCountByLabelValuePair []TSDBStat `json:"seriesCountByLabelValuePair"`
}

TSDBStatus has information of cardinality statistics from postings.

type Target

type Target struct {
	// Labels before any processing.
	DiscoveredLabels labels.Labels `json:"discoveredLabels"`
	// Any labels that are added to this target and its metrics.
	Labels labels.Labels `json:"labels"`

	ScrapePool string `json:"scrapePool"`
	ScrapeURL  string `json:"scrapeUrl"`
	GlobalURL  string `json:"globalUrl"`

	LastError          string              `json:"lastError"`
	LastScrape         time.Time           `json:"lastScrape"`
	LastScrapeDuration float64             `json:"lastScrapeDuration"`
	Health             scrape.TargetHealth `json:"health"`

	ScrapeInterval string `json:"scrapeInterval"`
	ScrapeTimeout  string `json:"scrapeTimeout"`
}

Target has the information for one target.

type TargetDiscovery

type TargetDiscovery struct {
	ActiveTargets       []*Target        `json:"activeTargets"`
	DroppedTargets      []*DroppedTarget `json:"droppedTargets"`
	DroppedTargetCounts map[string]int   `json:"droppedTargetCounts"`
}

TargetDiscovery has all the active targets.

type TargetRetriever

type TargetRetriever interface {
	TargetsActive() map[string][]*scrape.Target
	TargetsDropped() map[string][]*scrape.Target
	TargetsDroppedCounts() map[string]int
	ScrapePoolConfig(string) (*config.ScrapeConfig, error)
}

TargetRetriever provides the list of active/dropped targets to scrape or not.

Jump to

Keyboard shortcuts

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