-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
370 lines (313 loc) · 9.02 KB
/
client.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
package prometheus
import (
"fmt"
"sort"
"strings"
"sync"
"time"
"unsafe"
"github.com/prometheus/prometheus/prompb"
prom "github.com/prometheus/prometheus/prompb"
qdb "github.com/bureau14/qdb-api-go/v3"
"github.com/prometheus/common/model"
)
// Client represents a QuasarDB Prometheus client that knows how to read and
// write Promethus requests and responses
type Client struct {
ClusterURI string
Handle *qdb.HandleType
Logger func(string, ...interface{})
mutex sync.Mutex
}
// Write takes a slice prometheus Timeseries and writes them to QuasarDB
func (c *Client) Write(tses []prom.TimeSeries) error {
for _, ts := range tses {
var tableName string
var labelNames []string
var labelValues []string
for _, label := range ts.Labels {
if label.Name == model.MetricNameLabel {
tableName = fmt.Sprintf("$qdb.prom.%s", label.Value)
} else {
labelNames = append(labelNames, label.Name)
labelValues = append(labelValues, label.Value)
}
}
if tableName == "" {
return fmt.Errorf("Timeseries had no metric name")
}
handle, err := c.GetHandle()
if err != nil {
return fmt.Errorf("Failed to retrieve qdb handle: %s", err.Error())
}
err = c.EnsureTable(ts)
if err != nil {
return err
}
var tsBatchColInfo []qdb.TsBatchColumnInfo
for _, labelName := range labelNames {
tsBatchColInfo = append(tsBatchColInfo, qdb.NewTsBatchColumnInfo(tableName, labelName, int64(len(ts.Samples))))
}
tsBatchColInfo = append(tsBatchColInfo, qdb.NewTsBatchColumnInfo(tableName, "value", int64(len(ts.Samples))))
tsBatch, err := handle.TsBatch(tsBatchColInfo...)
if err != nil {
return fmt.Errorf("Failed to created qdb.TsBatch: %s", err.Error())
}
for _, sample := range ts.Samples {
timestamp := model.Time(sample.Timestamp).Time()
err = tsBatch.StartRow(timestamp)
if err != nil {
return err
}
var i int64
for _, col := range labelValues {
err = tsBatch.RowSetBlob(i, []byte(col))
if err != nil {
return err
}
i++
}
err = tsBatch.RowSetDouble(i, sample.Value)
if err != nil {
return err
}
}
if err != nil {
return fmt.Errorf("Failed to set TsBatch rows: %s", err.Error())
}
err = tsBatch.Push()
if err != nil {
return fmt.Errorf("Failed to flush TsBatch: %s", err.Error())
}
}
return nil
}
// GetHandle caches and returns an anonymous user qdb handle
func (c *Client) GetHandle() (*qdb.HandleType, error) {
c.mutex.Lock()
if c.Handle == nil {
handle, err := qdb.SetupHandle(c.ClusterURI, time.Duration(12)*time.Hour)
if err != nil {
return nil, err
}
c.Handle = &handle
}
c.mutex.Unlock()
return c.Handle, nil
}
// EnsureTable ensures the prometheus metric table and required columns exist
func (c *Client) EnsureTable(ts prom.TimeSeries) error {
var tableName string
var columnNames []string
for _, label := range ts.Labels {
labelName := label.GetName()
if labelName == model.MetricNameLabel {
tableName = label.GetValue()
} else {
columnNames = append(columnNames, labelName)
}
}
sort.Strings(columnNames)
if tableName == "" {
return fmt.Errorf("prometheus timeseries missing metric name")
}
handle, err := c.GetHandle()
if err != nil {
return err
}
table := handle.Timeseries(fmt.Sprintf("$qdb.prom.%s", tableName))
doubleCols, blobCols, _, _, _, err := table.Columns()
// Unexpected error
if err != nil && err != qdb.ErrAliasNotFound {
return err
}
// Timeseries doesn't exist so we create it
if err == qdb.ErrAliasNotFound {
var colsInfo []qdb.TsColumnInfo
for _, name := range columnNames {
colsInfo = append(colsInfo, qdb.NewTsColumnInfo(name, qdb.TsColumnBlob))
}
colsInfo = append(colsInfo, qdb.NewTsColumnInfo("value", qdb.TsColumnDouble))
err = table.Create(24*time.Hour, colsInfo...)
return err
}
// Add any missing prometheus labels as blob columns
var newColsInfo []qdb.TsColumnInfo
for _, label := range columnNames {
var hasColumn bool
for _, col := range blobCols {
if label == col.Name() {
hasColumn = true
}
}
if !hasColumn {
newColsInfo = append(newColsInfo, qdb.NewTsColumnInfo(label, qdb.TsColumnBlob))
}
}
var hasValueColumn bool
for _, col := range doubleCols {
if col.Name() == "value" {
hasValueColumn = true
}
}
if !hasValueColumn {
newColsInfo = append(newColsInfo, qdb.NewTsColumnInfo("value", qdb.TsColumnDouble))
}
// Table already has all the columns it needs
if len(newColsInfo) == 0 {
return nil
}
err = table.InsertColumns(newColsInfo...)
return err
}
// Read takes a Prometheus read request, fetches the corresponding data from the
// client's configured QuasarDB server daemon and returns Promethus read response
func (c *Client) Read(req *prom.ReadRequest) (*prom.ReadResponse, error) {
handle, err := c.GetHandle()
if err != nil {
return nil, err
}
labelsToSeries := map[string]*prom.TimeSeries{}
for _, query := range req.Queries {
qdbQuery, name, err := buildQuasarDbQuery(query)
if err != nil {
c.Logger("Failed to build query: %+v", *query)
return nil, err
}
q := handle.Query(qdbQuery)
table, err := q.Execute()
if err != nil {
c.Logger("Failed to execute query: %s", qdbQuery)
return nil, err
}
defer handle.Release(unsafe.Pointer(table))
// query only ever has one table result
colNames := table.ColumnsNames()
for _, row := range table.Rows() {
columns := table.Columns(row)
var (
time int64
value float64
labels = make(map[string]string)
)
// Read row values
for i, colName := range colNames {
if colName == "$timestamp" {
timestamp, err := columns[i].GetTimestamp()
if err != nil {
return nil, err
}
time = timestamp.UnixNano() / 1000000
} else if colName == "value" {
double, err := columns[i].GetDouble()
if err != nil {
return nil, err
}
value = double
} else if colName != "$table" {
blob, err := columns[i].GetBlob()
if err == nil {
labels[colName] = string(blob)
}
}
}
key := promTimeSeriesKey(name, labels)
ts, ok := labelsToSeries[key]
// Initialise timeseries if it doesn't exist yet
if !ok {
labelPairs := make([]prom.Label, 0, len(labels)+1)
labelPairs = append(labelPairs, prom.Label{
Name: model.MetricNameLabel,
Value: name,
})
for k, v := range labels {
labelPairs = append(labelPairs, prom.Label{
Name: k,
Value: v,
})
}
ts = &prompb.TimeSeries{
Labels: labelPairs,
Samples: make([]prom.Sample, 0, 100),
}
labelsToSeries[key] = ts
}
// Append samples
ts.Samples = append(ts.Samples, prom.Sample{
Timestamp: time,
Value: value,
})
}
}
resp := prom.ReadResponse{
Results: []*prom.QueryResult{
{
Timeseries: make([]*prom.TimeSeries, 0, len(labelsToSeries)),
},
},
}
// Build result
for _, ts := range labelsToSeries {
resp.Results[0].Timeseries = append(resp.Results[0].Timeseries, ts)
}
return &resp, nil
}
// buildQuasarDbQuery constructs the required QuasarDB SQL from a prometheus query
func buildQuasarDbQuery(q *prom.Query) (string, string, error) {
var query string
var metricName string
var tableName string
var whereConditions = make([]string, 0, len(q.Matchers)-1)
for _, matcher := range q.Matchers {
if matcher.Name == model.MetricNameLabel {
switch matcher.Type {
case prom.LabelMatcher_EQ:
metricName = matcher.Value
tableName = fmt.Sprintf("$qdb.prom.%s", matcher.Value)
case prom.LabelMatcher_NEQ:
return query, metricName, fmt.Errorf("unsupported matcher NOT EQ on metric name")
default:
return query, metricName, fmt.Errorf("unknown metric type %v", matcher.Type)
}
} else {
switch matcher.Type {
case prom.LabelMatcher_EQ:
condition := fmt.Sprintf("%s = '%s'", matcher.Name, matcher.Value)
whereConditions = append(whereConditions, condition)
case prom.LabelMatcher_NEQ:
condition := fmt.Sprintf("%s != '%s'", matcher.Name, matcher.Value)
whereConditions = append(whereConditions, condition)
default:
return query, metricName, fmt.Errorf("unknown metric type %v", matcher.Type)
}
}
}
if metricName == "" {
return query, metricName, fmt.Errorf("queries without a metric name are not supported")
}
var where string
if len(whereConditions) > 0 {
where = fmt.Sprintf(" WHERE %s ", strings.Join(whereConditions, " AND "))
}
query = fmt.Sprintf("SELECT * FROM %s%s", tableName, where)
return query, metricName, nil
}
// Helper methods
func newTimeFromUnixNs(timestamp int64) time.Time {
return model.Time(timestamp).Time()
}
// Creates a key unique to a set label key-value pairs
func promTimeSeriesKey(metric string, labels map[string]string) string {
// 0xff cannot occur in valid UTF-8 sequences, so use it as a separator.
separator := "\xff"
keys := make([]string, 0, len(labels))
for k := range labels {
keys = append(keys, k)
}
sort.Strings(keys)
pairs := make([]string, 0, len(labels))
for _, k := range keys {
pairs = append(pairs, k+separator+labels[k])
}
return metric + separator + strings.Join(pairs, separator)
}