-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
metrics_handler.go
230 lines (215 loc) · 6.92 KB
/
metrics_handler.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package asynqmon
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type getMetricsResponse struct {
QueueSize *json.RawMessage `json:"queue_size"`
QueueLatency *json.RawMessage `json:"queue_latency_seconds"`
QueueMemUsgApprox *json.RawMessage `json:"queue_memory_usage_approx_bytes"`
ProcessedPerSecond *json.RawMessage `json:"tasks_processed_per_second"`
FailedPerSecond *json.RawMessage `json:"tasks_failed_per_second"`
ErrorRate *json.RawMessage `json:"error_rate"`
PendingTasksByQueue *json.RawMessage `json:"pending_tasks_by_queue"`
RetryTasksByQueue *json.RawMessage `json:"retry_tasks_by_queue"`
ArchivedTasksByQueue *json.RawMessage `json:"archived_tasks_by_queue"`
}
type metricsFetchOptions struct {
// Specifies the number of seconds to scan for metrics.
duration time.Duration
// Specifies the end time when fetching metrics.
endTime time.Time
// Optional filter to speicify a list of queues to get metrics for.
// Empty list indicates no filter (i.e. get metrics for all queues).
queues []string
}
func newGetMetricsHandlerFunc(client *http.Client, prometheusAddr string) http.HandlerFunc {
// res is the result of calling a JSON API endpoint.
type res struct {
query string
msg *json.RawMessage
err error
}
// List of PromQLs.
// Strings are used as template to optionally insert queue filter specified by QUEUE_FILTER.
const (
promQLQueueSize = "asynq_queue_size{QUEUE_FILTER}"
promQLQueueLatency = "asynq_queue_latency_seconds{QUEUE_FILTER}"
promQLMemUsage = "asynq_queue_memory_usage_approx_bytes{QUEUE_FILTER}"
promQLProcessedTasks = "rate(asynq_tasks_processed_total{QUEUE_FILTER}[5m])"
promQLFailedTasks = "rate(asynq_tasks_failed_total{QUEUE_FILTER}[5m])"
promQLErrorRate = "rate(asynq_tasks_failed_total{QUEUE_FILTER}[5m]) / rate(asynq_tasks_processed_total{QUEUE_FILTER}[5m])"
promQLPendingTasks = "asynq_tasks_enqueued_total{state=\"pending\",QUEUE_FILTER}"
promQLRetryTasks = "asynq_tasks_enqueued_total{state=\"retry\",QUEUE_FILTER}"
promQLArchivedTasks = "asynq_tasks_enqueued_total{state=\"archived\",QUEUE_FILTER}"
)
// Optional query params:
// `duration_sec`: specifies the number of seconds to scan
// `end_time`: specifies the end_time in Unix time seconds
return func(w http.ResponseWriter, r *http.Request) {
opts, err := extractMetricsFetchOptions(r)
if err != nil {
http.Error(w, fmt.Sprintf("invalid query parameter: %v", err), http.StatusBadRequest)
return
}
// List of queries (i.e. promQL) to send to prometheus server.
queries := []string{
promQLQueueSize,
promQLQueueLatency,
promQLMemUsage,
promQLProcessedTasks,
promQLFailedTasks,
promQLErrorRate,
promQLPendingTasks,
promQLRetryTasks,
promQLArchivedTasks,
}
resp := getMetricsResponse{}
// Make multiple API calls concurrently
n := len(queries)
ch := make(chan res, len(queries))
for _, q := range queries {
go func(q string) {
url := buildPrometheusURL(prometheusAddr, q, opts)
msg, err := fetchPrometheusMetrics(client, url)
ch <- res{q, msg, err}
}(q)
}
for r := range ch {
n--
if r.err != nil {
http.Error(w, fmt.Sprintf("failed to fetch %q: %v", r.query, r.err), http.StatusInternalServerError)
return
}
switch r.query {
case promQLQueueSize:
resp.QueueSize = r.msg
case promQLQueueLatency:
resp.QueueLatency = r.msg
case promQLMemUsage:
resp.QueueMemUsgApprox = r.msg
case promQLProcessedTasks:
resp.ProcessedPerSecond = r.msg
case promQLFailedTasks:
resp.FailedPerSecond = r.msg
case promQLErrorRate:
resp.ErrorRate = r.msg
case promQLPendingTasks:
resp.PendingTasksByQueue = r.msg
case promQLRetryTasks:
resp.RetryTasksByQueue = r.msg
case promQLArchivedTasks:
resp.ArchivedTasksByQueue = r.msg
}
if n == 0 {
break // fetched all metrics
}
}
bytes, err := json.Marshal(resp)
if err != nil {
http.Error(w, fmt.Sprintf("failed to marshal response into JSON: %v", err), http.StatusInternalServerError)
return
}
if _, err := w.Write(bytes); err != nil {
http.Error(w, fmt.Sprintf("failed to write to response: %v", err), http.StatusInternalServerError)
return
}
}
}
const prometheusAPIPath = "/api/v1/query_range"
func extractMetricsFetchOptions(r *http.Request) (*metricsFetchOptions, error) {
opts := &metricsFetchOptions{
duration: 60 * time.Minute,
endTime: time.Now(),
}
q := r.URL.Query()
if d := q.Get("duration"); d != "" {
val, err := strconv.Atoi(d)
if err != nil {
return nil, fmt.Errorf("invalid value provided for duration: %q", d)
}
opts.duration = time.Duration(val) * time.Second
}
if t := q.Get("endtime"); t != "" {
val, err := strconv.Atoi(t)
if err != nil {
return nil, fmt.Errorf("invalid value provided for end_time: %q", t)
}
opts.endTime = time.Unix(int64(val), 0)
}
if qs := q.Get("queues"); qs != "" {
opts.queues = strings.Split(qs, ",")
}
return opts, nil
}
func buildPrometheusURL(baseAddr, promQL string, opts *metricsFetchOptions) string {
var b strings.Builder
b.WriteString(strings.TrimSuffix(baseAddr, "/"))
b.WriteString(prometheusAPIPath)
v := url.Values{}
v.Add("query", applyQueueFilter(promQL, opts.queues))
v.Add("start", unixTimeString(opts.endTime.Add(-opts.duration)))
v.Add("end", unixTimeString(opts.endTime))
v.Add("step", strconv.Itoa(int(step(opts).Seconds())))
b.WriteString("?")
b.WriteString(v.Encode())
return b.String()
}
func applyQueueFilter(promQL string, qnames []string) string {
if len(qnames) == 0 {
return strings.ReplaceAll(promQL, "QUEUE_FILTER", "")
}
var b strings.Builder
b.WriteString(`queue=~"`)
for i, q := range qnames {
if i != 0 {
b.WriteString("|")
}
b.WriteString(q)
}
b.WriteByte('"')
return strings.ReplaceAll(promQL, "QUEUE_FILTER", b.String())
}
func fetchPrometheusMetrics(client *http.Client, url string) (*json.RawMessage, error) {
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
msg := json.RawMessage(bytes)
return &msg, err
}
// Returns step to use given the fetch options.
// In general, the longer the duration, longer the each step.
func step(opts *metricsFetchOptions) time.Duration {
if opts.duration <= 6*time.Hour {
// maximum number of data points to return: 6h / 10s = 2160
return 10 * time.Second
}
if opts.duration <= 24*time.Hour {
// maximum number of data points to return: 24h / 1m = 1440
return 1 * time.Minute
}
if opts.duration <= 8*24*time.Hour {
// maximum number of data points to return: (8*24)h / 3m = 3840
return 3 * time.Minute
}
if opts.duration <= 30*24*time.Hour {
// maximum number of data points to return: (30*24)h / 10m = 4320
return 10 * time.Minute
}
return opts.duration / 3000
}
func unixTimeString(t time.Time) string {
return strconv.Itoa(int(t.Unix()))
}