forked from thanos-io/thanos
/
bucket.go
417 lines (357 loc) · 12.7 KB
/
bucket.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
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"text/template"
"time"
"github.com/go-kit/kit/log"
"github.com/improbable-eng/thanos/pkg/block"
"github.com/improbable-eng/thanos/pkg/block/metadata"
"github.com/improbable-eng/thanos/pkg/objstore"
"github.com/improbable-eng/thanos/pkg/objstore/client"
"github.com/improbable-eng/thanos/pkg/runutil"
"github.com/improbable-eng/thanos/pkg/verifier"
"github.com/oklog/run"
"github.com/oklog/ulid"
"github.com/olekukonko/tablewriter"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/tsdb/labels"
"golang.org/x/text/language"
"golang.org/x/text/message"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
issuesMap = map[string]verifier.Issue{
verifier.IndexIssueID: verifier.IndexIssue,
verifier.OverlappedBlocksIssueID: verifier.OverlappedBlocksIssue,
verifier.DuplicatedCompactionIssueID: verifier.DuplicatedCompactionIssue,
}
allIssues = func() (s []string) {
for id := range issuesMap {
s = append(s, id)
}
sort.Strings(s)
return s
}
inspectColumns = []string{"ULID", "FROM", "UNTIL", "RANGE", "UNTIL-COMP", "#SERIES", "#SAMPLES", "#CHUNKS", "COMP-LEVEL", "COMP-FAILED", "LABELS", "RESOLUTION", "SOURCE"}
)
func registerBucket(m map[string]setupFunc, app *kingpin.Application, name string) {
cmd := app.Command(name, "Bucket utility commands")
objStoreConfig := regCommonObjStoreFlags(cmd, "", true)
registerBucketVerify(m, cmd, name, objStoreConfig)
registerBucketLs(m, cmd, name, objStoreConfig)
registerBucketInspect(m, cmd, name, objStoreConfig)
return
}
func registerBucketVerify(m map[string]setupFunc, root *kingpin.CmdClause, name string, objStoreConfig *pathOrContent) {
cmd := root.Command("verify", "Verify all blocks in the bucket against specified issues")
objStoreBackupConfig := regCommonObjStoreFlags(cmd, "-backup", false, "Used for repair logic to backup blocks before removal.")
repair := cmd.Flag("repair", "Attempt to repair blocks for which issues were detected").
Short('r').Default("false").Bool()
issuesToVerify := cmd.Flag("issues", fmt.Sprintf("Issues to verify (and optionally repair). Possible values: %v", allIssues())).
Short('i').Default(verifier.IndexIssueID, verifier.OverlappedBlocksIssueID).Strings()
idWhitelist := cmd.Flag("id-whitelist", "Block IDs to verify (and optionally repair) only. "+
"If none is specified, all blocks will be verified. Repeated field").Strings()
m[name+" verify"] = func(g *run.Group, logger log.Logger, reg *prometheus.Registry, _ opentracing.Tracer, _ bool) error {
confContentYaml, err := objStoreConfig.Content()
if err != nil {
return err
}
bkt, err := client.NewBucket(logger, confContentYaml, reg, name)
if err != nil {
return err
}
defer runutil.CloseWithLogOnErr(logger, bkt, "bucket client")
backupconfContentYaml, err := objStoreBackupConfig.Content()
if err != nil {
return err
}
var backupBkt objstore.Bucket
if len(backupconfContentYaml) == 0 {
if *repair {
return errors.Wrap(err, "repair is specified, so backup client is required")
}
} else {
backupBkt, err = client.NewBucket(logger, backupconfContentYaml, reg, name)
if err != nil {
return err
}
defer runutil.CloseWithLogOnErr(logger, backupBkt, "backup bucket client")
}
// Dummy actor to immediately kill the group after the run function returns.
g.Add(func() error { return nil }, func(error) {})
var (
ctx = context.Background()
v *verifier.Verifier
issues []verifier.Issue
)
for _, i := range *issuesToVerify {
issueFn, ok := issuesMap[i]
if !ok {
return errors.Errorf("no such issue name %s", i)
}
issues = append(issues, issueFn)
}
if *repair {
v = verifier.NewWithRepair(logger, bkt, backupBkt, issues)
} else {
v = verifier.New(logger, bkt, issues)
}
var idMatcher func(ulid.ULID) bool = nil
if len(*idWhitelist) > 0 {
whilelistIDs := map[string]struct{}{}
for _, bid := range *idWhitelist {
id, err := ulid.Parse(bid)
if err != nil {
return errors.Wrap(err, "invalid ULID found in --id-whitelist flag")
}
whilelistIDs[id.String()] = struct{}{}
}
idMatcher = func(id ulid.ULID) bool {
if _, ok := whilelistIDs[id.String()]; !ok {
return false
}
return true
}
}
return v.Verify(ctx, idMatcher)
}
}
func registerBucketLs(m map[string]setupFunc, root *kingpin.CmdClause, name string, objStoreConfig *pathOrContent) {
cmd := root.Command("ls", "List all blocks in the bucket")
output := cmd.Flag("output", "Optional format in which to print each block's information. Options are 'json', 'wide' or a custom template.").
Short('o').Default("").String()
m[name+" ls"] = func(g *run.Group, logger log.Logger, reg *prometheus.Registry, _ opentracing.Tracer, _ bool) error {
confContentYaml, err := objStoreConfig.Content()
if err != nil {
return err
}
bkt, err := client.NewBucket(logger, confContentYaml, reg, name)
if err != nil {
return err
}
// Dummy actor to immediately kill the group after the run function returns.
g.Add(func() error { return nil }, func(error) {})
defer runutil.CloseWithLogOnErr(logger, bkt, "bucket client")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
var (
format = *output
printBlock func(id ulid.ULID) error
)
switch format {
case "":
printBlock = func(id ulid.ULID) error {
fmt.Fprintln(os.Stdout, id.String())
return nil
}
case "wide":
printBlock = func(id ulid.ULID) error {
m, err := block.DownloadMeta(ctx, logger, bkt, id)
if err != nil {
return err
}
minTime := time.Unix(m.MinTime/1000, 0)
maxTime := time.Unix(m.MaxTime/1000, 0)
if _, err = fmt.Fprintf(os.Stdout, "%s -- %s - %s Diff: %s, Compaction: %d, Downsample: %d, Source: %s\n",
m.ULID, minTime.Format("2006-01-02 15:04"), maxTime.Format("2006-01-02 15:04"), maxTime.Sub(minTime),
m.Compaction.Level, m.Thanos.Downsample.Resolution, m.Thanos.Source); err != nil {
return err
}
return nil
}
case "json":
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", "\t")
printBlock = func(id ulid.ULID) error {
m, err := block.DownloadMeta(ctx, logger, bkt, id)
if err != nil {
return err
}
return enc.Encode(&m)
}
default:
tmpl, err := template.New("").Parse(format)
if err != nil {
return errors.Wrap(err, "invalid template")
}
printBlock = func(id ulid.ULID) error {
m, err := block.DownloadMeta(ctx, logger, bkt, id)
if err != nil {
return err
}
if err := tmpl.Execute(os.Stdout, &m); err != nil {
return errors.Wrap(err, "execute template")
}
fmt.Fprintln(os.Stdout, "")
return nil
}
}
return bkt.Iter(ctx, "", func(name string) error {
id, ok := block.IsBlockDir(name)
if !ok {
return nil
}
return printBlock(id)
})
}
}
func registerBucketInspect(m map[string]setupFunc, root *kingpin.CmdClause, name string, objStoreConfig *pathOrContent) {
cmd := root.Command("inspect", "Inspect all blocks in the bucket in detailed, table-like way")
selector := cmd.Flag("selector", "Selects blocks based on label, e.g. '-l key1=\"value1\" -l key2=\"value2\"'. All key value pairs must match.").Short('l').
PlaceHolder("<name>=\"<value>\"").Strings()
sortBy := cmd.Flag("sort-by", "Sort by columns. It's also possible to sort by multiple columns, e.g. '--sort-by FROM --sort-by UNTIL'. I.e., if the 'FROM' value is equal the rows are then further sorted by the 'UNTIL' value.").
Default("FROM", "UNTIL").Enums(inspectColumns...)
m[name+" inspect"] = func(g *run.Group, logger log.Logger, reg *prometheus.Registry, _ opentracing.Tracer, _ bool) error {
// Parse selector.
selectorLabels, err := parseFlagLabels(*selector)
if err != nil {
return fmt.Errorf("error parsing selector flag: %v", err)
}
confContentYaml, err := objStoreConfig.Content()
if err != nil {
return err
}
bkt, err := client.NewBucket(logger, confContentYaml, reg, name)
if err != nil {
return err
}
// Dummy actor to immediately kill the group after the run function returns.
g.Add(func() error { return nil }, func(error) {})
defer runutil.CloseWithLogOnErr(logger, bkt, "bucket client")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
// Getting Metas.
var blockMetas []*metadata.Meta
if err = bkt.Iter(ctx, "", func(name string) error {
id, ok := block.IsBlockDir(name)
if !ok {
return nil
}
m, err := block.DownloadMeta(ctx, logger, bkt, id)
if err != nil {
return err
}
blockMetas = append(blockMetas, &m)
return nil
}); err != nil {
return err
}
return printTable(blockMetas, selectorLabels, *sortBy)
}
}
func printTable(blockMetas []*metadata.Meta, selectorLabels labels.Labels, sortBy []string) error {
header := inspectColumns
var lines [][]string
p := message.NewPrinter(language.English)
for _, blockMeta := range blockMetas {
if !matchesSelector(blockMeta, selectorLabels) {
continue
}
timeRange := time.Duration((blockMeta.MaxTime - blockMeta.MinTime) * int64(time.Millisecond))
// Calculate how long it takes until the next compaction.
untilComp := "-"
if blockMeta.Thanos.Downsample.Resolution == 0 { // data currently raw, downsample if range >= 40 hours
untilComp = (time.Duration(40*60*60*1000*time.Millisecond) - timeRange).String()
}
if blockMeta.Thanos.Downsample.Resolution == 5*60*1000 { // data currently 5m resolution, downsample if range >= 10 days
untilComp = (time.Duration(10*24*60*60*1000*time.Millisecond) - timeRange).String()
}
var labels []string
for _, key := range getKeysAlphabetically(blockMeta.Thanos.Labels) {
labels = append(labels, fmt.Sprintf("%s=%s", key, blockMeta.Thanos.Labels[key]))
}
var line []string
line = append(line, blockMeta.ULID.String())
line = append(line, time.Unix(blockMeta.MinTime/1000, 0).Format("02-01-2006 15:04:05"))
line = append(line, time.Unix(blockMeta.MaxTime/1000, 0).Format("02-01-2006 15:04:05"))
line = append(line, timeRange.String())
line = append(line, untilComp)
line = append(line, p.Sprintf("%d", blockMeta.Stats.NumSeries))
line = append(line, p.Sprintf("%d", blockMeta.Stats.NumSamples))
line = append(line, p.Sprintf("%d", blockMeta.Stats.NumChunks))
line = append(line, p.Sprintf("%d", blockMeta.Compaction.Level))
line = append(line, p.Sprintf("%t", blockMeta.Compaction.Failed))
line = append(line, strings.Join(labels, ","))
line = append(line, time.Duration(blockMeta.Thanos.Downsample.Resolution*int64(time.Millisecond)).String())
line = append(line, string(blockMeta.Thanos.Source))
lines = append(lines, line)
}
var sortByColNum []int
for _, col := range sortBy {
index := getIndex(header, col)
if index == -1 {
return fmt.Errorf("column %s not found", col)
}
sortByColNum = append(sortByColNum, index)
}
t := Table{Header: header, Lines: lines, SortIndices: sortByColNum}
sort.Sort(t)
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(t.Header)
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetCenterSeparator("|")
table.SetAutoWrapText(false)
table.SetReflowDuringAutoWrap(false)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.AppendBulk(t.Lines)
table.Render()
return nil
}
func getKeysAlphabetically(labels map[string]string) []string {
var keys []string
for k := range labels {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// matchesSelector checks if blockMeta contains every label from
// the selector with the correct value
func matchesSelector(blockMeta *metadata.Meta, selectorLabels labels.Labels) bool {
for _, l := range selectorLabels {
if v, ok := blockMeta.Thanos.Labels[l.Name]; !ok || v != l.Value {
return false
}
}
return true
}
// getIndex calculates the index of s in strs
func getIndex(strs []string, s string) int {
for i, col := range strs {
if col == s {
return i
}
}
return -1
}
type Table struct {
Header []string
Lines [][]string
SortIndices []int
}
func (t Table) Len() int { return len(t.Lines) }
func (t Table) Swap(i, j int) { t.Lines[i], t.Lines[j] = t.Lines[j], t.Lines[i] }
func (t Table) Less(i, j int) bool {
for _, index := range t.SortIndices {
if t.Lines[i][index] == t.Lines[j][index] {
continue
}
return compare(t.Lines[i][index], t.Lines[j][index])
}
return compare(t.Lines[i][0], t.Lines[j][0])
}
func compare(s1, s2 string) bool {
s1Time, s1Err := time.Parse("02-01-2006 15:04:05", s1)
s2Time, s2Err := time.Parse("02-01-2006 15:04:05", s2)
if s1Err != nil || s2Err != nil {
return s1 < s2
}
return s1Time.Before(s2Time)
}