forked from thanos-io/thanos
/
tsdb.go
189 lines (167 loc) · 5.23 KB
/
tsdb.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
package store
import (
"context"
"math"
"sort"
"github.com/go-kit/kit/log"
"github.com/improbable-eng/thanos/pkg/component"
"github.com/improbable-eng/thanos/pkg/runutil"
"github.com/improbable-eng/thanos/pkg/store/storepb"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/tsdb"
"github.com/prometheus/tsdb/chunkenc"
"github.com/prometheus/tsdb/labels"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// TSDBStore implements the store API against a local TSDB instance.
// It attaches the provided external labels to all results. It only responds with raw data
// and does not support downsampling.
type TSDBStore struct {
logger log.Logger
db *tsdb.DB
component component.SourceStoreAPI
labels labels.Labels
}
// NewTSDBStore creates a new TSDBStore.
func NewTSDBStore(logger log.Logger, reg prometheus.Registerer, db *tsdb.DB, component component.SourceStoreAPI, externalLabels labels.Labels) *TSDBStore {
if logger == nil {
logger = log.NewNopLogger()
}
return &TSDBStore{
logger: logger,
db: db,
component: component,
labels: externalLabels,
}
}
// Info returns store information about the Prometheus instance.
func (s *TSDBStore) Info(ctx context.Context, r *storepb.InfoRequest) (*storepb.InfoResponse, error) {
res := &storepb.InfoResponse{
Labels: make([]storepb.Label, 0, len(s.labels)),
StoreType: s.component.ToProto(),
MinTime: 0,
MaxTime: math.MaxInt64,
}
if blocks := s.db.Blocks(); len(blocks) > 0 {
res.MinTime = blocks[0].Meta().MinTime
}
for _, l := range s.labels {
res.Labels = append(res.Labels, storepb.Label{
Name: l.Name,
Value: l.Value,
})
}
return res, nil
}
// Series returns all series for a requested time range and label matcher. The returned data may
// exceed the requested time bounds.
func (s *TSDBStore) Series(r *storepb.SeriesRequest, srv storepb.Store_SeriesServer) error {
match, newMatchers, err := labelsMatches(s.labels, r.Matchers)
if err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}
if !match {
return nil
}
matchers, err := translateMatchers(newMatchers)
if err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}
// TODO(fabxc): An improvement over this trivial approach would be to directly
// use the chunks provided by TSDB in the response.
// But since the sidecar has a similar approach, optimizing here has only
// limited benefit for now.
q, err := s.db.Querier(r.MinTime, r.MaxTime)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
defer runutil.CloseWithLogOnErr(s.logger, q, "close tsdb querier series")
set, err := q.Select(matchers...)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
var respSeries storepb.Series
for set.Next() {
series := set.At()
c, err := s.encodeChunk(series.Iterator())
if err != nil {
return status.Errorf(codes.Internal, "encode chunk: %s", err)
}
respSeries.Labels = s.translateAndExtendLabels(series.Labels(), s.labels)
respSeries.Chunks = append(respSeries.Chunks[:0], c)
if err := srv.Send(storepb.NewSeriesResponse(&respSeries)); err != nil {
return status.Error(codes.Aborted, err.Error())
}
}
return nil
}
func (s *TSDBStore) encodeChunk(it tsdb.SeriesIterator) (storepb.AggrChunk, error) {
chk := chunkenc.NewXORChunk()
app, err := chk.Appender()
if err != nil {
return storepb.AggrChunk{}, err
}
var mint int64
for i := 0; it.Next(); i++ {
if i == 0 {
mint, _ = it.At()
}
app.Append(it.At())
}
if it.Err() != nil {
return storepb.AggrChunk{}, errors.Wrap(it.Err(), "read series")
}
maxt, _ := it.At()
return storepb.AggrChunk{
MinTime: mint,
MaxTime: maxt,
Raw: &storepb.Chunk{Type: storepb.Chunk_XOR, Data: chk.Bytes()},
}, nil
}
// translateAndExtendLabels transforms a metrics into a protobuf label set. It additionally
// attaches the given labels to it, overwriting existing ones on collision.
func (s *TSDBStore) translateAndExtendLabels(m, extend labels.Labels) []storepb.Label {
lset := make([]storepb.Label, 0, len(m)+len(extend))
for _, l := range m {
if extend.Get(l.Name) != "" {
continue
}
lset = append(lset, storepb.Label{
Name: l.Name,
Value: l.Value,
})
}
for _, l := range extend {
lset = append(lset, storepb.Label{
Name: l.Name,
Value: l.Value,
})
}
sort.Slice(lset, func(i, j int) bool {
return lset[i].Name < lset[j].Name
})
return lset
}
// LabelNames returns all known label names.
func (s *TSDBStore) LabelNames(ctx context.Context, r *storepb.LabelNamesRequest) (
*storepb.LabelNamesResponse, error,
) {
return nil, status.Error(codes.Unimplemented, "not implemented")
}
// LabelValues returns all known label values for a given label name.
func (s *TSDBStore) LabelValues(ctx context.Context, r *storepb.LabelValuesRequest) (
*storepb.LabelValuesResponse, error,
) {
q, err := s.db.Querier(math.MinInt64, math.MaxInt64)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
defer runutil.CloseWithLogOnErr(s.logger, q, "close tsdb querier label values")
res, err := q.LabelValues(r.Label)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &storepb.LabelValuesResponse{Values: res}, nil
}