Documentation ¶
Overview ¶
Package v1 provides bindings to the Prometheus HTTP API v1: http://prometheus.io/docs/querying/api/
Index ¶
- Constants
- type API
- type ActiveTarget
- type Alert
- type AlertManager
- type AlertManagersResult
- type AlertState
- type AlertingRule
- type AlertsResult
- type BuildinfoResult
- type ConfigResult
- type DroppedTarget
- type Error
- type ErrorType
- type Exemplar
- type ExemplarQueryResult
- type FlagsResult
- type HealthStatus
- type Metadata
- type MetricMetadata
- type MetricType
- type Option
- type Range
- type RecordingRule
- type RuleGroup
- type RuleHealth
- type RuleType
- type Rules
- type RulesResult
- type RuntimeinfoResult
- type SnapshotResult
- type Stat
- type TSDBHeadStats
- type TSDBResult
- type TargetsResult
- type WalReplayStatus
- type Warnings
Examples ¶
Constants ¶
const ( // Possible values for AlertState. AlertStateFiring AlertState = "firing" AlertStateInactive AlertState = "inactive" AlertStatePending AlertState = "pending" // Possible values for ErrorType. ErrBadData ErrorType = "bad_data" ErrTimeout ErrorType = "timeout" ErrCanceled ErrorType = "canceled" ErrExec ErrorType = "execution" ErrBadResponse ErrorType = "bad_response" ErrServer ErrorType = "server_error" ErrClient ErrorType = "client_error" // Possible values for HealthStatus. HealthGood HealthStatus = "up" HealthUnknown HealthStatus = "unknown" HealthBad HealthStatus = "down" // Possible values for RuleType. RuleTypeRecording RuleType = "recording" RuleTypeAlerting RuleType = "alerting" // Possible values for RuleHealth. RuleHealthGood = "ok" RuleHealthUnknown = "unknown" RuleHealthBad = "err" // Possible values for MetricType MetricTypeCounter MetricType = "counter" MetricTypeGauge MetricType = "gauge" MetricTypeHistogram MetricType = "histogram" MetricTypeGaugeHistogram MetricType = "gaugehistogram" MetricTypeSummary MetricType = "summary" MetricTypeInfo MetricType = "info" MetricTypeStateset MetricType = "stateset" MetricTypeUnknown MetricType = "unknown" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type API ¶
type API interface { // Alerts returns a list of all active alerts. Alerts(ctx context.Context) (AlertsResult, error) // AlertManagers returns an overview of the current state of the Prometheus alert manager discovery. AlertManagers(ctx context.Context) (AlertManagersResult, error) // CleanTombstones removes the deleted data from disk and cleans up the existing tombstones. CleanTombstones(ctx context.Context) error // Config returns the current Prometheus configuration. Config(ctx context.Context) (ConfigResult, error) // DeleteSeries deletes data for a selection of series in a time range. DeleteSeries(ctx context.Context, matches []string, startTime, endTime time.Time) error // Flags returns the flag values that Prometheus was launched with. Flags(ctx context.Context) (FlagsResult, error) // LabelNames returns the unique label names present in the block in sorted order by given time range and matchers. LabelNames(ctx context.Context, matches []string, startTime, endTime time.Time, opts ...Option) ([]string, Warnings, error) // LabelValues performs a query for the values of the given label, time range and matchers. LabelValues(ctx context.Context, label string, matches []string, startTime, endTime time.Time, opts ...Option) (model.LabelValues, Warnings, error) // Query performs a query for the given time. Query(ctx context.Context, query string, ts time.Time, opts ...Option) (model.Value, Warnings, error) // QueryRange performs a query for the given range. QueryRange(ctx context.Context, query string, r Range, opts ...Option) (model.Value, Warnings, error) // QueryExemplars performs a query for exemplars by the given query and time range. QueryExemplars(ctx context.Context, query string, startTime, endTime time.Time) ([]ExemplarQueryResult, error) // Buildinfo returns various build information properties about the Prometheus server Buildinfo(ctx context.Context) (BuildinfoResult, error) // Runtimeinfo returns the various runtime information properties about the Prometheus server. Runtimeinfo(ctx context.Context) (RuntimeinfoResult, error) // Series finds series by label matchers. Series(ctx context.Context, matches []string, startTime, endTime time.Time, opts ...Option) ([]model.LabelSet, Warnings, error) // Snapshot creates a snapshot of all current data into snapshots/<datetime>-<rand> // under the TSDB's data directory and returns the directory as response. Snapshot(ctx context.Context, skipHead bool) (SnapshotResult, error) // Rules returns a list of alerting and recording rules that are currently loaded. Rules(ctx context.Context) (RulesResult, error) // Targets returns an overview of the current state of the Prometheus target discovery. Targets(ctx context.Context) (TargetsResult, error) // TargetsMetadata returns metadata about metrics currently scraped by the target. TargetsMetadata(ctx context.Context, matchTarget, metric, limit string) ([]MetricMetadata, error) // Metadata returns metadata about metrics currently scraped by the metric name. Metadata(ctx context.Context, metric, limit string) (map[string][]Metadata, error) // TSDB returns the cardinality statistics. TSDB(ctx context.Context, opts ...Option) (TSDBResult, error) // WalReplay returns the current replay status of the wal. WalReplay(ctx context.Context) (WalReplayStatus, error) }
API provides bindings for Prometheus's v1 API.
Example (Query) ¶
package main import ( "context" "fmt" "os" "time" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" ) func main() { client, err := api.NewClient(api.Config{ Address: "http://demo.robustperception.io:9090", }) if err != nil { fmt.Printf("Error creating client: %v\n", err) os.Exit(1) } v1api := v1.NewAPI(client) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() result, warnings, err := v1api.Query(ctx, "up", time.Now(), v1.WithTimeout(5*time.Second)) if err != nil { fmt.Printf("Error querying Prometheus: %v\n", err) os.Exit(1) } if len(warnings) > 0 { fmt.Printf("Warnings: %v\n", warnings) } fmt.Printf("Result:\n%v\n", result) }
Output:
Example (QueryRange) ¶
package main import ( "context" "fmt" "os" "time" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" ) func main() { client, err := api.NewClient(api.Config{ Address: "http://demo.robustperception.io:9090", }) if err != nil { fmt.Printf("Error creating client: %v\n", err) os.Exit(1) } v1api := v1.NewAPI(client) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() r := v1.Range{ Start: time.Now().Add(-time.Hour), End: time.Now(), Step: time.Minute, } result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r, v1.WithTimeout(5*time.Second)) if err != nil { fmt.Printf("Error querying Prometheus: %v\n", err) os.Exit(1) } if len(warnings) > 0 { fmt.Printf("Warnings: %v\n", warnings) } fmt.Printf("Result:\n%v\n", result) }
Output:
Example (QueryRangeWithAuthBearerToken) ¶
package main import ( "context" "fmt" "os" "time" "github.com/prometheus/common/config" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" ) func main() { client, err := api.NewClient(api.Config{ Address: "http://demo.robustperception.io:9090", // We can use amazing github.com/prometheus/common/config helper! RoundTripper: config.NewAuthorizationCredentialsRoundTripper( "Bearer", config.NewInlineSecret("secret_token"), api.DefaultRoundTripper, ), }) if err != nil { fmt.Printf("Error creating client: %v\n", err) os.Exit(1) } v1api := v1.NewAPI(client) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() r := v1.Range{ Start: time.Now().Add(-time.Hour), End: time.Now(), Step: time.Minute, } result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r) if err != nil { fmt.Printf("Error querying Prometheus: %v\n", err) os.Exit(1) } if len(warnings) > 0 { fmt.Printf("Warnings: %v\n", warnings) } fmt.Printf("Result:\n%v\n", result) }
Output:
Example (QueryRangeWithBasicAuth) ¶
package main import ( "context" "fmt" "os" "time" "github.com/prometheus/common/config" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" ) func main() { client, err := api.NewClient(api.Config{ Address: "http://demo.robustperception.io:9090", // We can use amazing github.com/prometheus/common/config helper! RoundTripper: config.NewBasicAuthRoundTripper( config.NewInlineSecret("me"), config.NewInlineSecret("definitely_me"), api.DefaultRoundTripper, ), }) if err != nil { fmt.Printf("Error creating client: %v\n", err) os.Exit(1) } v1api := v1.NewAPI(client) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() r := v1.Range{ Start: time.Now().Add(-time.Hour), End: time.Now(), Step: time.Minute, } result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r) if err != nil { fmt.Printf("Error querying Prometheus: %v\n", err) os.Exit(1) } if len(warnings) > 0 { fmt.Printf("Warnings: %v\n", warnings) } fmt.Printf("Result:\n%v\n", result) }
Output:
Example (QueryRangeWithUserAgent) ¶
package main import ( "context" "fmt" "net/http" "os" "time" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" ) type userAgentRoundTripper struct { name string rt http.RoundTripper } // RoundTrip implements the http.RoundTripper interface. func (u userAgentRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { if r.UserAgent() == "" { r2 := new(http.Request) *r2 = *r r2.Header = make(http.Header) for k, s := range r.Header { r2.Header[k] = s } r2.Header.Set("User-Agent", u.name) r = r2 } return u.rt.RoundTrip(r) } func main() { client, err := api.NewClient(api.Config{ Address: "http://demo.robustperception.io:9090", RoundTripper: userAgentRoundTripper{name: "Client-Golang", rt: api.DefaultRoundTripper}, }) if err != nil { fmt.Printf("Error creating client: %v\n", err) os.Exit(1) } v1api := v1.NewAPI(client) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() r := v1.Range{ Start: time.Now().Add(-time.Hour), End: time.Now(), Step: time.Minute, } result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r) if err != nil { fmt.Printf("Error querying Prometheus: %v\n", err) os.Exit(1) } if len(warnings) > 0 { fmt.Printf("Warnings: %v\n", warnings) } fmt.Printf("Result:\n%v\n", result) }
Output:
Example (Series) ¶
package main import ( "context" "fmt" "os" "time" "github.com/prometheus/client_golang/api" v1 "github.com/prometheus/client_golang/api/prometheus/v1" ) func main() { client, err := api.NewClient(api.Config{ Address: "http://demo.robustperception.io:9090", }) if err != nil { fmt.Printf("Error creating client: %v\n", err) os.Exit(1) } v1api := v1.NewAPI(client) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() lbls, warnings, err := v1api.Series(ctx, []string{ "{__name__=~\"scrape_.+\",job=\"node\"}", "{__name__=~\"scrape_.+\",job=\"prometheus\"}", }, time.Now().Add(-time.Hour), time.Now()) if err != nil { fmt.Printf("Error querying Prometheus: %v\n", err) os.Exit(1) } if len(warnings) > 0 { fmt.Printf("Warnings: %v\n", warnings) } fmt.Println("Result:") for _, lbl := range lbls { fmt.Println(lbl) } }
Output:
type ActiveTarget ¶
type ActiveTarget struct { DiscoveredLabels map[string]string `json:"discoveredLabels"` Labels model.LabelSet `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 HealthStatus `json:"health"` }
ActiveTarget models an active Prometheus scrape target.
type Alert ¶ added in v0.9.3
type Alert struct { ActiveAt time.Time `json:"activeAt"` Annotations model.LabelSet Labels model.LabelSet State AlertState Value string }
Alert models an active alert.
type AlertManager ¶
type AlertManager struct {
URL string `json:"url"`
}
AlertManager models a configured Alert Manager.
type AlertManagersResult ¶
type AlertManagersResult struct { Active []AlertManager `json:"activeAlertManagers"` Dropped []AlertManager `json:"droppedAlertManagers"` }
AlertManagersResult contains the result from querying the alertmanagers endpoint.
type AlertingRule ¶ added in v0.9.3
type AlertingRule struct { Name string `json:"name"` Query string `json:"query"` Duration float64 `json:"duration"` Labels model.LabelSet `json:"labels"` Annotations model.LabelSet `json:"annotations"` Alerts []*Alert `json:"alerts"` Health RuleHealth `json:"health"` LastError string `json:"lastError,omitempty"` EvaluationTime float64 `json:"evaluationTime"` LastEvaluation time.Time `json:"lastEvaluation"` State string `json:"state"` }
AlertingRule models a alerting rule.
func (*AlertingRule) UnmarshalJSON ¶ added in v0.9.3
func (r *AlertingRule) UnmarshalJSON(b []byte) error
type AlertsResult ¶ added in v0.9.3
type AlertsResult struct {
Alerts []Alert `json:"alerts"`
}
AlertsResult contains the result from querying the alerts endpoint.
type BuildinfoResult ¶ added in v0.12.1
type BuildinfoResult 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"` }
BuildinfoResult contains the results from querying the buildinfo endpoint.
type ConfigResult ¶
type ConfigResult struct {
YAML string `json:"yaml"`
}
ConfigResult contains the result from querying the config endpoint.
type DroppedTarget ¶
DroppedTarget models a dropped Prometheus scrape target.
type Exemplar ¶ added in v0.12.1
type Exemplar struct { Labels model.LabelSet `json:"labels"` Value model.SampleValue `json:"value"` Timestamp model.Time `json:"timestamp"` }
Exemplar is additional information associated with a time series.
type ExemplarQueryResult ¶ added in v0.12.1
type FlagsResult ¶
FlagsResult contains the result from querying the flag endpoint.
type HealthStatus ¶
type HealthStatus string
HealthStatus models the health status of a scrape target.
type Metadata ¶ added in v0.12.1
type Metadata struct { Type MetricType `json:"type"` Help string `json:"help"` Unit string `json:"unit"` }
Metadata models the metadata of a metric.
type MetricMetadata ¶ added in v0.9.4
type MetricMetadata struct { Target map[string]string `json:"target"` Metric string `json:"metric,omitempty"` Type MetricType `json:"type"` Help string `json:"help"` Unit string `json:"unit"` }
MetricMetadata models the metadata of a metric with its scrape target and name.
type Option ¶ added in v1.13.0
type Option func(c *apiOptions)
func WithLimit ¶ added in v1.20.0
WithLimit provides an optional maximum number of returned entries for APIs that support limit parameter e.g. https://prometheus.io/docs/prometheus/latest/querying/api/#instant-querie:~:text=%3A%20End%20timestamp.-,limit%3D%3Cnumber%3E,-%3A%20Maximum%20number%20of
func WithTimeout ¶ added in v1.13.0
WithTimeout can be used to provide an optional query evaluation timeout for Query and QueryRange. https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries
type Range ¶
type Range struct {
// The boundaries of the time range.
Start, End time.Time
// The maximum time between two slices within the boundaries.
Step time.Duration
}
Range represents a sliced time range.
type RecordingRule ¶ added in v0.9.3
type RecordingRule struct { Name string `json:"name"` Query string `json:"query"` Labels model.LabelSet `json:"labels,omitempty"` Health RuleHealth `json:"health"` LastError string `json:"lastError,omitempty"` EvaluationTime float64 `json:"evaluationTime"` LastEvaluation time.Time `json:"lastEvaluation"` }
RecordingRule models a recording rule.
func (*RecordingRule) UnmarshalJSON ¶ added in v0.9.3
func (r *RecordingRule) UnmarshalJSON(b []byte) error
type RuleGroup ¶ added in v0.9.3
type RuleGroup struct { Name string `json:"name"` File string `json:"file"` Interval float64 `json:"interval"` Rules Rules `json:"rules"` }
RuleGroup models a rule group that contains a set of recording and alerting rules.
func (*RuleGroup) UnmarshalJSON ¶ added in v0.9.3
type RuleHealth ¶ added in v0.9.3
type RuleHealth string
RuleHealth models the health status of a rule.
type Rules ¶ added in v0.9.3
type Rules []interface{}
Recording and alerting rules are stored in the same slice to preserve the order that rules are returned in by the API.
Rule types can be determined using a type switch:
switch v := rule.(type) { case RecordingRule: fmt.Print("got a recording rule") case AlertingRule: fmt.Print("got a alerting rule") default: fmt.Printf("unknown rule type %s", v) }
type RulesResult ¶ added in v0.9.3
type RulesResult struct {
Groups []RuleGroup `json:"groups"`
}
RulesResult contains the result from querying the rules endpoint.
type RuntimeinfoResult ¶ added in v0.12.1
type RuntimeinfoResult struct { StartTime time.Time `json:"startTime"` CWD string `json:"CWD"` ReloadConfigSuccess bool `json:"reloadConfigSuccess"` LastConfigTime time.Time `json:"lastConfigTime"` CorruptionCount int `json:"corruptionCount"` GoroutineCount int `json:"goroutineCount"` GOMAXPROCS int `json:"GOMAXPROCS"` GOGC string `json:"GOGC"` GODEBUG string `json:"GODEBUG"` StorageRetention string `json:"storageRetention"` }
RuntimeinfoResult contains the result from querying the runtimeinfo endpoint.
type SnapshotResult ¶
type SnapshotResult struct {
Name string `json:"name"`
}
SnapshotResult contains the result from querying the snapshot endpoint.
type TSDBHeadStats ¶ added in v0.12.1
type TSDBHeadStats struct { NumSeries int `json:"numSeries"` NumLabelPairs int `json:"numLabelPairs"` ChunkCount int `json:"chunkCount"` MinTime int `json:"minTime"` MaxTime int `json:"maxTime"` }
TSDBHeadStats contains TSDB stats
type TSDBResult ¶ added in v0.12.1
type TSDBResult struct { HeadStats TSDBHeadStats `json:"headStats"` SeriesCountByMetricName []Stat `json:"seriesCountByMetricName"` LabelValueCountByLabelName []Stat `json:"labelValueCountByLabelName"` MemoryInBytesByLabelName []Stat `json:"memoryInBytesByLabelName"` SeriesCountByLabelValuePair []Stat `json:"seriesCountByLabelValuePair"` }
TSDBResult contains the result from querying the tsdb endpoint.
type TargetsResult ¶
type TargetsResult struct { Active []ActiveTarget `json:"activeTargets"` Dropped []DroppedTarget `json:"droppedTargets"` }
TargetsResult contains the result from querying the targets endpoint.
type WalReplayStatus ¶ added in v0.12.1
type WalReplayStatus struct { Min int `json:"min"` Max int `json:"max"` Current int `json:"current"` }
WalReplayStatus represents the wal replay status.