forked from grafana/cortex-tools
/
remote_read.go
441 lines (369 loc) · 10.4 KB
/
remote_read.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package commands
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"text/tabwriter"
"time"
config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/pkg/value"
"github.com/prometheus/prometheus/prompb"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/storage/remote"
log "github.com/sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/cortexproject/cortex-tools/pkg/backfill"
)
type RemoteReadCommand struct {
address string
remoteReadPath string
tenantID string
apiKey string
readTimeout time.Duration
tsdbPath string
selector string
from string
to string
}
func (c *RemoteReadCommand) Register(app *kingpin.Application) {
remoteReadCmd := app.Command("remote-read", "Inspect stored series in Cortex using the remote read API.")
exportCmd := remoteReadCmd.Command("export", "Export metrics remote read series into a local TSDB.").Action(c.export)
dumpCmd := remoteReadCmd.Command("dump", "Dump remote read series.").Action(c.dump)
statsCmd := remoteReadCmd.Command("stats", "Show statistic of remote read series.").Action(c.stats)
now := time.Now()
for _, cmd := range []*kingpin.CmdClause{exportCmd, dumpCmd, statsCmd} {
cmd.Flag("address", "Address of the cortex cluster, alternatively set $CORTEX_ADDRESS.").
Envar("CORTEX_ADDRESS").
Required().
StringVar(&c.address)
cmd.Flag("remote-read-path", "Path of the remote read endpoint.").
Default("/prometheus/api/v1/read").
StringVar(&c.remoteReadPath)
cmd.Flag("id", "Cortex tenant id, alternatively set $CORTEX_TENANT_ID.").
Envar("CORTEX_TENANT_ID").
Default("").
StringVar(&c.tenantID)
cmd.Flag("key", "Api key to use when contacting cortex, alternatively set $CORTEX_API_KEY.").
Envar("CORTEX_API_KEY").
Default("").
StringVar(&c.apiKey)
cmd.Flag("read-timeout", "timeout for read requests").
Default("30s").
DurationVar(&c.readTimeout)
cmd.Flag("selector", `PromQL selector to filter metrics on. To return all metrics '{__name__!=""}' can be used.`).
Default("up").
StringVar(&c.selector)
cmd.Flag("from", "Start of the time window to select metrics.").
Default(now.Add(-time.Hour).Format(time.RFC3339)).
StringVar(&c.from)
cmd.Flag("to", "End of the time window to select metrics.").
Default(now.Format(time.RFC3339)).
StringVar(&c.to)
}
exportCmd.Flag("tsdb-path", "Path to the folder where to store the TSDB blocks, if not set a new directory in $TEMP is created.").
Default("").
StringVar(&c.tsdbPath)
}
type setTenantIDTransport struct {
http.RoundTripper
tenantID string
}
func (s *setTenantIDTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("X-Scope-OrgID", s.tenantID)
return s.RoundTripper.RoundTrip(req)
}
type timeSeriesIterator struct {
posSeries int
posSample int
ts []*prompb.TimeSeries
// labels slice is reused across samples within a series
labels labels.Labels
labelsSeriesPos int
}
func newTimeSeriesIterator(ts []*prompb.TimeSeries) *timeSeriesIterator {
return &timeSeriesIterator{
posSeries: 0,
posSample: -1,
// ensure we are not pointing to a valid slice position
labelsSeriesPos: -1,
ts: ts,
}
}
func (i *timeSeriesIterator) Next() error {
if i.posSeries >= len(i.ts) {
return io.EOF
}
i.posSample++
if i.posSample >= len(i.ts[i.posSeries].Samples) {
i.posSample = -1
i.posSeries++
return i.Next()
}
return nil
}
func (i *timeSeriesIterator) Labels() (l labels.Labels) {
// if it's the same label as previously return it
if i.posSeries == i.labelsSeriesPos {
return i.labels
}
series := i.ts[i.posSeries]
i.labels = make(labels.Labels, len(series.Labels))
for posLabel := range series.Labels {
i.labels[posLabel].Name = series.Labels[posLabel].Name
i.labels[posLabel].Value = series.Labels[posLabel].Value
}
i.labelsSeriesPos = i.posSeries
return i.labels
}
func (i *timeSeriesIterator) Sample() (ts int64, v float64) {
series := i.ts[i.posSeries]
sample := series.Samples[i.posSample]
//sample.GetValue()
return sample.GetTimestamp(), sample.GetValue()
}
// this is adapted from Go 1.15 for older versions
// TODO: Reuse upstream once that version is common
func redactedURL(u *url.URL) string {
if u == nil {
return ""
}
ru := *u
if _, has := ru.User.Password(); has {
ru.User = url.UserPassword(ru.User.Username(), "xxxxx")
}
return ru.String()
}
func (c *RemoteReadCommand) readClient() (remote.ReadClient, error) {
// validate inputs
addressURL, err := url.Parse(c.address)
if err != nil {
return nil, err
}
addressURL.Path = filepath.Join(
addressURL.Path,
c.remoteReadPath,
)
// build client
readClient, err := remote.NewReadClient("remote-read", &remote.ClientConfig{
URL: &config_util.URL{URL: addressURL},
Timeout: model.Duration(c.readTimeout),
HTTPClientConfig: config_util.HTTPClientConfig{
BasicAuth: &config_util.BasicAuth{
Username: c.tenantID,
Password: config_util.Secret(c.apiKey),
},
},
})
if err != nil {
return nil, err
}
// if tenant ID is set, add a tenant ID header to every request
if c.tenantID != "" {
client, ok := readClient.(*remote.Client)
if !ok {
return nil, fmt.Errorf("unexpected type %T", readClient)
}
client.Client.Transport = &setTenantIDTransport{
RoundTripper: client.Client.Transport,
tenantID: c.tenantID,
}
}
log.Infof("Created remote read client using endpoint '%s'", redactedURL(addressURL))
return readClient, nil
}
// prepare() validates the input and prepares the client to query remote read endpoints
func (c *RemoteReadCommand) prepare() (query func(context.Context) ([]*prompb.TimeSeries, error), from, to time.Time, err error) {
from, err = time.Parse(time.RFC3339, c.from)
if err != nil {
return nil, time.Time{}, time.Time{}, fmt.Errorf("error parsing from: '%s' value: %w", c.from, err)
}
to, err = time.Parse(time.RFC3339, c.to)
if err != nil {
return nil, time.Time{}, time.Time{}, fmt.Errorf("error parsing to: '%s' value: %w", c.to, err)
}
matchers, err := parser.ParseMetricSelector(c.selector)
if err != nil {
return nil, time.Time{}, time.Time{}, err
}
readClient, err := c.readClient()
if err != nil {
return nil, time.Time{}, time.Time{}, err
}
pbQuery, err := remote.ToQuery(
int64(model.TimeFromUnixNano(from.UnixNano())),
int64(model.TimeFromUnixNano(to.UnixNano())),
matchers,
nil,
)
if err != nil {
return nil, time.Time{}, time.Time{}, err
}
return func(ctx context.Context) ([]*prompb.TimeSeries, error) {
log.Infof("Querying time from=%s to=%s with selector=%s", from.Format(time.RFC3339), to.Format(time.RFC3339), c.selector)
resp, err := readClient.Read(ctx, pbQuery)
if err != nil {
return nil, err
}
return resp.Timeseries, nil
}, from, to, nil
}
func (c *RemoteReadCommand) dump(k *kingpin.ParseContext) error {
query, _, _, err := c.prepare()
if err != nil {
return err
}
timeseries, err := query(context.Background())
if err != nil {
return nil
}
iterator := newTimeSeriesIterator(timeseries)
for {
err := iterator.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
l := iterator.Labels()
ts, v := iterator.Sample()
comment := ""
if value.IsStaleNaN(v) {
comment = " # StaleNaN"
}
fmt.Printf("%s %g %d%s\n", l, v, ts, comment)
}
return nil
}
func (c *RemoteReadCommand) stats(k *kingpin.ParseContext) error {
query, _, _, err := c.prepare()
if err != nil {
return err
}
timeseries, err := query(context.Background())
if err != nil {
return nil
}
num := struct {
Samples int64
Series map[string]struct{}
NaNValues int64
StaleNaNValues int64
MinT model.Time
MaxT model.Time
}{
Series: make(map[string]struct{}),
}
iterator := newTimeSeriesIterator(timeseries)
for {
err := iterator.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
num.Samples++
num.Series[iterator.Labels().String()] = struct{}{}
ts, v := iterator.Sample()
if int64(num.MaxT) < ts {
num.MaxT = model.Time(ts)
}
if num.MinT == 0 || int64(num.MinT) > ts {
num.MinT = model.Time(ts)
}
if math.IsNaN(v) {
num.NaNValues++
}
if value.IsStaleNaN(v) {
num.StaleNaNValues++
}
}
output := bytes.NewBuffer(nil)
tw := tabwriter.NewWriter(output, 13, 0, 2, ' ', 0)
fmt.Fprintln(tw, "MIN TIME\tMAX TIME\tDURATION\tNUM SAMPLES\tNUM SERIES\tNUM STALE NAN VALUES\tNUM NAN VALUES")
fmt.Fprintf(
tw,
"%s\t%s\t%s\t%d\t%d\t%d\t%d\n",
num.MinT.Time().UTC().String(),
num.MaxT.Time().UTC().String(),
num.MaxT.Sub(num.MinT),
num.Samples,
len(num.Series),
num.StaleNaNValues,
num.NaNValues,
)
if err := tw.Flush(); err != nil {
return err
}
for _, line := range strings.Split(output.String(), "\n") {
if len(line) != 0 {
log.Info(line)
}
}
return nil
}
func (c *RemoteReadCommand) export(k *kingpin.ParseContext) error {
query, from, to, err := c.prepare()
if err != nil {
return err
}
if c.tsdbPath == "" {
c.tsdbPath, err = ioutil.TempDir("", "cortextool-tsdb")
if err != nil {
return err
}
log.Infof("Created TSDB in path '%s'", c.tsdbPath)
} else {
if _, err := os.Stat(c.tsdbPath); err != nil && os.IsNotExist(err) {
if err = os.Mkdir(c.tsdbPath, 0755); err != nil {
return err
}
log.Infof("Created TSDB in path '%s'", c.tsdbPath)
}
log.Infof("Using existing TSDB in path '%s'", c.tsdbPath)
}
mint := model.TimeFromUnixNano(from.UnixNano())
maxt := model.TimeFromUnixNano(to.UnixNano())
timeseries, err := query(context.Background())
if err != nil {
return err
}
iterator := func() backfill.Iterator {
return newTimeSeriesIterator(timeseries)
}
pipeR, pipeW := io.Pipe()
go func() {
scanner := bufio.NewScanner(pipeR)
for scanner.Scan() {
log.Info(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Error("reading block status:", err)
}
}()
defer pipeR.Close()
log.Infof("Store TSDB blocks in '%s'", c.tsdbPath)
if err := backfill.CreateBlocks(iterator, int64(mint), int64(maxt), 1000, c.tsdbPath, true, pipeW); err != nil {
return err
}
// ensure that tsdb directory has WAL, otherwise 'promtool tsdb dump' fails
walPath := filepath.Join(c.tsdbPath, "wal")
if _, err := os.Stat(walPath); err != nil && os.IsNotExist(err) {
if err := os.Mkdir(walPath, 0755); err != nil {
return err
}
}
return nil
}