-
Notifications
You must be signed in to change notification settings - Fork 46
/
query.go
191 lines (164 loc) · 4.84 KB
/
query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package promapi
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"math"
"net/http"
"net/url"
"time"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prymitive/current"
)
type QueryResult struct {
URI string
Series []Sample
Stats QueryStats
}
type instantQuery struct {
timestamp time.Time
ctx context.Context
prom *Prometheus
expr string
}
func (q instantQuery) Run() queryResult {
slog.Debug(
"Running prometheus query",
slog.String("uri", q.prom.safeURI),
slog.String("query", q.expr),
)
ctx, cancel := q.prom.requestContext(q.ctx)
defer cancel()
var qr queryResult
args := url.Values{}
args.Set("query", q.expr)
args.Set("timeout", q.prom.timeout.String())
args.Set("stats", "1")
resp, err := q.prom.doRequest(ctx, http.MethodPost, q.Endpoint(), args)
if err != nil {
qr.err = err
return qr
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
qr.err = tryDecodingAPIError(resp)
return qr
}
qr.value, qr.stats, qr.err = streamSamples(resp.Body)
return qr
}
func (q instantQuery) Endpoint() string {
return "/api/v1/query"
}
func (q instantQuery) String() string {
return q.expr
}
func (q instantQuery) CacheKey() uint64 {
return hash(q.prom.unsafeURI, q.Endpoint(), q.expr)
}
func (q instantQuery) CacheTTL() time.Duration {
return time.Minute * 5
}
func (p *Prometheus) Query(ctx context.Context, expr string) (*QueryResult, error) {
slog.Debug("Scheduling prometheus query", slog.String("uri", p.safeURI), slog.String("query", expr))
key := fmt.Sprintf("/api/v1/query/%s", expr)
p.locker.lock(key)
defer p.locker.unlock(key)
resultChan := make(chan queryResult)
p.queries <- queryRequest{
query: instantQuery{prom: p, ctx: ctx, expr: expr, timestamp: time.Now()},
result: resultChan,
}
result := <-resultChan
if result.err != nil {
return nil, QueryError{err: result.err, msg: decodeError(result.err)}
}
qr := QueryResult{
URI: p.publicURI,
Series: result.value.([]Sample),
Stats: result.stats,
}
slog.Debug("Parsed response", slog.String("uri", p.safeURI), slog.String("query", expr), slog.Int("series", len(qr.Series)))
return &qr, nil
}
type Sample struct {
Labels labels.Labels
Value float64
}
func streamSamples(r io.Reader) (samples []Sample, stats QueryStats, err error) {
defer dummyReadAll(r)
var status, resultType, errType, errText string
samples = []Sample{}
var sample model.Sample
decoder := current.Object(
current.Key("status", current.Value(func(s string, _ bool) {
status = s
})),
current.Key("error", current.Value(func(s string, _ bool) {
errText = s
})),
current.Key("errorType", current.Value(func(s string, _ bool) {
errType = s
})),
current.Key("data", current.Object(
current.Key("resultType", current.Value(func(s string, _ bool) {
resultType = s
})),
current.Key("result", current.Array(
&sample,
func() {
samples = append(samples, Sample{
Labels: MetricToLabels(sample.Metric),
Value: float64(sample.Value),
})
sample.Metric = model.Metric{}
},
)),
current.Key("stats", current.Object(
current.Key("timings", current.Object(
current.Key("evalTotalTime", current.Value(func(v float64, _ bool) {
stats.Timings.EvalTotalTime = v
})),
current.Key("resultSortTime", current.Value(func(v float64, _ bool) {
stats.Timings.ResultSortTime = v
})),
current.Key("queryPreparationTime", current.Value(func(v float64, _ bool) {
stats.Timings.QueryPreparationTime = v
})),
current.Key("innerEvalTime", current.Value(func(v float64, _ bool) {
stats.Timings.InnerEvalTime = v
})),
current.Key("execQueueTime", current.Value(func(v float64, _ bool) {
stats.Timings.ExecQueueTime = v
})),
current.Key("execTotalTime", current.Value(func(v float64, _ bool) {
stats.Timings.ExecTotalTime = v
})),
)),
current.Key("samples", current.Object(
current.Key("totalQueryableSamples", current.Value(func(v float64, _ bool) {
stats.Samples.TotalQueryableSamples = int(math.Round(v))
})),
current.Key("peakSamples", current.Value(func(v float64, _ bool) {
stats.Samples.PeakSamples = int(math.Round(v))
})),
)),
)),
)),
)
dec := json.NewDecoder(r)
if err = decoder.Stream(dec); err != nil {
return nil, stats, APIError{Status: status, ErrorType: v1.ErrBadResponse, Err: fmt.Sprintf("JSON parse error: %s", err)}
}
if status != "success" {
return nil, stats, APIError{Status: status, ErrorType: decodeErrorType(errType), Err: errText}
}
if resultType != "vector" {
return nil, stats, APIError{Status: status, ErrorType: v1.ErrBadResponse, Err: fmt.Sprintf("invalid result type, expected vector, got %s", resultType)}
}
return samples, stats, nil
}