Debian Codegraph @

api/prometheus/v1/api.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2017 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package v1 provides bindings to the Prometheus HTTP API v1:
15 // http://prometheus.io/docs/querying/api/
16 package v1
17
18 import (
19 "context"
20 "errors"
21 "fmt"
22 "math"
23 "net/http"
24 "net/url"
25 "strconv"
26 "strings"
27 "time"
28 "unsafe"
29
30 json "github.com/json-iterator/go"
31
32 "github.com/prometheus/common/model"
33
34 "github.com/prometheus/client_golang/api"
35 )
36
37 func init() {
38 json.RegisterTypeEncoderFunc("model.SamplePair", marshalSamplePairJSON, marshalJSONIsEmpty)
39 json.RegisterTypeDecoderFunc("model.SamplePair", unmarshalSamplePairJSON)
40 json.RegisterTypeEncoderFunc("model.SampleHistogramPair", marshalSampleHistogramPairJSON, marshalJSONIsEmpty)
41 json.RegisterTypeDecoderFunc("model.SampleHistogramPair", unmarshalSampleHistogramPairJSON)
42 json.RegisterTypeEncoderFunc("model.SampleStream", marshalSampleStreamJSON, marshalJSONIsEmpty) // Only needed for benchmark.
43 json.RegisterTypeDecoderFunc("model.SampleStream", unmarshalSampleStreamJSON) // Only needed for benchmark.
44 }
45
46 func unmarshalSamplePairJSON(ptr unsafe.Pointer, iter *json.Iterator) {
47 p := (*model.SamplePair)(ptr)
48 if !iter.ReadArray() {
49 iter.ReportError("unmarshal model.SamplePair", "SamplePair must be [timestamp, value]")
50 return
51 }
52 t := iter.ReadNumber()
53 if err := p.Timestamp.UnmarshalJSON([]byte(t)); err != nil {
54 iter.ReportError("unmarshal model.SamplePair", err.Error())
55 return
56 }
57 if !iter.ReadArray() {
58 iter.ReportError("unmarshal model.SamplePair", "SamplePair missing value")
59 return
60 }
61
62 f, err := strconv.ParseFloat(iter.ReadString(), 64)
63 if err != nil {
64 iter.ReportError("unmarshal model.SamplePair", err.Error())
65 return
66 }
67 p.Value = model.SampleValue(f)
68
69 if iter.ReadArray() {
70 iter.ReportError("unmarshal model.SamplePair", "SamplePair has too many values, must be [timestamp, value]")
71 return
72 }
73 }
74
75 func marshalSamplePairJSON(ptr unsafe.Pointer, stream *json.Stream) {
76 p := *((*model.SamplePair)(ptr))
77 stream.WriteArrayStart()
78 marshalTimestamp(p.Timestamp, stream)
79 stream.WriteMore()
80 marshalFloat(float64(p.Value), stream)
81 stream.WriteArrayEnd()
82 }
83
84 func unmarshalSampleHistogramPairJSON(ptr unsafe.Pointer, iter *json.Iterator) {
85 p := (*model.SampleHistogramPair)(ptr)
86 if !iter.ReadArray() {
87 iter.ReportError("unmarshal model.SampleHistogramPair", "SampleHistogramPair must be [timestamp, {histogram}]")
88 return
89 }
90 t := iter.ReadNumber()
91 if err := p.Timestamp.UnmarshalJSON([]byte(t)); err != nil {
92 iter.ReportError("unmarshal model.SampleHistogramPair", err.Error())
93 return
94 }
95 if !iter.ReadArray() {
96 iter.ReportError("unmarshal model.SampleHistogramPair", "SamplePair missing histogram")
97 return
98 }
99 h := &model.SampleHistogram{}
100 p.Histogram = h
101 for key := iter.ReadObject(); key != ""; key = iter.ReadObject() {
102 switch key {
103 case "count":
104 f, err := strconv.ParseFloat(iter.ReadString(), 64)
105 if err != nil {
106 iter.ReportError("unmarshal model.SampleHistogramPair", "count of histogram is not a float")
107 return
108 }
109 h.Count = model.FloatString(f)
110 case "sum":
111 f, err := strconv.ParseFloat(iter.ReadString(), 64)
112 if err != nil {
113 iter.ReportError("unmarshal model.SampleHistogramPair", "sum of histogram is not a float")
114 return
115 }
116 h.Sum = model.FloatString(f)
117 case "buckets":
118 for iter.ReadArray() {
119 b, err := unmarshalHistogramBucket(iter)
120 if err != nil {
121 iter.ReportError("unmarshal model.HistogramBucket", err.Error())
122 return
123 }
124 h.Buckets = append(h.Buckets, b)
125 }
126 default:
127 iter.ReportError("unmarshal model.SampleHistogramPair", fmt.Sprint("unexpected key in histogram:", key))
128 return
129 }
130 }
131 if iter.ReadArray() {
132 iter.ReportError("unmarshal model.SampleHistogramPair", "SampleHistogramPair has too many values, must be [timestamp, {histogram}]")
133 return
134 }
135 }
136
137 func marshalSampleHistogramPairJSON(ptr unsafe.Pointer, stream *json.Stream) {
138 p := *((*model.SampleHistogramPair)(ptr))
139 stream.WriteArrayStart()
140 marshalTimestamp(p.Timestamp, stream)
141 stream.WriteMore()
142 marshalHistogram(*p.Histogram, stream)
143 stream.WriteArrayEnd()
144 }
145
146 func unmarshalSampleStreamJSON(ptr unsafe.Pointer, iter *json.Iterator) {
147 ss := (*model.SampleStream)(ptr)
148 for key := iter.ReadObject(); key != ""; key = iter.ReadObject() {
149 switch key {
150 case "metric":
151 metricString := iter.ReadAny().ToString()
152 if err := json.UnmarshalFromString(metricString, &ss.Metric); err != nil {
153 iter.ReportError("unmarshal model.SampleStream", err.Error())
154 return
155 }
156 case "values":
157 for iter.ReadArray() {
158 v := model.SamplePair{}
159 unmarshalSamplePairJSON(unsafe.Pointer(&v), iter)
160 ss.Values = append(ss.Values, v)
161 }
162 case "histograms":
163 for iter.ReadArray() {
164 h := model.SampleHistogramPair{}
165 unmarshalSampleHistogramPairJSON(unsafe.Pointer(&h), iter)
166 ss.Histograms = append(ss.Histograms, h)
167 }
168 default:
169 iter.ReportError("unmarshal model.SampleStream", fmt.Sprint("unexpected key:", key))
170 return
171 }
172 }
173 }
174
175 func marshalSampleStreamJSON(ptr unsafe.Pointer, stream *json.Stream) {
176 ss := *((*model.SampleStream)(ptr))
177 stream.WriteObjectStart()
178 stream.WriteObjectField(`metric`)
179 m, err := json.ConfigCompatibleWithStandardLibrary.Marshal(ss.Metric)
180 if err != nil {
181 stream.Error = err
182 return
183 }
184 stream.SetBuffer(append(stream.Buffer(), m...))
185 if len(ss.Values) > 0 {
186 stream.WriteMore()
187 stream.WriteObjectField(`values`)
188 stream.WriteArrayStart()
189 for i, v := range ss.Values {
190 if i > 0 {
191 stream.WriteMore()
192 }
193 marshalSamplePairJSON(unsafe.Pointer(&v), stream)
194 }
195 stream.WriteArrayEnd()
196 }
197 if len(ss.Histograms) > 0 {
198 stream.WriteMore()
199 stream.WriteObjectField(`histograms`)
200 stream.WriteArrayStart()
201 for i, h := range ss.Histograms {
202 if i > 0 {
203 stream.WriteMore()
204 }
205 marshalSampleHistogramPairJSON(unsafe.Pointer(&h), stream)
206 }
207 stream.WriteArrayEnd()
208 }
209 stream.WriteObjectEnd()
210 }
211
212 func marshalFloat(v float64, stream *json.Stream) {
213 stream.WriteRaw(`"`)
214 // Taken from https://github.com/json-iterator/go/blob/master/stream_float.go#L71 as a workaround
215 // to https://github.com/json-iterator/go/issues/365 (json-iterator, to follow json standard, doesn't allow inf/nan).
216 buf := stream.Buffer()
217 abs := math.Abs(v)
218 fmt := byte('f')
219 // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
220 if abs != 0 {
221 if abs < 1e-6 || abs >= 1e21 {
222 fmt = 'e'
223 }
224 }
225 buf = strconv.AppendFloat(buf, v, fmt, -1, 64)
226 stream.SetBuffer(buf)
227 stream.WriteRaw(`"`)
228 }
229
230 func marshalTimestamp(timestamp model.Time, stream *json.Stream) {
231 t := int64(timestamp)
232 // Write out the timestamp as a float divided by 1000.
233 // This is ~3x faster than converting to a float.
234 if t < 0 {
235 stream.WriteRaw(`-`)
236 t = -t
237 }
238 stream.WriteInt64(t / 1000)
239 fraction := t % 1000
240 if fraction != 0 {
241 stream.WriteRaw(`.`)
242 if fraction < 100 {
243 stream.WriteRaw(`0`)
244 }
245 if fraction < 10 {
246 stream.WriteRaw(`0`)
247 }
248 stream.WriteInt64(fraction)
249 }
250 }
251
252 func unmarshalHistogramBucket(iter *json.Iterator) (*model.HistogramBucket, error) {
253 b := model.HistogramBucket{}
254 if !iter.ReadArray() {
255 return nil, errors.New("HistogramBucket must be [boundaries, lower, upper, count]")
256 }
257 boundaries, err := iter.ReadNumber().Int64()
258 if err != nil {
259 return nil, err
260 }
261 b.Boundaries = int32(boundaries)
262 if !iter.ReadArray() {
263 return nil, errors.New("HistogramBucket must be [boundaries, lower, upper, count]")
264 }
265 f, err := strconv.ParseFloat(iter.ReadString(), 64)
266 if err != nil {
267 return nil, err
268 }
269 b.Lower = model.FloatString(f)
270 if !iter.ReadArray() {
271 return nil, errors.New("HistogramBucket must be [boundaries, lower, upper, count]")
272 }
273 f, err = strconv.ParseFloat(iter.ReadString(), 64)
274 if err != nil {
275 return nil, err
276 }
277 b.Upper = model.FloatString(f)
278 if !iter.ReadArray() {
279 return nil, errors.New("HistogramBucket must be [boundaries, lower, upper, count]")
280 }
281 f, err = strconv.ParseFloat(iter.ReadString(), 64)
282 if err != nil {
283 return nil, err
284 }
285 b.Count = model.FloatString(f)
286 if iter.ReadArray() {
287 return nil, errors.New("HistogramBucket has too many values, must be [boundaries, lower, upper, count]")
288 }
289 return &b, nil
290 }
291
292 // marshalHistogramBucket writes something like: [ 3, "-0.25", "0.25", "3"]
293 // See marshalHistogram to understand what the numbers mean
294 func marshalHistogramBucket(b model.HistogramBucket, stream *json.Stream) {
295 stream.WriteArrayStart()
296 stream.WriteInt32(b.Boundaries)
297 stream.WriteMore()
298 marshalFloat(float64(b.Lower), stream)
299 stream.WriteMore()
300 marshalFloat(float64(b.Upper), stream)
301 stream.WriteMore()
302 marshalFloat(float64(b.Count), stream)
303 stream.WriteArrayEnd()
304 }
305
306 // marshalHistogram writes something like:
307 //
308 // {
309 // "count": "42",
310 // "sum": "34593.34",
311 // "buckets": [
312 // [ 3, "-0.25", "0.25", "3"],
313 // [ 0, "0.25", "0.5", "12"],
314 // [ 0, "0.5", "1", "21"],
315 // [ 0, "2", "4", "6"]
316 // ]
317 // }
318 //
319 // The 1st element in each bucket array determines if the boundaries are
320 // inclusive (AKA closed) or exclusive (AKA open):
321 //
322 // 0: lower exclusive, upper inclusive
323 // 1: lower inclusive, upper exclusive
324 // 2: both exclusive
325 // 3: both inclusive
326 //
327 // The 2nd and 3rd elements are the lower and upper boundary. The 4th element is
328 // the bucket count.
329 func marshalHistogram(h model.SampleHistogram, stream *json.Stream) {
330 stream.WriteObjectStart()
331 stream.WriteObjectField(`count`)
332 marshalFloat(float64(h.Count), stream)
333 stream.WriteMore()
334 stream.WriteObjectField(`sum`)
335 marshalFloat(float64(h.Sum), stream)
336
337 bucketFound := false
338 for _, bucket := range h.Buckets {
339 if bucket.Count == 0 {
340 continue // No need to expose empty buckets in JSON.
341 }
342 stream.WriteMore()
343 if !bucketFound {
344 stream.WriteObjectField(`buckets`)
345 stream.WriteArrayStart()
346 }
347 bucketFound = true
348 marshalHistogramBucket(*bucket, stream)
349 }
350 if bucketFound {
351 stream.WriteArrayEnd()
352 }
353 stream.WriteObjectEnd()
354 }
355
356 func marshalJSONIsEmpty(ptr unsafe.Pointer) bool {
357 return false
358 }
359
360 const (
361 apiPrefix = "/api/v1"
362
363 epAlerts = apiPrefix + "/alerts"
364 epAlertManagers = apiPrefix + "/alertmanagers"
365 epQuery = apiPrefix + "/query"
366 epQueryRange = apiPrefix + "/query_range"
367 epQueryExemplars = apiPrefix + "/query_exemplars"
368 epLabels = apiPrefix + "/labels"
369 epLabelValues = apiPrefix + "/label/:name/values"
370 epSeries = apiPrefix + "/series"
371 epTargets = apiPrefix + "/targets"
372 epTargetsMetadata = apiPrefix + "/targets/metadata"
373 epMetadata = apiPrefix + "/metadata"
374 epRules = apiPrefix + "/rules"
375 epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
376 epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
377 epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
378 epConfig = apiPrefix + "/status/config"
379 epFlags = apiPrefix + "/status/flags"
380 epBuildinfo = apiPrefix + "/status/buildinfo"
381 epRuntimeinfo = apiPrefix + "/status/runtimeinfo"
382 epTSDB = apiPrefix + "/status/tsdb"
383 epWalReplay = apiPrefix + "/status/walreplay"
384 )
385
386 // AlertState models the state of an alert.
387 type AlertState string
388
389 // ErrorType models the different API error types.
390 type ErrorType string
391
392 // HealthStatus models the health status of a scrape target.
393 type HealthStatus string
394
395 // RuleType models the type of a rule.
396 type RuleType string
397
398 // RuleHealth models the health status of a rule.
399 type RuleHealth string
400
401 // MetricType models the type of a metric.
402 type MetricType string
403
404 const (
405 // Possible values for AlertState.
406 AlertStateFiring AlertState = "firing"
407 AlertStateInactive AlertState = "inactive"
408 AlertStatePending AlertState = "pending"
409
410 // Possible values for ErrorType.
411 ErrBadData ErrorType = "bad_data"
412 ErrTimeout ErrorType = "timeout"
413 ErrCanceled ErrorType = "canceled"
414 ErrExec ErrorType = "execution"
415 ErrBadResponse ErrorType = "bad_response"
416 ErrServer ErrorType = "server_error"
417 ErrClient ErrorType = "client_error"
418
419 // Possible values for HealthStatus.
420 HealthGood HealthStatus = "up"
421 HealthUnknown HealthStatus = "unknown"
422 HealthBad HealthStatus = "down"
423
424 // Possible values for RuleType.
425 RuleTypeRecording RuleType = "recording"
426 RuleTypeAlerting RuleType = "alerting"
427
428 // Possible values for RuleHealth.
429 RuleHealthGood = "ok"
430 RuleHealthUnknown = "unknown"
431 RuleHealthBad = "err"
432
433 // Possible values for MetricType
434 MetricTypeCounter MetricType = "counter"
435 MetricTypeGauge MetricType = "gauge"
436 MetricTypeHistogram MetricType = "histogram"
437 MetricTypeGaugeHistogram MetricType = "gaugehistogram"
438 MetricTypeSummary MetricType = "summary"
439 MetricTypeInfo MetricType = "info"
440 MetricTypeStateset MetricType = "stateset"
441 MetricTypeUnknown MetricType = "unknown"
442 )
443
444 // Error is an error returned by the API.
445 type Error struct {
446 Type ErrorType
447 Msg string
448 Detail string
449 }
450
451 func (e *Error) Error() string {
452 return fmt.Sprintf("%s: %s", e.Type, e.Msg)
453 }
454
455 // Range represents a sliced time range.
456 type Range struct {
457 // The boundaries of the time range.
458 Start, End time.Time
459 // The maximum time between two slices within the boundaries.
460 Step time.Duration
461 }
462
463 // API provides bindings for Prometheus's v1 API.
464 type API interface {
465 // Alerts returns a list of all active alerts.
466 Alerts(ctx context.Context) (AlertsResult, error)
467 // AlertManagers returns an overview of the current state of the Prometheus alert manager discovery.
468 AlertManagers(ctx context.Context) (AlertManagersResult, error)
469 // CleanTombstones removes the deleted data from disk and cleans up the existing tombstones.
470 CleanTombstones(ctx context.Context) error
471 // Config returns the current Prometheus configuration.
472 Config(ctx context.Context) (ConfigResult, error)
473 // DeleteSeries deletes data for a selection of series in a time range.
474 DeleteSeries(ctx context.Context, matches []string, startTime, endTime time.Time) error
475 // Flags returns the flag values that Prometheus was launched with.
476 Flags(ctx context.Context) (FlagsResult, error)
477 // LabelNames returns the unique label names present in the block in sorted order by given time range and matchers.
478 LabelNames(ctx context.Context, matches []string, startTime, endTime time.Time, opts ...Option) ([]string, Warnings, error)
479 // LabelValues performs a query for the values of the given label, time range and matchers.
480 LabelValues(ctx context.Context, label string, matches []string, startTime, endTime time.Time, opts ...Option) (model.LabelValues, Warnings, error)
481 // Query performs a query for the given time.
482 Query(ctx context.Context, query string, ts time.Time, opts ...Option) (model.Value, Warnings, error)
483 // QueryRange performs a query for the given range.
484 QueryRange(ctx context.Context, query string, r Range, opts ...Option) (model.Value, Warnings, error)
485 // QueryExemplars performs a query for exemplars by the given query and time range.
486 QueryExemplars(ctx context.Context, query string, startTime, endTime time.Time) ([]ExemplarQueryResult, error)
487 // Buildinfo returns various build information properties about the Prometheus server
488 Buildinfo(ctx context.Context) (BuildinfoResult, error)
489 // Runtimeinfo returns the various runtime information properties about the Prometheus server.
490 Runtimeinfo(ctx context.Context) (RuntimeinfoResult, error)
491 // Series finds series by label matchers.
492 Series(ctx context.Context, matches []string, startTime, endTime time.Time, opts ...Option) ([]model.LabelSet, Warnings, error)
493 // Snapshot creates a snapshot of all current data into snapshots/<datetime>-<rand>
494 // under the TSDB's data directory and returns the directory as response.
495 Snapshot(ctx context.Context, skipHead bool) (SnapshotResult, error)
496 // Rules returns a list of alerting and recording rules that are currently loaded.
497 Rules(ctx context.Context) (RulesResult, error)
498 // Targets returns an overview of the current state of the Prometheus target discovery.
499 Targets(ctx context.Context) (TargetsResult, error)
500 // TargetsMetadata returns metadata about metrics currently scraped by the target.
501 TargetsMetadata(ctx context.Context, matchTarget, metric, limit string) ([]MetricMetadata, error)
502 // Metadata returns metadata about metrics currently scraped by the metric name.
503 Metadata(ctx context.Context, metric, limit string) (map[string][]Metadata, error)
504 // TSDB returns the cardinality statistics.
505 TSDB(ctx context.Context, opts ...Option) (TSDBResult, error)
506 // WalReplay returns the current replay status of the wal.
507 WalReplay(ctx context.Context) (WalReplayStatus, error)
508 }
509
510 // AlertsResult contains the result from querying the alerts endpoint.
511 type AlertsResult struct {
512 Alerts []Alert `json:"alerts"`
513 }
514
515 // AlertManagersResult contains the result from querying the alertmanagers endpoint.
516 type AlertManagersResult struct {
517 Active []AlertManager `json:"activeAlertManagers"`
518 Dropped []AlertManager `json:"droppedAlertManagers"`
519 }
520
521 // AlertManager models a configured Alert Manager.
522 type AlertManager struct {
523 URL string `json:"url"`
524 }
525
526 // ConfigResult contains the result from querying the config endpoint.
527 type ConfigResult struct {
528 YAML string `json:"yaml"`
529 }
530
531 // FlagsResult contains the result from querying the flag endpoint.
532 type FlagsResult map[string]string
533
534 // BuildinfoResult contains the results from querying the buildinfo endpoint.
535 type BuildinfoResult struct {
536 Version string `json:"version"`
537 Revision string `json:"revision"`
538 Branch string `json:"branch"`
539 BuildUser string `json:"buildUser"`
540 BuildDate string `json:"buildDate"`
541 GoVersion string `json:"goVersion"`
542 }
543
544 // RuntimeinfoResult contains the result from querying the runtimeinfo endpoint.
545 type RuntimeinfoResult struct {
546 StartTime time.Time `json:"startTime"`
547 CWD string `json:"CWD"`
548 ReloadConfigSuccess bool `json:"reloadConfigSuccess"`
549 LastConfigTime time.Time `json:"lastConfigTime"`
550 CorruptionCount int `json:"corruptionCount"`
551 GoroutineCount int `json:"goroutineCount"`
552 GOMAXPROCS int `json:"GOMAXPROCS"`
553 GOGC string `json:"GOGC"`
554 GODEBUG string `json:"GODEBUG"`
555 StorageRetention string `json:"storageRetention"`
556 }
557
558 // SnapshotResult contains the result from querying the snapshot endpoint.
559 type SnapshotResult struct {
560 Name string `json:"name"`
561 }
562
563 // RulesResult contains the result from querying the rules endpoint.
564 type RulesResult struct {
565 Groups []RuleGroup `json:"groups"`
566 }
567
568 // RuleGroup models a rule group that contains a set of recording and alerting rules.
569 type RuleGroup struct {
570 Name string `json:"name"`
571 File string `json:"file"`
572 Interval float64 `json:"interval"`
573 Rules Rules `json:"rules"`
574 }
575
576 // Recording and alerting rules are stored in the same slice to preserve the order
577 // that rules are returned in by the API.
578 //
579 // Rule types can be determined using a type switch:
580 //
581 // switch v := rule.(type) {
582 // case RecordingRule:
583 // fmt.Print("got a recording rule")
584 // case AlertingRule:
585 // fmt.Print("got a alerting rule")
586 // default:
587 // fmt.Printf("unknown rule type %s", v)
588 // }
589 type Rules []interface{}
590
591 // AlertingRule models a alerting rule.
592 type AlertingRule struct {
593 Name string `json:"name"`
594 Query string `json:"query"`
595 Duration float64 `json:"duration"`
596 Labels model.LabelSet `json:"labels"`
597 Annotations model.LabelSet `json:"annotations"`
598 Alerts []*Alert `json:"alerts"`
599 Health RuleHealth `json:"health"`
600 LastError string `json:"lastError,omitempty"`
601 EvaluationTime float64 `json:"evaluationTime"`
602 LastEvaluation time.Time `json:"lastEvaluation"`
603 State string `json:"state"`
604 }
605
606 // RecordingRule models a recording rule.
607 type RecordingRule struct {
608 Name string `json:"name"`
609 Query string `json:"query"`
610 Labels model.LabelSet `json:"labels,omitempty"`
611 Health RuleHealth `json:"health"`
612 LastError string `json:"lastError,omitempty"`
613 EvaluationTime float64 `json:"evaluationTime"`
614 LastEvaluation time.Time `json:"lastEvaluation"`
615 }
616
617 // Alert models an active alert.
618 type Alert struct {
619 ActiveAt time.Time `json:"activeAt"`
620 Annotations model.LabelSet
621 Labels model.LabelSet
622 State AlertState
623 Value string
624 }
625
626 // TargetsResult contains the result from querying the targets endpoint.
627 type TargetsResult struct {
628 Active []ActiveTarget `json:"activeTargets"`
629 Dropped []DroppedTarget `json:"droppedTargets"`
630 }
631
632 // ActiveTarget models an active Prometheus scrape target.
633 type ActiveTarget struct {
634 DiscoveredLabels map[string]string `json:"discoveredLabels"`
635 Labels model.LabelSet `json:"labels"`
636 ScrapePool string `json:"scrapePool"`
637 ScrapeURL string `json:"scrapeUrl"`
638 GlobalURL string `json:"globalUrl"`
639 LastError string `json:"lastError"`
640 LastScrape time.Time `json:"lastScrape"`
641 LastScrapeDuration float64 `json:"lastScrapeDuration"`
642 Health HealthStatus `json:"health"`
643 }
644
645 // DroppedTarget models a dropped Prometheus scrape target.
646 type DroppedTarget struct {
647 DiscoveredLabels map[string]string `json:"discoveredLabels"`
648 }
649
650 // MetricMetadata models the metadata of a metric with its scrape target and name.
651 type MetricMetadata struct {
652 Target map[string]string `json:"target"`
653 Metric string `json:"metric,omitempty"`
654 Type MetricType `json:"type"`
655 Help string `json:"help"`
656 Unit string `json:"unit"`
657 }
658
659 // Metadata models the metadata of a metric.
660 type Metadata struct {
661 Type MetricType `json:"type"`
662 Help string `json:"help"`
663 Unit string `json:"unit"`
664 }
665
666 // queryResult contains result data for a query.
667 type queryResult struct {
668 Type model.ValueType `json:"resultType"`
669 Result interface{} `json:"result"`
670
671 // The decoded value.
672 v model.Value
673 }
674
675 // TSDBResult contains the result from querying the tsdb endpoint.
676 type TSDBResult struct {
677 HeadStats TSDBHeadStats `json:"headStats"`
678 SeriesCountByMetricName []Stat `json:"seriesCountByMetricName"`
679 LabelValueCountByLabelName []Stat `json:"labelValueCountByLabelName"`
680 MemoryInBytesByLabelName []Stat `json:"memoryInBytesByLabelName"`
681 SeriesCountByLabelValuePair []Stat `json:"seriesCountByLabelValuePair"`
682 }
683
684 // TSDBHeadStats contains TSDB stats
685 type TSDBHeadStats struct {
686 NumSeries int `json:"numSeries"`
687 NumLabelPairs int `json:"numLabelPairs"`
688 ChunkCount int `json:"chunkCount"`
•689 MinTime int64 `json:"minTime"`
690 MaxTime int64 `json:"maxTime"`
691 }
692
693 // WalReplayStatus represents the wal replay status.
694 type WalReplayStatus struct {
695 Min int `json:"min"`
696 Max int `json:"max"`
697 Current int `json:"current"`
698 }
699
700 // Stat models information about statistic value.
701 type Stat struct {
702 Name string `json:"name"`
703 Value uint64 `json:"value"`
704 }
705
706 func (rg *RuleGroup) UnmarshalJSON(b []byte) error {
707 v := struct {
708 Name string `json:"name"`
709 File string `json:"file"`
710 Interval float64 `json:"interval"`
711 Rules []json.RawMessage `json:"rules"`
712 }{}
713
714 if err := json.Unmarshal(b, &v); err != nil {
715 return err
716 }
717
718 rg.Name = v.Name
719 rg.File = v.File
720 rg.Interval = v.Interval
721
722 for _, rule := range v.Rules {
723 alertingRule := AlertingRule{}
724 if err := json.Unmarshal(rule, &alertingRule); err == nil {
725 rg.Rules = append(rg.Rules, alertingRule)
726 continue
727 }
728 recordingRule := RecordingRule{}
729 if err := json.Unmarshal(rule, &recordingRule); err == nil {
730 rg.Rules = append(rg.Rules, recordingRule)
731 continue
732 }
733 return errors.New("failed to decode JSON into an alerting or recording rule")
734 }
735
736 return nil
737 }
738
739 func (r *AlertingRule) UnmarshalJSON(b []byte) error {
740 v := struct {
741 Type string `json:"type"`
742 }{}
743 if err := json.Unmarshal(b, &v); err != nil {
744 return err
745 }
746 if v.Type == "" {
747 return errors.New("type field not present in rule")
748 }
749 if v.Type != string(RuleTypeAlerting) {
750 return fmt.Errorf("expected rule of type %s but got %s", string(RuleTypeAlerting), v.Type)
751 }
752
753 rule := struct {
754 Name string `json:"name"`
755 Query string `json:"query"`
756 Duration float64 `json:"duration"`
757 Labels model.LabelSet `json:"labels"`
758 Annotations model.LabelSet `json:"annotations"`
759 Alerts []*Alert `json:"alerts"`
760 Health RuleHealth `json:"health"`
761 LastError string `json:"lastError,omitempty"`
762 EvaluationTime float64 `json:"evaluationTime"`
763 LastEvaluation time.Time `json:"lastEvaluation"`
764 State string `json:"state"`
765 }{}
766 if err := json.Unmarshal(b, &rule); err != nil {
767 return err
768 }
769 r.Health = rule.Health
770 r.Annotations = rule.Annotations
771 r.Name = rule.Name
772 r.Query = rule.Query
773 r.Alerts = rule.Alerts
774 r.Duration = rule.Duration
775 r.Labels = rule.Labels
776 r.LastError = rule.LastError
777 r.EvaluationTime = rule.EvaluationTime
778 r.LastEvaluation = rule.LastEvaluation
779 r.State = rule.State
780
781 return nil
782 }
783
784 func (r *RecordingRule) UnmarshalJSON(b []byte) error {
785 v := struct {
786 Type string `json:"type"`
787 }{}
788 if err := json.Unmarshal(b, &v); err != nil {
789 return err
790 }
791 if v.Type == "" {
792 return errors.New("type field not present in rule")
793 }
794 if v.Type != string(RuleTypeRecording) {
795 return fmt.Errorf("expected rule of type %s but got %s", string(RuleTypeRecording), v.Type)
796 }
797
798 rule := struct {
799 Name string `json:"name"`
800 Query string `json:"query"`
801 Labels model.LabelSet `json:"labels,omitempty"`
802 Health RuleHealth `json:"health"`
803 LastError string `json:"lastError,omitempty"`
804 EvaluationTime float64 `json:"evaluationTime"`
805 LastEvaluation time.Time `json:"lastEvaluation"`
806 }{}
807 if err := json.Unmarshal(b, &rule); err != nil {
808 return err
809 }
810 r.Health = rule.Health
811 r.Labels = rule.Labels
812 r.Name = rule.Name
813 r.LastError = rule.LastError
814 r.Query = rule.Query
815 r.EvaluationTime = rule.EvaluationTime
816 r.LastEvaluation = rule.LastEvaluation
817
818 return nil
819 }
820
821 func (qr *queryResult) UnmarshalJSON(b []byte) error {
822 v := struct {
823 Type model.ValueType `json:"resultType"`
824 Result json.RawMessage `json:"result"`
825 }{}
826
827 err := json.Unmarshal(b, &v)
828 if err != nil {
829 return err
830 }
831
832 switch v.Type {
833 case model.ValScalar:
834 var sv model.Scalar
835 err = json.Unmarshal(v.Result, &sv)
836 qr.v = &sv
837
838 case model.ValVector:
839 var vv model.Vector
840 err = json.Unmarshal(v.Result, &vv)
841 qr.v = vv
842
843 case model.ValMatrix:
844 var mv model.Matrix
845 err = json.Unmarshal(v.Result, &mv)
846 qr.v = mv
847
848 default:
849 err = fmt.Errorf("unexpected value type %q", v.Type)
850 }
851 return err
852 }
853
854 // Exemplar is additional information associated with a time series.
855 type Exemplar struct {
856 Labels model.LabelSet `json:"labels"`
857 Value model.SampleValue `json:"value"`
858 Timestamp model.Time `json:"timestamp"`
859 }
860
861 type ExemplarQueryResult struct {
862 SeriesLabels model.LabelSet `json:"seriesLabels"`
863 Exemplars []Exemplar `json:"exemplars"`
864 }
865
866 // NewAPI returns a new API for the client.
867 //
868 // It is safe to use the returned API from multiple goroutines.
869 func NewAPI(c api.Client) API {
870 return &httpAPI{
871 client: &apiClientImpl{
872 client: c,
873 },
874 }
875 }
876
877 type httpAPI struct {
878 client apiClient
879 }
880
881 func (h *httpAPI) Alerts(ctx context.Context) (AlertsResult, error) {
882 u := h.client.URL(epAlerts, nil)
883
884 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
885 if err != nil {
886 return AlertsResult{}, err
887 }
888
889 _, body, _, err := h.client.Do(ctx, req)
890 if err != nil {
891 return AlertsResult{}, err
892 }
893
894 var res AlertsResult
895 err = json.Unmarshal(body, &res)
896 return res, err
897 }
898
899 func (h *httpAPI) AlertManagers(ctx context.Context) (AlertManagersResult, error) {
900 u := h.client.URL(epAlertManagers, nil)
901
902 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
903 if err != nil {
904 return AlertManagersResult{}, err
905 }
906
907 _, body, _, err := h.client.Do(ctx, req)
908 if err != nil {
909 return AlertManagersResult{}, err
910 }
911
912 var res AlertManagersResult
913 err = json.Unmarshal(body, &res)
914 return res, err
915 }
916
917 func (h *httpAPI) CleanTombstones(ctx context.Context) error {
918 u := h.client.URL(epCleanTombstones, nil)
919
920 req, err := http.NewRequest(http.MethodPost, u.String(), nil)
921 if err != nil {
922 return err
923 }
924
925 _, _, _, err = h.client.Do(ctx, req)
926 return err
927 }
928
929 func (h *httpAPI) Config(ctx context.Context) (ConfigResult, error) {
930 u := h.client.URL(epConfig, nil)
931
932 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
933 if err != nil {
934 return ConfigResult{}, err
935 }
936
937 _, body, _, err := h.client.Do(ctx, req)
938 if err != nil {
939 return ConfigResult{}, err
940 }
941
942 var res ConfigResult
943 err = json.Unmarshal(body, &res)
944 return res, err
945 }
946
947 func (h *httpAPI) DeleteSeries(ctx context.Context, matches []string, startTime, endTime time.Time) error {
948 u := h.client.URL(epDeleteSeries, nil)
949 q := u.Query()
950
951 for _, m := range matches {
952 q.Add("match[]", m)
953 }
954
955 if !startTime.IsZero() {
956 q.Set("start", formatTime(startTime))
957 }
958 if !endTime.IsZero() {
959 q.Set("end", formatTime(endTime))
960 }
961
962 u.RawQuery = q.Encode()
963
964 req, err := http.NewRequest(http.MethodPost, u.String(), nil)
965 if err != nil {
966 return err
967 }
968
969 _, _, _, err = h.client.Do(ctx, req)
970 return err
971 }
972
973 func (h *httpAPI) Flags(ctx context.Context) (FlagsResult, error) {
974 u := h.client.URL(epFlags, nil)
975
976 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
977 if err != nil {
978 return FlagsResult{}, err
979 }
980
981 _, body, _, err := h.client.Do(ctx, req)
982 if err != nil {
983 return FlagsResult{}, err
984 }
985
986 var res FlagsResult
987 err = json.Unmarshal(body, &res)
988 return res, err
989 }
990
991 func (h *httpAPI) Buildinfo(ctx context.Context) (BuildinfoResult, error) {
992 u := h.client.URL(epBuildinfo, nil)
993
994 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
995 if err != nil {
996 return BuildinfoResult{}, err
997 }
998
999 _, body, _, err := h.client.Do(ctx, req)
1000 if err != nil {
1001 return BuildinfoResult{}, err
1002 }
1003
1004 var res BuildinfoResult
1005 err = json.Unmarshal(body, &res)
1006 return res, err
1007 }
1008
1009 func (h *httpAPI) Runtimeinfo(ctx context.Context) (RuntimeinfoResult, error) {
1010 u := h.client.URL(epRuntimeinfo, nil)
1011
1012 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
1013 if err != nil {
1014 return RuntimeinfoResult{}, err
1015 }
1016
1017 _, body, _, err := h.client.Do(ctx, req)
1018 if err != nil {
1019 return RuntimeinfoResult{}, err
1020 }
1021
1022 var res RuntimeinfoResult
1023 err = json.Unmarshal(body, &res)
1024 return res, err
1025 }
1026
1027 func (h *httpAPI) LabelNames(ctx context.Context, matches []string, startTime, endTime time.Time, opts ...Option) ([]string, Warnings, error) {
1028 u := h.client.URL(epLabels, nil)
1029 q := addOptionalURLParams(u.Query(), opts)
1030
1031 if !startTime.IsZero() {
1032 q.Set("start", formatTime(startTime))
1033 }
1034 if !endTime.IsZero() {
1035 q.Set("end", formatTime(endTime))
1036 }
1037 for _, m := range matches {
1038 q.Add("match[]", m)
1039 }
1040
1041 _, body, w, err := h.client.DoGetFallback(ctx, u, q)
1042 if err != nil {
1043 return nil, w, err
1044 }
1045 var labelNames []string
1046 err = json.Unmarshal(body, &labelNames)
1047 return labelNames, w, err
1048 }
1049
1050 func (h *httpAPI) LabelValues(ctx context.Context, label string, matches []string, startTime, endTime time.Time, opts ...Option) (model.LabelValues, Warnings, error) {
1051 u := h.client.URL(epLabelValues, map[string]string{"name": label})
1052 q := addOptionalURLParams(u.Query(), opts)
1053
1054 if !startTime.IsZero() {
1055 q.Set("start", formatTime(startTime))
1056 }
1057 if !endTime.IsZero() {
1058 q.Set("end", formatTime(endTime))
1059 }
1060 for _, m := range matches {
1061 q.Add("match[]", m)
1062 }
1063
1064 u.RawQuery = q.Encode()
1065
1066 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
1067 if err != nil {
1068 return nil, nil, err
1069 }
1070 _, body, w, err := h.client.Do(ctx, req)
1071 if err != nil {
1072 return nil, w, err
1073 }
1074 var labelValues model.LabelValues
1075 err = json.Unmarshal(body, &labelValues)
1076 return labelValues, w, err
1077 }
1078
1079 // StatsValue is a type for `stats` query parameter.
1080 type StatsValue string
1081
1082 // AllStatsValue is the query parameter value to return all the query statistics.
1083 const (
1084 AllStatsValue StatsValue = "all"
1085 )
1086
1087 type apiOptions struct {
1088 timeout time.Duration
1089 lookbackDelta time.Duration
1090 stats StatsValue
1091 limit uint64
1092 }
1093
1094 type Option func(c *apiOptions)
1095
1096 // WithTimeout can be used to provide an optional query evaluation timeout for Query and QueryRange.
1097 // https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries
1098 func WithTimeout(timeout time.Duration) Option {
1099 return func(o *apiOptions) {
1100 o.timeout = timeout
1101 }
1102 }
1103
1104 // WithLookbackDelta can be used to provide an optional query lookback delta for Query and QueryRange.
1105 // This URL variable is not documented on Prometheus HTTP API.
1106 // https://github.com/prometheus/prometheus/blob/e04913aea2792a5c8bc7b3130c389ca1b027dd9b/promql/engine.go#L162-L167
1107 func WithLookbackDelta(lookbackDelta time.Duration) Option {
1108 return func(o *apiOptions) {
1109 o.lookbackDelta = lookbackDelta
1110 }
1111 }
1112
1113 // WithStats can be used to provide an optional per step stats for Query and QueryRange.
1114 // This URL variable is not documented on Prometheus HTTP API.
1115 // https://github.com/prometheus/prometheus/blob/e04913aea2792a5c8bc7b3130c389ca1b027dd9b/promql/engine.go#L162-L167
1116 func WithStats(stats StatsValue) Option {
1117 return func(o *apiOptions) {
1118 o.stats = stats
1119 }
1120 }
1121
1122 // WithLimit provides an optional maximum number of returned entries for APIs that support limit parameter
1123 // e.g. https://prometheus.io/docs/prometheus/latest/querying/api/#instant-querie:~:text=%3A%20End%20timestamp.-,limit%3D%3Cnumber%3E,-%3A%20Maximum%20number%20of
1124 func WithLimit(limit uint64) Option {
1125 return func(o *apiOptions) {
1126 o.limit = limit
1127 }
1128 }
1129
1130 func addOptionalURLParams(q url.Values, opts []Option) url.Values {
1131 opt := &apiOptions{}
1132 for _, o := range opts {
1133 o(opt)
1134 }
1135
1136 if opt.timeout > 0 {
1137 q.Set("timeout", opt.timeout.String())
1138 }
1139
1140 if opt.lookbackDelta > 0 {
1141 q.Set("lookback_delta", opt.lookbackDelta.String())
1142 }
1143
1144 if opt.stats != "" {
1145 q.Set("stats", string(opt.stats))
1146 }
1147
1148 if opt.limit > 0 {
1149 q.Set("limit", strconv.FormatUint(opt.limit, 10))
1150 }
1151
1152 return q
1153 }
1154
1155 func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time, opts ...Option) (model.Value, Warnings, error) {
1156 u := h.client.URL(epQuery, nil)
1157 q := addOptionalURLParams(u.Query(), opts)
1158
1159 q.Set("query", query)
1160 if !ts.IsZero() {
1161 q.Set("time", formatTime(ts))
1162 }
1163
1164 _, body, warnings, err := h.client.DoGetFallback(ctx, u, q)
1165 if err != nil {
1166 return nil, warnings, err
1167 }
1168
1169 var qres queryResult
1170 return qres.v, warnings, json.Unmarshal(body, &qres)
1171 }
1172
1173 func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range, opts ...Option) (model.Value, Warnings, error) {
1174 u := h.client.URL(epQueryRange, nil)
1175 q := addOptionalURLParams(u.Query(), opts)
1176
1177 q.Set("query", query)
1178 q.Set("start", formatTime(r.Start))
1179 q.Set("end", formatTime(r.End))
1180 q.Set("step", strconv.FormatFloat(r.Step.Seconds(), 'f', -1, 64))
1181
1182 _, body, warnings, err := h.client.DoGetFallback(ctx, u, q)
1183 if err != nil {
1184 return nil, warnings, err
1185 }
1186
1187 var qres queryResult
1188 return qres.v, warnings, json.Unmarshal(body, &qres)
1189 }
1190
1191 func (h *httpAPI) Series(ctx context.Context, matches []string, startTime, endTime time.Time, opts ...Option) ([]model.LabelSet, Warnings, error) {
1192 u := h.client.URL(epSeries, nil)
1193 q := addOptionalURLParams(u.Query(), opts)
1194
1195 for _, m := range matches {
1196 q.Add("match[]", m)
1197 }
1198
1199 if !startTime.IsZero() {
1200 q.Set("start", formatTime(startTime))
1201 }
1202 if !endTime.IsZero() {
1203 q.Set("end", formatTime(endTime))
1204 }
1205
1206 _, body, warnings, err := h.client.DoGetFallback(ctx, u, q)
1207 if err != nil {
1208 return nil, warnings, err
1209 }
1210
1211 var mset []model.LabelSet
1212 return mset, warnings, json.Unmarshal(body, &mset)
1213 }
1214
1215 func (h *httpAPI) Snapshot(ctx context.Context, skipHead bool) (SnapshotResult, error) {
1216 u := h.client.URL(epSnapshot, nil)
1217 q := u.Query()
1218
1219 q.Set("skip_head", strconv.FormatBool(skipHead))
1220
1221 u.RawQuery = q.Encode()
1222
1223 req, err := http.NewRequest(http.MethodPost, u.String(), nil)
1224 if err != nil {
1225 return SnapshotResult{}, err
1226 }
1227
1228 _, body, _, err := h.client.Do(ctx, req)
1229 if err != nil {
1230 return SnapshotResult{}, err
1231 }
1232
1233 var res SnapshotResult
1234 err = json.Unmarshal(body, &res)
1235 return res, err
1236 }
1237
1238 func (h *httpAPI) Rules(ctx context.Context) (RulesResult, error) {
1239 u := h.client.URL(epRules, nil)
1240
1241 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
1242 if err != nil {
1243 return RulesResult{}, err
1244 }
1245
1246 _, body, _, err := h.client.Do(ctx, req)
1247 if err != nil {
1248 return RulesResult{}, err
1249 }
1250
1251 var res RulesResult
1252 err = json.Unmarshal(body, &res)
1253 return res, err
1254 }
1255
1256 func (h *httpAPI) Targets(ctx context.Context) (TargetsResult, error) {
1257 u := h.client.URL(epTargets, nil)
1258
1259 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
1260 if err != nil {
1261 return TargetsResult{}, err
1262 }
1263
1264 _, body, _, err := h.client.Do(ctx, req)
1265 if err != nil {
1266 return TargetsResult{}, err
1267 }
1268
1269 var res TargetsResult
1270 err = json.Unmarshal(body, &res)
1271 return res, err
1272 }
1273
1274 func (h *httpAPI) TargetsMetadata(ctx context.Context, matchTarget, metric, limit string) ([]MetricMetadata, error) {
1275 u := h.client.URL(epTargetsMetadata, nil)
1276 q := u.Query()
1277
1278 q.Set("match_target", matchTarget)
1279 q.Set("metric", metric)
1280 q.Set("limit", limit)
1281
1282 u.RawQuery = q.Encode()
1283
1284 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
1285 if err != nil {
1286 return nil, err
1287 }
1288
1289 _, body, _, err := h.client.Do(ctx, req)
1290 if err != nil {
1291 return nil, err
1292 }
1293
1294 var res []MetricMetadata
1295 err = json.Unmarshal(body, &res)
1296 return res, err
1297 }
1298
1299 func (h *httpAPI) Metadata(ctx context.Context, metric, limit string) (map[string][]Metadata, error) {
1300 u := h.client.URL(epMetadata, nil)
1301 q := u.Query()
1302
1303 q.Set("metric", metric)
1304 q.Set("limit", limit)
1305
1306 u.RawQuery = q.Encode()
1307
1308 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
1309 if err != nil {
1310 return nil, err
1311 }
1312
1313 _, body, _, err := h.client.Do(ctx, req)
1314 if err != nil {
1315 return nil, err
1316 }
1317
1318 var res map[string][]Metadata
1319 err = json.Unmarshal(body, &res)
1320 return res, err
1321 }
1322
1323 func (h *httpAPI) TSDB(ctx context.Context, opts ...Option) (TSDBResult, error) {
1324 u := h.client.URL(epTSDB, nil)
1325 q := addOptionalURLParams(u.Query(), opts)
1326 u.RawQuery = q.Encode()
1327
1328 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
1329 if err != nil {
1330 return TSDBResult{}, err
1331 }
1332
1333 _, body, _, err := h.client.Do(ctx, req)
1334 if err != nil {
1335 return TSDBResult{}, err
1336 }
1337
1338 var res TSDBResult
1339 err = json.Unmarshal(body, &res)
1340 return res, err
1341 }
1342
1343 func (h *httpAPI) WalReplay(ctx context.Context) (WalReplayStatus, error) {
1344 u := h.client.URL(epWalReplay, nil)
1345
1346 req, err := http.NewRequest(http.MethodGet, u.String(), nil)
1347 if err != nil {
1348 return WalReplayStatus{}, err
1349 }
1350
1351 _, body, _, err := h.client.Do(ctx, req)
1352 if err != nil {
1353 return WalReplayStatus{}, err
1354 }
1355
1356 var res WalReplayStatus
1357 err = json.Unmarshal(body, &res)
1358 return res, err
1359 }
1360
1361 func (h *httpAPI) QueryExemplars(ctx context.Context, query string, startTime, endTime time.Time) ([]ExemplarQueryResult, error) {
1362 u := h.client.URL(epQueryExemplars, nil)
1363 q := u.Query()
1364
1365 q.Set("query", query)
1366 if !startTime.IsZero() {
1367 q.Set("start", formatTime(startTime))
1368 }
1369 if !endTime.IsZero() {
1370 q.Set("end", formatTime(endTime))
1371 }
1372
1373 _, body, _, err := h.client.DoGetFallback(ctx, u, q)
1374 if err != nil {
1375 return nil, err
1376 }
1377
1378 var res []ExemplarQueryResult
1379 err = json.Unmarshal(body, &res)
1380 return res, err
1381 }
1382
1383 // Warnings is an array of non critical errors
1384 type Warnings []string
1385
1386 // apiClient wraps a regular client and processes successful API responses.
1387 // Successful also includes responses that errored at the API level.
1388 type apiClient interface {
1389 URL(ep string, args map[string]string) *url.URL
1390 Do(context.Context, *http.Request) (*http.Response, []byte, Warnings, error)
1391 DoGetFallback(ctx context.Context, u *url.URL, args url.Values) (*http.Response, []byte, Warnings, error)
1392 }
1393
1394 type apiClientImpl struct {
1395 client api.Client
1396 }
1397
1398 type apiResponse struct {
1399 Status string `json:"status"`
1400 Data json.RawMessage `json:"data"`
1401 ErrorType ErrorType `json:"errorType"`
1402 Error string `json:"error"`
1403 Warnings []string `json:"warnings,omitempty"`
1404 }
1405
1406 func apiError(code int) bool {
1407 // These are the codes that Prometheus sends when it returns an error.
1408 return code == http.StatusUnprocessableEntity || code == http.StatusBadRequest
1409 }
1410
1411 func errorTypeAndMsgFor(resp *http.Response) (ErrorType, string) {
1412 switch resp.StatusCode / 100 {
1413 case 4:
1414 return ErrClient, fmt.Sprintf("client error: %d", resp.StatusCode)
1415 case 5:
1416 return ErrServer, fmt.Sprintf("server error: %d", resp.StatusCode)
1417 }
1418 return ErrBadResponse, fmt.Sprintf("bad response code %d", resp.StatusCode)
1419 }
1420
1421 func (h *apiClientImpl) URL(ep string, args map[string]string) *url.URL {
1422 return h.client.URL(ep, args)
1423 }
1424
1425 func (h *apiClientImpl) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, Warnings, error) {
1426 resp, body, err := h.client.Do(ctx, req)
1427 if err != nil {
1428 return resp, body, nil, err
1429 }
1430
1431 code := resp.StatusCode
1432
1433 if code/100 != 2 && !apiError(code) {
1434 errorType, errorMsg := errorTypeAndMsgFor(resp)
1435 return resp, body, nil, &Error{
1436 Type: errorType,
1437 Msg: errorMsg,
1438 Detail: string(body),
1439 }
1440 }
1441
1442 var result apiResponse
1443
1444 if http.StatusNoContent != code {
1445 if jsonErr := json.Unmarshal(body, &result); jsonErr != nil {
1446 return resp, body, nil, &Error{
1447 Type: ErrBadResponse,
1448 Msg: jsonErr.Error(),
1449 }
1450 }
1451 }
1452
1453 if apiError(code) && result.Status == "success" {
1454 err = &Error{
1455 Type: ErrBadResponse,
1456 Msg: "inconsistent body for response code",
1457 }
1458 }
1459
1460 if result.Status == "error" {
1461 err = &Error{
1462 Type: result.ErrorType,
1463 Msg: result.Error,
1464 }
1465 }
1466
1467 return resp, []byte(result.Data), result.Warnings, err
1468 }
1469
1470 // DoGetFallback will attempt to do the request as-is, and on a 405 or 501 it
1471 // will fallback to a GET request.
1472 func (h *apiClientImpl) DoGetFallback(ctx context.Context, u *url.URL, args url.Values) (*http.Response, []byte, Warnings, error) {
1473 encodedArgs := args.Encode()
1474 req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(encodedArgs))
1475 if err != nil {
1476 return nil, nil, nil, err
1477 }
1478 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
1479 // Following comment originates from https://pkg.go.dev/net/http#Transport
1480 // Transport only retries a request upon encountering a network error if the request is
1481 // idempotent and either has no body or has its Request.GetBody defined. HTTP requests
1482 // are considered idempotent if they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or
1483 // if their Header map contains an "Idempotency-Key" or "X-Idempotency-Key" entry. If the
1484 // idempotency key value is a zero-length slice, the request is treated as idempotent but
1485 // the header is not sent on the wire.
1486 req.Header["Idempotency-Key"] = nil
1487
1488 resp, body, warnings, err := h.Do(ctx, req)
1489 if resp != nil && (resp.StatusCode == http.StatusMethodNotAllowed || resp.StatusCode == http.StatusNotImplemented) {
1490 u.RawQuery = encodedArgs
1491 req, err = http.NewRequest(http.MethodGet, u.String(), nil)
1492 if err != nil {
1493 return nil, nil, warnings, err
1494 }
1495 return h.Do(ctx, req)
1496 }
1497 return resp, body, warnings, err
1498 }
1499
1500 func formatTime(t time.Time) string {
1501 return strconv.FormatFloat(float64(t.Unix())+float64(t.Nanosecond())/1e9, 'f', -1, 64)
1502 }