-
Notifications
You must be signed in to change notification settings - Fork 4
/
unwrap.go
343 lines (320 loc) · 9.65 KB
/
unwrap.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
package main
import (
"context"
"fmt"
"github.com/efficientgo/tools/extkingpin"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/oklog/ulid"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/relabel"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb"
"github.com/prometheus/prometheus/tsdb/chunkenc"
tsdb_errors "github.com/prometheus/prometheus/tsdb/errors"
"github.com/thanos-io/objstore"
"github.com/thanos-io/objstore/client"
"github.com/thanos-io/thanos/pkg/block"
"github.com/thanos-io/thanos/pkg/block/metadata"
"github.com/thanos-io/thanos/pkg/model"
"github.com/thanos-io/thanos/pkg/runutil"
"gopkg.in/yaml.v2"
"math"
"os"
"path"
"path/filepath"
"slices"
"strings"
"sync"
"time"
)
const metaExtLabels = "__meta_ext_labels"
func unwrap(bkt objstore.Bucket, unwrapRelabel extkingpin.PathOrContent, unwrapMetaRelabel extkingpin.PathOrContent, recursive bool, dir *string, wait *time.Duration, unwrapDry bool, outConfig *extkingpin.PathOrContent, maxTime *model.TimeOrDurationValue, unwrapSrc *string, logger log.Logger) (err error) {
relabelContentYaml, err := unwrapRelabel.Content()
if err != nil {
return fmt.Errorf("get content of relabel configuration: %w", err)
}
var relabelConfig []*relabel.Config
if err := yaml.Unmarshal(relabelContentYaml, &relabelConfig); err != nil {
return fmt.Errorf("parse relabel configuration: %w", err)
}
metaRelabelContentYaml, err := unwrapMetaRelabel.Content()
if err != nil {
return fmt.Errorf("get content of meta-relabel configuration: %w", err)
}
var metaRelabel []*relabel.Config
if err := yaml.Unmarshal(metaRelabelContentYaml, &metaRelabel); err != nil {
return fmt.Errorf("parse relabel configuration: %w", err)
}
objStoreYaml, err := outConfig.Content()
if err != nil {
return err
}
dst, err := client.NewBucket(logger, objStoreYaml, "thanos-kit")
if err != nil {
return err
}
processBucket := func() error {
begin := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
blocks, err := getBlocks(ctx, bkt, recursive, maxTime)
if err != nil {
return err
}
for _, b := range blocks {
if *unwrapSrc != "" {
m, err := getMeta(ctx, b, bkt, logger)
if bkt.IsObjNotFoundErr(err) {
continue // Meta.json was deleted between bkt.Exists and here.
}
if err != nil {
return err
}
if string(m.Thanos.Source) != *unwrapSrc {
continue
}
}
if err := unwrapBlock(bkt, b, relabelConfig, metaRelabel, *dir, unwrapDry, dst, logger); err != nil {
return err
}
}
level.Info(logger).Log("msg", "bucket iteration done", "blocks", len(blocks), "duration", time.Since(begin), "sleeping", wait)
return nil
}
if *wait == 0 {
return processBucket()
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return runutil.Repeat(*wait, ctx.Done(), func() error {
return processBucket()
})
}
func unwrapBlock(bkt objstore.Bucket, b Block, relabelConfig []*relabel.Config, metaRelabel []*relabel.Config, dir string, unwrapDry bool, dst objstore.Bucket, logger log.Logger) error {
if err := runutil.DeleteAll(dir); err != nil {
return fmt.Errorf("unable to cleanup cache folder %s: %w", dir, err)
}
inDir := path.Join(dir, "in")
outDir := path.Join(dir, "out")
matchAll := &labels.Matcher{
Name: "__name__",
Type: labels.MatchNotEqual,
Value: "",
}
// prepare input
ctxd, canceld := context.WithTimeout(context.Background(), 10*time.Minute)
defer canceld()
pb := objstore.NewPrefixedBucket(bkt, b.Prefix)
if err := downloadBlock(ctxd, inDir, b.Id.String(), pb, logger); err != nil {
return err
}
os.Mkdir(path.Join(inDir, "wal"), 0777)
origMeta, err := metadata.ReadFromDir(path.Join(inDir, b.Id.String()))
if err != nil {
return fmt.Errorf("fail to read meta.json for %s: %w", b.Id.String(), err)
}
lbls, keep := relabel.Process(labels.FromMap(origMeta.Thanos.Labels), metaRelabel...)
if !keep {
return nil
}
origMeta.Thanos.Labels = lbls.Map()
db, err := tsdb.OpenDBReadOnly(inDir, logger)
if err != nil {
return err
}
defer func() {
err = tsdb_errors.NewMulti(err, db.Close()).Err()
}()
q, err := db.Querier(context.Background(), 0, math.MaxInt64)
if err != nil {
return err
}
defer q.Close()
// prepare output
os.Mkdir(outDir, 0777)
duration := getCompatibleBlockDuration(math.MaxInt64) //todo
mw, err := newMultiBlockWriter(outDir, logger, duration, *origMeta)
if err != nil {
return err
}
// unwrap
ss := q.Select(false, nil, matchAll)
for ss.Next() {
series := ss.At()
rl, keep := relabel.Process(series.Labels(), relabelConfig...)
if !keep {
continue
}
lbs, extl := extractLabels(rl, strings.Split(rl.Get(metaExtLabels), ";"))
tdb, err := mw.getTenant(context.Background(), extl)
if err != nil {
return err
}
it := series.Iterator(nil)
for it.Next() == chunkenc.ValFloat {
ts, val := it.At()
if _, err := tdb.appender.Append(0, lbs, ts, val); err != nil {
return err
}
tdb.samples++
}
for it.Next() == chunkenc.ValFloatHistogram {
ts, fh := it.AtFloatHistogram()
if _, err := tdb.appender.AppendHistogram(0, lbs, ts, nil, fh); err != nil {
return err
}
tdb.samples++
}
for it.Next() == chunkenc.ValHistogram {
ts, h := it.AtHistogram()
if _, err := tdb.appender.AppendHistogram(0, lbs, ts, h, nil); err != nil {
return err
}
tdb.samples++
}
if it.Err() != nil {
return ss.Err()
}
}
if ss.Err() != nil {
return ss.Err()
}
if ws := ss.Warnings(); len(ws) > 0 {
return tsdb_errors.NewMulti(ws...).Err()
}
blocks, err := mw.flush(context.Background())
if unwrapDry {
level.Info(logger).Log("msg", "dry-run: skipping upload of created blocks and delete of original block", "ulids", fmt.Sprint(blocks), "orig", b.Id)
} else {
for _, id := range blocks {
begin := time.Now()
ctxu, cancelu := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancelu()
err = block.Upload(ctxu, logger, dst, filepath.Join(outDir, id.String()), metadata.SHA256Func)
if err != nil {
return fmt.Errorf("upload block %s: %v", id, err)
}
level.Info(logger).Log("msg", "uploaded block", "ulid", id, "duration", time.Since(begin))
}
level.Info(logger).Log("msg", "deleting original block", "ulid", b.Id)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
if err := block.Delete(ctx, logger, pb, b.Id); err != nil {
return fmt.Errorf("delete block %s%s: %v", b.Prefix, b.Id, err)
}
}
return nil
}
// extractLabels splits given labels to two sets: for given `names` and the rest without metaExtLabels preserving sort order
func extractLabels(ls labels.Labels, names []string) (res labels.Labels, el labels.Labels) {
slices.Sort(names)
i, j := 0, 0
for i < len(ls) && j < len(names) {
switch {
// https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config
// Labels starting with __ will be removed from the label set after target relabeling is completed.
case strings.HasPrefix(ls[i].Name, "__") && ls[i].Name != "__name__":
i++
case names[j] < ls[i].Name:
j++
case ls[i].Name < names[j]:
res = append(res, ls[i])
i++
default:
el = append(el, ls[i])
i++
j++
}
}
res = append(res, ls[i:]...)
return res, el
}
type MultiBlockWriter struct {
db *tsdb.DBReadOnly
origMeta metadata.Meta
blockSize int64 // in ms
tenants map[uint64]*tenant
logger log.Logger
dir string
mu sync.Mutex
}
type tenant struct {
appender storage.Appender
writer *tsdb.BlockWriter
samples int
extLables labels.Labels
}
// newMultiBlockWriter creates a new multi-tenant tsdb BlockWriter
func newMultiBlockWriter(dir string, logger log.Logger, blockSize int64, meta metadata.Meta) (*MultiBlockWriter, error) {
return &MultiBlockWriter{
blockSize: blockSize,
origMeta: meta,
tenants: make(map[uint64]*tenant),
logger: logger,
dir: dir,
}, nil
}
func (m *MultiBlockWriter) getTenant(ctx context.Context, lbls labels.Labels) (*tenant, error) {
id := lbls.Hash()
if _, ok := m.tenants[id]; !ok {
w, err := tsdb.NewBlockWriter(m.logger, m.dir, m.blockSize)
if err != nil {
return nil, err
}
m.mu.Lock()
m.tenants[id] = &tenant{
writer: w,
appender: w.Appender(ctx),
samples: 0,
extLables: lbls,
}
m.mu.Unlock()
}
// reduce Mem usage, commit appender
if m.tenants[id].samples > 5000 {
if err := m.commit(ctx, id); err != nil {
return nil, err
}
}
return m.tenants[id], nil
}
func (m *MultiBlockWriter) commit(ctx context.Context, id uint64) error {
err := m.tenants[id].appender.Commit()
m.mu.Lock()
defer m.mu.Unlock()
m.tenants[id].appender = m.tenants[id].writer.Appender(ctx)
m.tenants[id].samples = 0
return err
}
// flush writes all blocks and reset MultiBlockWriter tenants
func (m *MultiBlockWriter) flush(ctx context.Context) (ids []ulid.ULID, err error) {
m.mu.Lock()
defer m.mu.Unlock()
for _, t := range m.tenants {
if err := t.appender.Commit(); err != nil {
return nil, err
}
id, err := t.writer.Flush(ctx)
if err != nil {
return nil, err
}
ids = append(ids, id)
if err := t.writer.Close(); err != nil {
return nil, err
}
meta, err := metadata.ReadFromDir(path.Join(m.dir, id.String()))
if err != nil {
return nil, fmt.Errorf("read %s metadata: %w", id, err)
}
l := m.origMeta.Thanos.Labels
for _, e := range t.extLables {
l[e.Name] = e.Value
}
if err = writeThanosMeta(meta.BlockMeta, l, m.origMeta.Thanos.Downsample.Resolution, m.dir, m.logger); err != nil {
return nil, fmt.Errorf("write %s metadata: %w", id, err)
}
}
m.tenants = make(map[uint64]*tenant)
return ids, nil
}